B4A Library [B4X] B4XEncryption

Status
Not open for further replies.
This library allows you to encrypt or decrypt data using the AES encryption method.

It is simple to use and it is compatible with B4J jB4XEncryption library and B4i Encryption library (Encrypt and Decrypt method) which means that you can encrypt the data on one platform and decrypt it on a different platform.

Usage example:
B4X:
Sub EncryptText(text As String, password As String) As Byte()
   Dim c As B4XCipher
   Return c.Encrypt(text.GetBytes("utf8"), password)
End Sub

Sub DecryptText(EncryptedData() As Byte, password As String) As String
   Dim c As B4XCipher
   Dim b() As Byte = c.Decrypt(EncryptedData, password)
   Return BytesToString(b, 0, b.Length, "utf8")
End Sub

Dim encryptedData() As Byte = EncryptText("confidential", "123456")
Log(DecryptText(encryptedData, "123456"))

B4XPages example project is attached.
 

Attachments

  • Project.zip
    14 KB · Views: 730
Last edited:

MarcoRome

Expert
Licensed User
Longtime User
Thanks for that lib but what protocole is used in it ? Is it XTEA protocol
http://en.wikipedia.org/wiki/XTEA
And example would be very helpfull
Best regards

if you see this example : https://www.b4x.com/android/forum/threads/problem-to-crypt-simple-strings.47805/#content


this is code example:

B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim cifro As B4XCipher
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
   
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Dim test() As Byte
    Dim string_crypt As String
   
    test = Encrypt("vediamo una frase lunga con 123 e %&/")
    string_crypt = BytesToString(test, 0, test.Length, "UTF8")
    Log(string_crypt)
   
    Dim string_encrypt As String
    string_encrypt = Decrypt(test)
    Log(string_encrypt)
   
   
End Sub

Sub Encrypt(testo As String) As Byte()
    Dim ByteArray() As Byte
    ByteArray=cifro.Encrypt(testo.GetBytes("UTF8"), "xxxx")
    Return ByteArray
End Sub

Sub Decrypt(testo() As Byte) As String
    Dim ByteArray() As Byte
    ByteArray=cifro.Decrypt(testo, "xxxx")
    Return BytesToString(ByteArray, 0, ByteArray.Length, "UTF8")   
End Sub

Bye
Marco
 

MarcoRome

Expert
Licensed User
Longtime User
Hi all.

I have this error when i Decrypt:

B4X:
** Activity (main) Pause, UserClosed = false **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
<k*��J`�}:-���Tp(QM���;��ʝ�L�06(4
<k*��J`�}:-���Tp(QM���;��ʝ�L�06(4
Error occurred on line: 54 (main)
javax.crypto.IllegalBlockSizeException: last block incomplete in decryption
    at com.android.org.bouncycastle.jce.provider.JCEBlockCipher.engineDoFinal(JCEBlockCipher.java:697)
    at javax.crypto.Cipher.doFinal(Cipher.java:1111)
    at anywheresoftware.b4a.object.B4XEncryption.Decrypt(B4XEncryption.java:47)
    at b4a.example.cryptdb.main._decrypt(main.java:525)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:636)
    at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:302)
    at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:238)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:121)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:163)
    at anywheresoftware.b4a.BA.raiseEvent(BA.java:159)
    at anywheresoftware.b4a.objects.ViewWrapper$1.onClick(ViewWrapper.java:77)
    at android.view.View.performClick(View.java:4100)
    at android.view.View$PerformClick.run(View.java:17016)
    at android.os.Handler.handleCallback(Handler.java:615)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4838)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:642)
    at dalvik.system.NativeStart.main(Native Method)
** Activity (main) Pause, UserClosed = true **
** Activity (main) Resume **


This is code:

B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim crypto As B4XCipher
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Dim SQL1 As SQL
    Dim database As String
    Private Button1 As Button
    Private Button2 As Button
    Private EditText1 As EditText
    Private Label1 As Label
    Private Label2 As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("cryptdb")
   
    'Test crypto su DB
    'inizializzo il database
    database = DBUtils.CopyDBFromAssets ("crypt.db")
    SQL1.Initialize(database, "crypt.db", True)

End Sub

Sub Encrypt(testo As String) As Byte()
    Dim ByteArray() As Byte
    ByteArray=crypto.Encrypt(testo.GetBytes("UTF8"), "xxxxxx") ' This is line 54
    Return ByteArray
End Sub



Sub Decrypt(testo() As Byte) As String
    Dim ByteArray() As Byte
    ByteArray=crypto.Decrypt(testo, "xxxxxx")
    Return BytesToString(ByteArray, 0, ByteArray.Length, "UTF8")   
