B4J Question Encryption

besoft

Active Member
Licensed User
Longtime User
Greetings

I studied example of data encryption. Example function normally. I tried during the encryption and decryption of data to look at how they look.

Encryption

B4X:
  Dim s As String = "mystring"
        Dim b() As Byte = Cipher.Encrypt(s.GetBytes("UTF8"), "pwd")
    
        Dim test As String = BytesToString(b, 0, b.Length, "UTF8")
        Log(test)

Decryption

B4X:
Dim test_byte() As Byte = test.GetBytes("UTF8")
    
Dim bb() As Byte = Cipher.Decrypt(test_byte, "pwd")
Dim ss As String = BytesToString(bb, 0, bb.Length, "UTF8")

The problem is presumably in the conversion string back into a byte.
I get the following error:
B4X:
org.bouncycastle.crypto.DataLengthException: last block incomplete in decryption

Does anyone have any advice on how to convert encrypted string back into a byte?
thanks
 
Last edited:

EnriqueGonzalez

Expert
Licensed User
Longtime User
You must use Base 64 (StringUtils) to work with Encryption

B4X:
Dim test As String = BytesToString(b, 0, b.Length, "UTF8")

change it to

B4X:
Dim SU As StringUtils
Dim test As String = SU.EncodeBase64(b)

and this one:

B4X:
Dim test_byte() As Byte = test.GetBytes("UTF8")

to:

B4X:
Dim test_byte() As Byte = SU.DecodeBase64(test)

I hope it works!
 
Upvote 0
Top