Android Question B4a Cipher (AES) vs. VB.NET 2017 Encryption

Jeffrey Cameron

Well-Known Member
Licensed User
Longtime User
I'm trying to use AES on the Android side, for a simple example, here's my encryption block
B4X:
Public Sub AES_Encrypt(DataToEncrypt As String) As String
    Dim poKG As KeyGenerator
    Dim poCy As Cipher
    Dim poBC As ByteConverter
    Dim poData() As Byte

    ' doing AES
    poCy.Initialize("AES")
    ' set InitializationVector value
    poCy.InitialisationVector = poBC.StringToBytes(USER_IV16, "utf8")
    ' Generate a key
    poKG.Initialize("AES")
    poKG.KeyFromBytes(poBC.StringToBytes(USER_KEY, "utf8"))
    ' encrypt the string into a byte array   
    poData = poCy.Encrypt(poBC.StringToBytes(DataToEncrypt, "utf8"), poKG.Key, True)
    ' convert the byte array to a HEX string and return it
    Return poBC.HexFromBytes(poData)
End Sub
The "USER_IV!6" is a 16-byte string constant as is the "USER_KEY" (differing values).

Encrypting a test value (such as "testmail@test.com") produces a 64-byte HEX string as expected. Using this same basic methodology in a VS-2017 VB.NET application, when I encrypt the same string using the same IV and KeyGen I come up with an entirely different 64-byte HEX string. My vb.net code:
B4X:
    Public Shared Function AESEncrypt(ByVal PlainText As String) As String
        Dim pyBytes() As Byte
        Dim pyResult() As Byte
        Dim piIndex As Integer
        Dim poResult As New System.Text.StringBuilder

        pyBytes = System.Text.UTF8Encoding.UTF8.GetBytes(PlainText)

        ' Encrypt it
        Dim poAES As New System.Security.Cryptography.AesManaged
        poAES.IV = System.Text.UTF8Encoding.UTF8.GetBytes(USER_IV16)
        poAES.Key = System.Text.UTF8Encoding.UTF8.GetBytes(USER_KEY)
        pyResult = poAES.CreateEncryptor().TransformFinalBlock(pyBytes, 0, pyBytes.Length)
        ' convert it to a HEX string
        For piIndex = 0 To pyResult.Length - 1
            poResult.Append(pyResult(piIndex).ToString("X2"))
        Next

        Return poResult.ToString
    End Function
I have verified IV and KEY values are exactly the same between apps. Is this related to the "bouncy castle" issues in newer Android versions? I thought that only affected DES/3DES?

Also, the specs on this project prohibit me from creating a B4J back-end I could call from the VB.NET app to decode it for me. Is there any way to encrypt/decrypt with B4A on the newer Android versions and have it decrypted/encrypted properly by a Windows platform application?
 

Jeffrey Cameron

Well-Known Member
Licensed User
Longtime User
You are correct @Erel, (as always ;) )

My fault for assuming that the "default" of a "standard" would be the same across all platforms, but it seems Java defaults to zero padding where .NET does the PKCS7.

And while I did read the cypher documentation prior to posting, it seems that understanding it are at least three different things when it comes to me! :D
 
Upvote 0
Top