B4J Question .net code to B4J

aaronk

Well-Known Member
Licensed User
Longtime User
Hi,

I am trying to the AES encryption and deception working in my B4J app.

I thought I had this working in the past, but looks like I didn't get it fully working after all.

I have been told that the AES uses AES-128 in ECB mode.

I have been told the following .net code works:

B4X:
Public Class AES
 
    Dim cAES As RijndaelManaged
 
    Public Sub New(ByVal AESkey As Byte())
 
        Dim InitVector() As Byte = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
 
        cAES = New RijndaelManaged
        cAES.BlockSize = 128
        cAES.KeySize = 128
        cAES.Mode = CipherMode.ECB
        cAES.IV = InitVector
        cAES.Padding = PaddingMode.Zeros
        cAES.Key = AESkey
 
    End Sub
 
    Public Sub Decrypt(ByRef cBytes As Byte(), ByVal NumBytes As Integer)
 
        Dim PlainBytes(IOBuffSize) As Byte
        Dim i As Integer
 
        Dim cDecryptor As ICryptoTransform = cAES.CreateDecryptor()
 
        ' Skip over the first 13 bytes - they are already in the plain.
        For i = 13 To NumBytes - 16 Step 16
            cDecryptor.TransformBlock(cBytes, i, 16, PlainBytes, i)
        Next
        Array.Copy(PlainBytes, 13, cBytes, 13, NumBytes - 13)
 
    End Sub
 
    Public Sub Encrypt(ByRef cBytes As Byte(), ByRef NumBytes As Integer)
 
        Dim EncryptedBytes(IOBuffSize) As Byte
        Dim i As Integer
 
        ' pad to a multiple of 16
        Dim numPadBytes As Integer = 16 - ((NumBytes - 13) Mod 16)
        ReDim Preserve cBytes(NumBytes + numPadBytes - 1)
        For i = NumBytes To NumBytes + numPadBytes - 1
            cBytes(i) = 0
        Next i
        NumBytes += numPadBytes
 
        Dim cEncryptor As ICryptoTransform = cAES.CreateEncryptor()
 
        ' Skip over the first 13 bytes - they are left in the plain.
        For i = 13 To NumBytes - 1 Step 16
            cEncryptor.TransformBlock(cBytes, i, 16, EncryptedBytes, i)
        Next
        Array.Copy(EncryptedBytes, 13, cBytes, 13, NumBytes - 13)
 
    End Sub
 
End Class

The data I need to decrypt (which is sent from the product in the field) is sent to my B4J app as a UDP message.

I tried using the following B4J code to decrypt the message:

B4X:
Private Sub RMSockUDP_PacketArrived (Packet As UDPPacket)
    Decrypt(Packet.Data)
End Sub

Sub Decrypt(value() As Byte) As String
    Try
        Dim raw() As Byte = value
        bb.Initialize
        bb.Append(raw)
        Dim binaryflag() As Byte = Array As Byte(0x33, 0x36, 0x37, 0x30, 0x42, 0x42, 0x39, 0x46, 0x2f,0x2f,0x31,0x2f,0x2f)
        If bb.IndexOf(binaryflag) > -1 Then
            Dim msgbytes() As Byte = bb.SubArray2(13,bb.IndexOf2(Array As Byte(0x0),13))
        End If

        kg.Initialize("AES")
        kg.KeyFromBytes("0123456789ABCDEF".GetBytes("UTF8")) ' the key to encrypt the message was 0123456789ABCDEF
        C.Initialize("AES/ECB/NoPadding")
        msgbytes = C.Decrypt(msgbytes, kg.Key, False)
        
        Return BConv.StringFromBytes(msgbytes, "UTF8").Trim
    Catch
        Log("Error: " & LastException.message)
    End Try
End Sub

Using my B4J code above it shows the following error:
Error: java.lang.IllegalArgumentException: Null input buffer

Based on the .Net code above, is the B4J code correct or have I done something wrong ?

I am guessing I have done something wrong since it's showing the above error, and I can't work it out.
 

aaronk

