B4A Library B4XEncryption

Discussion in 'Additional libraries, classes and official updates' started by Erel, Dec 14, 2014.

  1. Erel

    Erel Administrator Staff Member Licensed User

    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:
    Code:
    Sub EncryptText(text As String, password As StringAs Byte()
       
    Dim c As B4XCipher
       
    Return c.Encrypt(text.GetBytes("utf8"), password)
    End Sub

    Sub DecryptText(EncryptedData() As Byte, password As StringAs 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"))
     

    Attached Files:

    Last edited: Apr 10, 2016
    JohnCody, Mashiane, zani and 7 others like this.
  2. MarcoRome

    MarcoRome Expert Licensed User

    Hi Erel.
    Is possible a little example.
    Thank you
     
    CanguroCode likes this.
  3. Quaki

    Quaki Member Licensed User

  4. Erel

    Erel Administrator Staff Member Licensed 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.
     
  5. MarcoRome

    MarcoRome Expert Licensed User

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


    this is code example:

    Code:
    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 StringAs 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
     
    koaunglay likes this.
  6. MarcoRome

    MarcoRome Expert Licensed User

    Hi all.

    I have this error when i Decrypt:

    Code:
    ** 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:

    Code:
    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 StringAs 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:

    Code:
    Sub Encrypt(testo As StringAs 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
     

    Attached Files:

    Argonc likes this.
  7. stu14t

    stu14t Active Member Licensed 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) ?
     
  8. Erel

    Erel Administrator Staff Member Licensed User

    Base64 is not an encryption method. It is an encoding. You can use StringUtils to encode / decode base 64 strings.

    You will not be able to use C# code with B4XEncryption.
     
    stu14t likes this.
  9. Erel

    Erel Administrator Staff Member Licensed User

    You cannot convert a random array of bytes to string:
    Code:
    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.
     
    RauchG and Argonc like this.
  10. MarcoRome

    MarcoRome Expert Licensed User

    Right work :)

    Event Button1_Click
    Code:
    'string_crypt = BytesToString(trasformobyte, 0, trasformobyte.Length, "UTF8") ' <----- This dont work
    string_crypt = encode.EncodeBase64(trasformobyte) ' <-------This is right
    Event Button2_Click
    Code:
    'risultato = Curs.GetString("testo").GetBytes("UTF8") '  <----- This dont work
    risultato = decode.DecodeBase64(Curs.GetString("testo")) ' ' <-------This is right
    Thank you ;)
     
    RauchG likes this.
  11. ivan.tellez

    ivan.tellez Active Member Licensed User

    "Base64 and Encryption" is the name of the agraham's library. @stu14t said he uses the AES mode of this lib.
     
  12. Erel

    Erel Administrator Staff Member Licensed User

    This library also uses AES for the encryption. The main advantage of this library is that it is simple to use and compatible with B4J B4XEncryption library and B4i iEncryption library.
     
  13. Stealth Pyro

    Stealth Pyro Member Licensed User

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

    Erel Administrator Staff Member Licensed User

    The salt itself will not help you as you also need the initialization vector and the exact encryption method. What do you need it for?
     
  15. omidaghakhani1368

    omidaghakhani1368 Well-Known Member Licensed User

    How use RSA algorithm in this library?
     
  16. Erel

    Erel Administrator Staff Member Licensed User

    See the first post. It describes the features in this library.
     
  17. atulindore

    atulindore Member Licensed 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 ..
     
  18. Erel

    Erel Administrator Staff Member Licensed User

  19. atulindore

    atulindore Member Licensed 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 ..
     
  20. Erel

    Erel Administrator Staff Member Licensed User

    You should use the Encryption library instead of B4XEncryption. B4XEncryption will only work with B4A, B4i and B4J.
     
    DonManfred and atulindore like this.
Loading...