B4J Question Use encryption data in b4a

Bel

Member
Licensed User
Hi
I need to use encryption data via b4j in b4a
I use below code but get error 16 byte
The encrypted data shouldn't use with anyone because it is secret
B4X:
Sub Encrypt(dataToEncrypt As String ) As String

   Dim kg As KeyGenerator
   Dim c As Cipher
   Dim B64 As Base64
   Dim bconv As ByteConverter

   Dim data(0) As Byte
   Dim iv(0) As Byte
   iv = Array As Byte(211, 5, 233, 24, 55, 166, 7, 88) ' 16 bytes for AES
     
   c.Initialize("DESEDE/CBC/PKCS5Padding")   
   c.InitialisationVector = iv
   kg.Initialize("DESEDE")
  
   kg.KeyFromBytes(bconv.StringToBytes("1234567890123456","ASCII"))
   data = bconv.StringToBytes(dataToEncrypt, "ASCII")     
   data = c.Encrypt(data, kg.Key, True)           

   Return B64.EncodeBtoS(data, 0, data.Length)
  
End Sub

Sub Decrypt(encryptedData As String ) As String

   Dim kg As KeyGenerator
   Dim c As Cipher
   Dim B64 As Base64
   Dim bconv As ByteConverter

   Dim data(0) As Byte
   Dim iv(0) As Byte
   iv = Array As Byte(211, 5, 233, 24, 55, 166, 7, 88) ' 16 bytes for AES
     
   c.Initialize("DESEDE/CBC/PKCS5Padding")   
   c.InitialisationVector = iv
   kg.Initialize("DESEDE")   
   kg.KeyFromBytes(bconv.StringToBytes("1234567890123456","ASCII"))
  
  
   data = B64.DecodeStoB(encryptedData)
   data = c.Decrypt(data, kg.Key, True)  

   Return bconv.StringFromBytes(data, "ASCII")

End Sub
 

Daestrum

Expert
Licensed User
Longtime User
Your key length is wrong instead of
B4X:
"1234567890123456"
you need
B4X:
"123456789012345678901234"
as the key has to be 24 Bytes

Also you can use
B4X:
kg.KeyFromBytes("123456789012345678901234".GetBytes("ASCII"))
 
  • Like
Reactions: Bel
Upvote 0

Bel

Member
Licensed User
Hi Thank you very much.
This lib is great.
I use below code and can encrypt data but cannot decrypt and get error
B4X:
    If r1.Selected = True Then
        Dim rs() As Byte
        rs = b4x.Encrypt(txtval.Text.GetBytes("UTF8"),"123")
        txtoutput.Text = BytesToString(rs,0,rs.Length,"UTF-8")
    Else
        Dim rs1() As Byte
        rs1 = b4x.Decrypt(txtval.Text.GetBytes("UTF8"),"123")
        txtoutput.Text = BytesToString(rs1,0,rs1.Length,"UTF-8")
    End If

error is :
org.bouncycastle.crypto.DataLengthException: last block incomplete in decryption
 
Upvote 0
Top