Well-Known Member
Licensed User
Longtime User
full error message.
Error occurred on line: 145 (RMSocket)
java.lang.IllegalArgumentException: Null input buffer
at javax.crypto.Cipher.doFinal(Cipher.java:2161)
at anywheresoftware.b4a.agraham.encryption.CipherWrapper.doFinal(CipherWrapper.java:140)
at anywheresoftware.b4a.agraham.encryption.CipherWrapper.Decrypt(CipherWrapper.java:150)
at b4j.example.rmsocket._decrypt(rmsocket.java:640)
at b4j.example.rmsocket._rmsockudp_packetarrived(rmsocket.java:1004)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:632)
at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:237)
at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:167)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:91)
at anywheresoftware.b4a.shell.ShellBA.raiseEvent2(ShellBA.java:98)
at anywheresoftware.b4a.BA$3.run(BA.java:247)
at anywheresoftware.b4a.keywords.SimpleMessageLoop.runMessageLoop(SimpleMessageLoop.java:30)
at anywheresoftware.b4a.StandardBA.startMessageLoop(StandardBA.java:26)
at anywheresoftware.b4a.shell.ShellBA.startMessageLoop(ShellBA.java:119)
at anywheresoftware.b4a.keywords.Common.StartMessageLoop(Common.java:153)
at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:309)
at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:167)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:91)
at anywheresoftware.b4a.shell.ShellBA.raiseEvent2(ShellBA.java:98)
at anywheresoftware.b4a.BA.raiseEvent(BA.java:78)
at b4j.example.main.main(main.java:29)

Line 145 is:

B4X:
msgbytes = C.Decrypt(msgbytes, kg.Key, False)

You are missing the initialization vector.

B4X:
Dim iv(16) As Byte
C.InitializationVector = iv
'and set UseIV parameter to true
Not 100% sure on where to use that based on my code?
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
Not 100% sure on where to use that based on my code?
try
B4X:
       C.Initialize("AES/ECB/NoPadding")
Dim iv(16) As Byte
C.InitializationVector = iv
        msgbytes = C.Decrypt(msgbytes, kg.Key, False)
 
Upvote 0

aaronk

Well-Known Member
Licensed User
Longtime User
try
B4X:
C.Initialize("AES/ECB/NoPadding")
Dim iv(16) As Byte
C.InitializationVector = iv
        msgbytes = C.Decrypt(msgbytes, kg.Key, False)

I tried that but it comes up saying Unknown Member: InitializationVector.

I have dimmed:
B4X:
Dim C As Cipher   ' in Process_Globals
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
Upvote 0

OliverA

Expert
Licensed User
Longtime User
Using my B4J code above it shows the following error:
Based on the .Net code above, is the B4J code correct or have I done something wrong ?
Even though you test for a flag in you incoming message, you don't really check it, since even if no flag is found, you just blindly de-encrypt. Add more logging to your code so you know what is going on.
B4X:
Sub Decrypt(value() As Byte) As String
    Try
        Dim raw() As Byte = value
        bb.Initialize
        bb.Append(raw)
        Dim binaryflag() As Byte = Array As Byte(0x33, 0x36, 0x37, 0x30, 0x42, 0x42, 0x39, 0x46, 0x2f,0x2f,0x31,0x2f,0x2f)
        If bb.IndexOf(binaryflag) > -1 Then
            Dim msgbytes() As Byte = bb.SubArray2(13,bb.IndexOf2(Array As Byte(0x0),13))
            If msgbytes.Legth > 0 Then
                Log("Found a message!")
                kg.Initialize("AES") '<--- since kg is a class global (I don't see it dim'ed here), this can be done outside of this method
                kg.KeyFromBytes("0123456789ABCDEF".GetBytes("UTF8")) ' the key to encrypt the message was 0123456789ABCDEF '<- again, has to be only done once,
                    ' unless you change password constantly
                C.Initialize("AES/ECB/NoPadding")  '<--- again, can be done outside of this method
                msgbytes = C.Decrypt(msgbytes, kg.Key, False)
       
                Return BConv.StringFromBytes(msgbytes, "UTF8").Trim
            Else
                Log("Found message, but had no content!!!!")
                Return ""'
            End If
        Else
            Log("Did not find my binary flag!!!!!")
            Return ""
        End If


    Catch
        Log("Error: " & LastException.message)
    End Try
