B4J Question [Cipher][Encryption] Why this code runs in B4A but not in B4J??

Dadaista

Active Member
Licensed User
Longtime User
Hi all

I've this code that runs in B4A:
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(11, 22, 33, 44, 55, 66, 77, 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

In B4J fails in this line:
B4X:
data = c.Encrypt(data, kg.Key, True)


Log says:
B4X:
java.security.InvalidKeyException: Invalid key length: 16 bytes

What's wrong??o_Oo_Oo_O
 

Daestrum

Expert
Licensed User
Longtime User
I think your key length is wrong
it needs to be '123456789012345678901234'

Extract from my working code
B4X:
...
	Dim code As String = Encrypt("fred was here")
	mykey = "123456789012345678901234"
	Log(code)
	Log(Decrypt(code))
End Sub
Sub Encrypt(dataToEncrypt As String ) As String
   Dim kg As KeyGenerator
   Dim c As Cipher
   Dim B64 As Base64
   Dim data() As Byte
   Dim iv() As Byte
   iv = Array As Byte(211, 5, 233, 24, 55, 166, 7, 88)
   c.Initialize("DESede/CBC/PKCS5Padding")   
   c.InitialisationVector = iv
   kg.Initialize("DESede")
   kg.KeyFromBytes(mykey.GetBytes("ASCII"))
   data = c.Encrypt(dataToEncrypt.GetBytes("ASCII"), 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() As Byte
   Dim iv() 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(mykey.GetBytes("ASCII"))
   data = c.Decrypt(B64.DecodeStoB(encryptedData), kg.Key, True)  
   Return bconv.StringFromBytes(data, "ASCII")
End Sub
 
Last edited:
Upvote 0

Daestrum

Expert
Licensed User
Longtime User
Not sure as Android expects DESede key to be 24 bytes long too.
 
Last edited:
Upvote 0

Dadaista

Active Member
Licensed User
Longtime User
Now I have to change the code, the files codificated and the codification of the files in the android app:eek::eek:... madness!! LOL o_O:confused:o_O:confused:

Thx again Daestrum!!!!!:):)
 
Upvote 0

Dadaista

Active Member
Licensed User
Longtime User
Wow, it is so simple Erel.
I was changed all the code affected last night and works. I do not want change it again but I will use B4XEncryption in future projects

Thx Erel
 
Upvote 0
Top