End Sub


Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub



Sub Button2_Click
        'Rileggo Valori dentro Configura
            'Lettura DB valori su una riga
            Dim Query As String
            Dim Curs As Cursor
           
            Dim risultato() As Byte
           
            Try
            Query = "SELECT * FROM crypto WHERE id = 1"
            Curs = SQL1.ExecQuery(Query)
            Curs.Position = 0
            risultato = Curs.GetString("testo").GetBytes("UTF8")
            Curs.Close
            Catch
            ToastMessageShow("Problem",True)
            End Try
           
            Dim vedi As String
            vedi = BytesToString(risultato, 0, risultato.Length, "UTF8")
           
            ToastMessageShow(vedi, True)
            LogColor(vedi, Colors.Red)
           
            Label1.Text = Decrypt(risultato)

End Sub

Sub Button1_Click
        Dim test As String
        test = EditText1.Text
        'test = test.Replace("'", "''") ' <------ In questo modo anche se presente l'apostrofo è ok ;)
       
        'Crypto stringa
        Dim trasformobyte() As Byte
        Dim string_crypt As String
       
        trasformobyte = Encrypt(test)
        string_crypt = BytesToString(trasformobyte, 0, trasformobyte.Length, "UTF8")
        Log(string_crypt)
       
        'Inserisco nel DB testo crypto
        SQL1.ExecNonQuery("UPDATE crypto SET testo ='" & string_crypt & "'")
       
       
        'Rileggo da DB
        Dim Query As String
        Dim Curs As Cursor
       
        Dim risultato() As Byte
       
        Try
        Query = "SELECT * FROM crypto WHERE id = 1"
        Curs = SQL1.ExecQuery(Query)
        Curs.Position = 0
        'Inserisco nella label2 testo crypto
        risultato = Curs.GetString("testo").GetBytes("UTF8")
        Curs.Close
        Catch
        ToastMessageShow("Problem",True)
        End Try
       
        Label2.Text = BytesToString(risultato, 0, risultato.Length, "UTF8")
       
   
       
End Sub

i have error here:

B4X:
Sub Encrypt(testo As String) As Byte()
    Dim ByteArray() As Byte
    ByteArray=crypto.Encrypt(testo.GetBytes("UTF8"), "xxxxxx") ' <---------------------------- This is line 54
    Return ByteArray
End Sub

in attachment file project.
Any idea ??
Thank you
 

Attachments

  • TestCryptDB.zip
    67 KB · Views: 667

stu14t

Active Member
Licensed User
Longtime User
Erel, I'm using agraham's Base64 encryption lib in AES mode, is this lib more efficient?

And, I'm reading into a C# program and I've seen some decryption issues between android and .Net. Can I use the same C# code (that works at the moment) ?
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
I have this error when i Decrypt:
You cannot convert a random array of bytes to string:
B4X:
string_crypt = BytesToString(trasformobyte, 0, trasformobyte.Length, "UTF8")
These bytes do not represent a real string.

You can use StringUtils.EncodeBase64 to convert it to string.
 

MarcoRome

Expert
Licensed User
Longtime User
Right work :)

Event Button1_Click
B4X:
'string_crypt = BytesToString(trasformobyte, 0, trasformobyte.Length, "UTF8") ' <----- This dont work
string_crypt = encode.EncodeBase64(trasformobyte) ' <-------This is right

Event Button2_Click
B4X:
'risultato = Curs.GetString("testo").GetBytes("UTF8") '  <----- This dont work
risultato = decode.DecodeBase64(Curs.GetString("testo")) ' ' <-------This is right

Thank you ;)
 

Nostrildumbass

Member
Licensed User
Longtime User
It uses AES with a random salt and random IV. The salt and IV (which are not considered sensitive information) are saved at the beginning of the data.

Just using this for the first time in my application. Is there any way to return the salt that was generated?
 

atulindore

Member
Licensed User
Longtime User
Hi Erel
I am not able to find this b4xEncryption lib on wiki.
Is it not listed on Wiki. I wanted to read / understand this lib so that I can use it in my app ..
 

atulindore

Member
Licensed User
Longtime User
Actually I need to encrypt data in B4a and decrypt in oracle..

using B4xEncryption I can encrypt data but is it AES128 or AES256 bit encryption ? Need details of encryption .
because with same logic I need to decrypt in oracle.

In your first post also no details are given for this lib.

Pls help ..
 
Status
Not open for further replies.
Top