End Sub
Note: Untested code
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
AES/ECB/NoPadding
The NoPadding is not the same as
cAES.Padding = PaddingMode.Zeros
Out of the box, ZeroBytePadding is not provided by Java's JDK and you have to also use BouncyCastle. Looks like this issue was worked on here
https://www.b4x.com/android/forum/threads/aes128-ecb-decrypt.108828/
with the additional caveat that if you us a non OpenJDK based Java (i.e. Oracle), you also will run into this issue
https://www.b4x.com/android/forum/threads/cannot-merge-external-library.109003/
 
Upvote 0

aaronk

Well-Known Member
Licensed User
Longtime User
if you can upload a base 64 string with the encrypted data and the password then it will be easier to help.

When I receive the UDP message I did:

B4X:
Dim msg1 As String     ' This will hold the incoming message
    msg1 = BytesToString(Packet.Data, Packet.Offset, Packet.Length, "UTF8")
   
    Log(msg1)

It logs:

4A2285A7//1//oB��ȵ��R��Mܨ^��=�uI���+ �ob##��t�6)�y�u��d��q{�ۺ�Y��

This shows the correct message being received.

The part 4A2285A7//1// is in plan text and the rest is meant to be encrypted. (I can hear in the background, "never convert random bytes to string")
However the last part of the message after //1// this is the encrypted data (in binary) which I am trying to decrypt which is part of the UDP packet being recevied.

The Key used was 0123456789ABCDEF

The .Net code is meant to decrypt the message. Which I am trying to figure out.

Even though you test for a flag in you incoming message, you don't really check it, since even if no flag is found, you just blindly de-encrypt. Add more logging to your code so you know what is going on.
B4X:
Sub Decrypt(value() As Byte) As String
    Try
        Dim raw() As Byte = value
        bb.Initialize
        bb.Append(raw)
        Dim binaryflag() As Byte = Array As Byte(0x33, 0x36, 0x37, 0x30, 0x42, 0x42, 0x39, 0x46, 0x2f,0x2f,0x31,0x2f,0x2f)
        If bb.IndexOf(binaryflag) > -1 Then
            Dim msgbytes() As Byte = bb.SubArray2(13,bb.IndexOf2(Array As Byte(0x0),13))
            If msgbytes.Legth > 0 Then
                Log("Found a message!")
                kg.Initialize("AES") '<--- since kg is a class global (I don't see it dim'ed here), this can be done outside of this method
                kg.KeyFromBytes("0123456789ABCDEF".GetBytes("UTF8")) ' the key to encrypt the message was 0123456789ABCDEF '<- again, has to be only done once,
                    ' unless you change password constantly
                C.Initialize("AES/ECB/NoPadding")  '<--- again, can be done outside of this method
                msgbytes = C.Decrypt(msgbytes, kg.Key, False)
     
                Return BConv.StringFromBytes(msgbytes, "UTF8").Trim
            Else
                Log("Found message, but had no content!!!!")
                Return ""'
            End If
        Else
            Log("Did not find my binary flag!!!!!")
            Return ""
        End If


    Catch
        Log("Error: " & LastException.message)
    End Try
End Sub
Note: Untested code
This logs: "Did not find my binary flag!!!!!"

you have to also use BouncyCastle.
I tried that but couldn't get it to work correctly. Here is the code I tried (might of done it wrong?):

B4X:
Sub De(packet As UDPPacket)

    Dim joSecurity As JavaObject
    joSecurity.InitializeStatic("java.security.Security")
#if B4J
    Dim jo As JavaObject
    jo.InitializeNewInstance("org.bouncycastle.jce.provider.BouncyCastleProvider", Null)
    joSecurity.RunMethod("addProvider", Array As Object (jo))
#else if B4A
    ' Seems to just work as of Android 5.1 (oldest version I have)
    '    Dim jo As JavaObject
    '    jo.InitializeNewInstance("org.spongycastle.jce.provider.BouncyCastleProvider", Null)
    '    joSecurity.RunMethod("insertProviderAt", Array As Object (jo, 1))
#else
    LOG("ERROR: UNSUPPORTED PLATFORM")
    Return
#End If

