iOS Question using cipher to encrypt/decrypt raw binary data

fransvlaarhoven

Active Member
Licensed User
Longtime User
Hello,

I want to encrypt raw binary data with cipher.

However, when decrypting the encrypted data, additional bytes are added to the result of the decryption.

The code below shows the problem:

B4X:
 Dim lp As Int
 Dim pw As String= "password"
 Dim unencrypted(16) As Byte
 For lp= 0 To 15
 unencrypted(lp)= lp
 Next
 'encrypt the data
 Dim encryptor As Cipher
 Dim encrypted() As Byte= encryptor.Encrypt(unencrypted, pw)
 'verify output
 Dim decryptor As Cipher
 Dim decrypted() As Byte= decryptor.Decrypt(encrypted, pw)
 If unencrypted.Length <> decrypted.Length Then
 LogColor("unencrypted.Length= " & unencrypted.Length, Colors.Blue)
 LogColor("decrypted.Length= " & decrypted.Length, Colors.Blue)
 Else
 For lp= 0 To unencrypted.Length-1
 If unencrypted(lp) <> decrypted(lp) Then
 LogColor(lp & " => unencrypted(lp) <> decrypted(lp)", Colors.Blue)
 End If
 Next
 End If

What am I doing wrong?
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
The encrypted data is padded with zeroes to complete a block of 16 bytes.

As you are working with raw binary data then you should store the data length together with the data itself. You can use this code:
B4X:
Private Sub Application_Start (Nav As NavigationController)
   NavControl = Nav
   Page1.Initialize("Page1")
   Page1.Title = "Page 1"
   Page1.RootPanel.Color = Colors.White
   NavControl.ShowPage(Page1)
   Dim secretData() As Byte = "asdadsd".GetBytes("utf8")
   Dim e() As Byte = Encrypt(secretData, "123")
   Dim d() As Byte = Decrypt(e, "123")
   Log(secretData.Length)
   Log(d.Length)
End Sub

Sub Encrypt(Data() As Byte, Password As String) As Byte()
   Dim encryptor As Cipher
   Dim ser As B4XSerializator
   Return encryptor.Encrypt(ser.ConvertObjectToBytes(Array(Data.Length, Data)), Password)
End Sub

Sub Decrypt (Data() As Byte, Password As String) As Byte()
   Dim encryptor As Cipher
   Dim ser As B4XSerializator
   Dim bc As ByteConverter
   Dim LengthAndData() As Object = ser.ConvertBytesToObject(encryptor.Decrypt(Data, Password))
   Dim buffer(LengthAndData(0)) As Byte
   bc.ArrayCopy(LengthAndData(1), 0, buffer, 0, buffer.Length)
   Return buffer
End Sub
 
Upvote 0

Similar Threads

Top