Dim bc As ByteConverter
    Dim msg() As Byte = bc.HexFromBytes(packet.Data).GetBytes("UTF8")
   
    Dim hexCurated As String = bc.StringFromBytes(msg,"UTF8")

    Dim bc As ByteConverter
    Dim pktHeader() As Byte = bc.HexToBytes("33363730424239462F2F312F2F")
    Log(bc.StringFromBytes(pktHeader, "UTF8"))
    Dim pktData() As Byte = bc.HexToBytes(hexCurated)
    Log(BytesToString(pktData, 0, pktData.Length, "UTF8"))
    Log(pktData.Length)
    Dim kg As KeyGenerator
    Dim C As Cipher
    kg.Initialize("AES")
    kg.KeyFromBytes("0123456789ABCDEF".GetBytes("UTF8"))
     
    C.Initialize("AES/ECB/ZeroBytePadding")
 
    Dim decryptedBytes() As Byte = C.Decrypt(pktData, kg.Key, False)
    Log(bc.HexFromBytes(decryptedBytes))
    Log(bc.StringFromBytes(decryptedBytes, "UTF8"))

End Sub
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
I see a couple of issues, but we may be on a path to nowhere. In the previous thread (linked above) I noticed that Java's AES encryption did not produce the same output as your .NET code. Looks like the issue may be RijndaelManaged. Taken from a Stackoverflow post:
In addition, RijndaelManaged class cannot provide an equivalent implementation with AES. There is another class implemented in .net framework, AesManaged class. This class just wrapped RijndaelManaged class with a fixed block size and iteration count to achieve the AES standard. However, it does not support the feedback size, especially, when the mode is set as CFB or OFB, the CryptographicException will be thrown.
note the words
a fixed block size and iteration count to achieve the AES standard
Java follows the AES standard. Therefore, Java's Crypto framework might not be able to work with .NET's RijndaelManaged class.
 
Upvote 0

aaronk

Well-Known Member
Licensed User
Longtime User
Java follows the AES standard. Therefore, Java's Crypto framework might not be able to work with .NET's RijndaelManaged class.
So I am guessing it can't be done in Java? Or you saying that the .Net code can't be converted to Java ?

All I need to do is work out how to decrypt the message so I can read it the encrypted data in B4J. I only posted the .net code hoping it might help work out what needs to be done in B4J.
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
So I am guessing it can't be done in Java? Or you saying that the .Net code can't be converted to Java ?
I don't know yet, but it is a possibility, since we have not been able yet to do it (here, nor in the other thread).
All I need to do is work out how to decrypt the message so I can read it the encrypted data in B4J
Since decryption is just the flip side of encryption, I need you to encrypt some text and I need to see if I can do the same encryption, with the same result on the B4J side. For that I need a clear .NET program that
1) Uses "0123456789ABCDEF" as the key (I need to see that this key is actually being used)
2) Shows how in .NET that key is turned into bytes and logs a hex output of those bytes
3) Uses RijndaelManaged with block size 128, key size 128, cipher mode of ECB and the key from 2)
4) Encrypts the following texts:
a) "Hello World"
b) "So ya, Thought ya, Might like to go to the show."
5) For each string above, shows how it is converted to bytes and logs hex output of those bytes.
6) Encrypts the string and logs a hex representation of the encrypted bytes produced

I need to see the complete source of the .NET program you use to accomplish the above. If you can do that, then I can see if Java is able to reproduce what RijndaelManaged produces.
 
Upvote 0

Daestrum

Expert
Licensed User
Longtime User
It looks like in your code (post #13) you are trying to decrypt the plaintext part of the message too.
Can you post the packet.Data byte array as a hex string.
 
Upvote 0

aaronk

Well-Known Member
Licensed User
Longtime User
Hopefully the following will help..

I have been playing with this more today and managed to get the encrypted side working in B4J and just stuck on decrypting the message. So looks like I am half way there.

A UDP Message is sent to my B4J app.
The data can either be sent encrypted or in plain text.

The Message being sent contains if it's encrypted or not.

Example:
Plan text = 3670BB9F//0//09ct00300CD
Encrypted = 3670BB9F//1//y]ªˆ¹¥·œ ÁÝuZV_

Example 2:
Plan text = 567EBD07//0//09ct00300CD
Encrypted = 567EBD07//1//y]ªˆ¹¥·œ ÁÝuZV_

The Message contains // which is used to split up the message:

ID_of_device
//
0 or 1 (0=plain text, 1=encrypted)
//
Message (plain text if the above is 0, or the message is encrypted if the above is 1)

If the Message is encrypted then its in AES-128 in ECB mode.

During my testing, I used the encryption key 0123456789ABCEDF

The encrypted message should match the plain text once decrypted.

The encrypted message above (from the example) was created using the following in B4J:

B4X:
Sub Encrypt(value As String)
' value = 3670BB9F//0//09ct00300CD

    Dim joSecurity As JavaObject
    joSecurity.InitializeStatic("java.security.Security")

    Dim jo As JavaObject
    jo.InitializeNewInstance("org.bouncycastle.jce.provider.BouncyCastleProvider", Null)
    joSecurity.RunMethod("addProvider", Array As Object (jo))

    Dim stringData As String = value & CRLF
    Dim stringPassword As String = "0123456789ABCDEF"

    Dim bytesData() As Byte = stringData.GetBytes("ASCII")
    Dim bytesPassword() As Byte = stringPassword.GetBytes("ASCII")

    Dim encryptedPacket() As Byte = Encrypt(bytesData, bytesPassword)

    File.WriteBytes(Globals.AppLocation,"Encrypt.txt",encryptedPacket)
' saves = 3670BB9F//0//y]ªˆ¹¥·œ ÁÝuZV_

    ' Let's Decrypt it
    Decrypt(encryptedPacket)

End Sub

The above code works, and encrypts the data fine. I just can't work out how to decrypt the encrypted message.

Looks like I am half way there, but just can't work out the decrypt part.

I tried the following but I think I am still a long way off from getting it to work:

B4X:
Sub Decrypt(value() As Byte)

    Dim raw() As Byte = value
    bb.Initialize
    bb.Append(raw)
    Dim binaryflag() As Byte = Array As Byte(0x33, 0x36, 0x37, 0x30, 0x42, 0x42, 0x39, 0x46, 0x2f,0x2f,0x31,0x2f,0x2f)
    If bb.IndexOf(binaryflag) > -1 Then
        Dim msgbytes() As Byte = bb.SubArray2(13,bb.IndexOf2(Array As Byte(0x0),13)) ' use the index of the zerobyte to mark the "end".
    End If

    kg.Initialize("AES")
    kg.KeyFromBytes("0123456789ABCDEF".GetBytes("UTF8"))
    C.Initialize("AES/ECB/NoPadding")
    msgbytes = C.Decrypt(msgbytes, kg.Key, False)

    Dim value1 As String
    value1 = BytesToString(value, 0, value.Length, "UTF-8")
    Dim msg_string() As String = Regex.Split("//",value1)
 
    File.WriteBytes(Globals.AppLocation,"Decrypt.txt",(msg_string(0) & "//" & msg_string(1) & "//" & BConv.StringFromBytes(msgbytes, "UTF8").Trim).GetBytes("UTF8"))
 
    Log(msg_string(0) & "//" & msg_string(1) & "//" & BConv.StringFromBytes(msgbytes, "UTF8").Trim)
   ' need to make it so it logs: 3670BB9F//0//09ct00300CD
End Sub
 
Upvote 0

Daestrum

Expert
Licensed User
Longtime User
This example encrypts and decrypts correctly. (it uses PKCS5Padding and pads the data to 16byte multiples)
on the encryption
If //0// in header no encryption takes place and message is left as plaintext.
If //1// is present, it splits off the header, encrypts the data then joins them together.

on decryption
If //0// is present it just returns the plaintext
If //1// is present it splits the header off, decrypts the data, then joins them together.

(NOTE: there is redundant code left in so you can see where the code differs from yours)

B4X:
Sub Process_Globals
 Private fx As JFX
 Private MainForm As Form
 Dim c As Cipher
 Dim kg As KeyGenerator
 Dim BConv As ByteConverter
End Sub
Sub AppStart (Form1 As Form, Args() As String)
 MainForm = Form1
 MainForm.Show
 Dim joSecurity As JavaObject
 joSecurity.InitializeStatic("java.security.Security")
 Dim jo As JavaObject
 jo.InitializeNewInstance("org.bouncycastle.jce.provider.BouncyCastleProvider", Null)
 joSecurity.RunMethod("addProvider", Array As Object (jo))
 
 Dim plainMessage As String = "3670BB9F//1//09ct00300CD"
 
 Log("Plain text message : "& plainMessage)
 Dim eMsg() As Byte = Encrypt(plainMessage)
 Log("eMsg      : " & BConv.StringFromBytes(eMsg,"utf8"))
 Log("decrypted : " & Decrypt(eMsg))
End Sub
Sub Encrypt(value As String) As Byte()
 ' value = 3670BB9F//0//09ct00300CD
 Dim header As String = value.SubString2(0,value.LastIndexOf("//")+2)
 Dim headerBytes() As Byte = header.GetBytes("utf8")
 If header.contains("//1//") Then
  Dim stringData As String = value.SubString(header.Length)
  Do While (stringData.Length Mod 16) <> 0
   stringData = stringData & " "
  Loop
  Dim stringPassword As String = "0123456789ABCDEF"
  Dim bytesData() As Byte = stringData.GetBytes("ASCII")
  Dim bytesPassword() As Byte = stringPassword.GetBytes("ASCII")
  kg.Initialize("AES")
  kg.KeyFromBytes("0123456789ABCDEF".GetBytes("UTF8"))
  C.Initialize("AES/ECB/PKCS5Padding")
  Dim encryptedData() As Byte = C.Encrypt(bytesData,kg.Key,False)
  Dim encryptedPacket(headerBytes.Length+encryptedData.Length) As Byte
  For a = 0 To (encryptedData.Length + headerBytes.Length) -1
   If a <= headerBytes.Length-1 Then
    encryptedPacket(a) = headerBytes(a)
   Else
    encryptedPacket(a) = encryptedData(a - headerBytes.length)
   End If 
  Next
 Else
  encryptedPacket = value.GetBytes("utf8")
 End If
 Return encryptedPacket
End Sub
Sub Decrypt(value() As Byte) As String
 Dim msg_string As String
 Dim dataString As String = BConv.StringFromBytes(value,"utf8")
 Dim header As String = dataString.SubString2(0,dataString.LastIndexOf("//")+2)
 If header.Contains("//1//") Then
  Dim headerBytes() As Byte = header.GetBytes("utf8")
  Dim headerLength As Int = headerBytes.Length
  Dim msgbytes(value.Length-headerLength) As Byte
  For a = headerLength To value.Length-1
   msgbytes(a-headerLength) = value(a)
  Next
  kg.Initialize("AES")
  kg.KeyFromBytes("0123456789ABCDEF".GetBytes("UTF8"))
  C.Initialize("AES/ECB/PKCS5Padding")
  Dim decryptedmsgbytes() As Byte  = C.Decrypt(msgbytes, kg.Key, False)
  Dim value1 As String
  value1 = BytesToString(decryptedmsgbytes, 0, decryptedmsgbytes.Length, "UTF-8")
  msg_string = header&value1
 Else
  msg_string = dataString
 End If
 Return msg_string.trim
End Sub

Hope it helps.
 
Upvote 0

aaronk

Well-Known Member
Licensed User
Longtime User
This example encrypts and decrypts correctly.
This seems to work and decrypt the message if the message was encrypted with the code.

The device in the field is sending me the UDP message which looks like:
(which I don't have control on how it's sending and encoding the message, but been told it's using AES-128 in ECB Mode)

3670BB9F//1//�Q~�]!���-L�>xY��y�����@�p"10g�_�\9Yp��d��q{�ۺ�Y��

When I use:

B4X:
Dim EncryptedMessage As String = $"3670BB9F//1//�Q~�]!���-L�>xY��y�����@�p"10g�_�\9Yp��d��q{�ۺ�Y��"$
        Dim eMsg() As Byte = EncryptedMessage.GetBytes("utf8")
        Log("eMsg      : " & BConv.StringFromBytes(eMsg,"utf8"))
        Log("decrypted : " & Decrypt(eMsg))

It seems to log:
eMsg : 3670BB9F//1//�Q~�]!���-L�>xY��y�����@�p"10g�_�\9Yp��d��q{�ۺ�Y��
javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes
decrypted : null

Should it decrypt the message, or have I done it wrong ?

The decrypted message should show:
3670BB9F//0//0000754C//00409D27558D//05.03.10//02.00.45//Hello
(key used was 0123456789ABCDEF)
 
Upvote 0
Top