Android Question AES encryption/decryption B4A- C#

wl

Well-Known Member
Licensed User
Longtime User
Hi,

I'm trying to encrypt AES in B4A en decrypt in C# (and visa versa).

If found this similar post (http://www.b4x.com/android/forum/threads/aes-sample.6855/page-2#post-157012) but can't seem to find a solution for .NET

I tried to encrypt using the same key and tekst in both B4 and C# but I obtain a different byte array in both

B4A:

B4X:
Sub Encrypt(dataToEncrypt As String)
    Dim kg As KeyGenerator
    Dim C As Cipher
    Dim encrypted() As Byte
  
    kg.Initialize("AES")
    kg.KeyFromBytes("5TGB&YHN7UJM(IK<".GetBytes("UTF8"))
    
    C.Initialize("AES/CBC/PKCS7Padding")
      C.InitialisationVector = "!QAZ2WSX#EDC4RFV".GetBytes("UTF8")
    encrypted = C.Encrypt(dataToEncrypt.GetBytes("UTF8"), kg.Key, False)
 
    Dim foo(encrypted.Length) As Int
    For lcv = 0 To encrypted.Length - 1
        foo (lcv) = Bit.AND(0xFF, encrypted(lcv))
    Next
End Sub

I compare the array foo with the dest array in C# code:

B4X:
        private const string AesIV = @"!QAZ2WSX#EDC4RFV";
        private const string AesKey = @"5TGB&YHN7UJM(IK<";
 
        private string Encrypt(string text)
        {
            // AesCryptoServiceProvider
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            aes.BlockSize = 128;
            aes.KeySize = 128;
            aes.IV = Encoding.UTF8.GetBytes(AesIV);
            aes.Key = Encoding.UTF8.GetBytes(AesKey);
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;
 
            // Convert string to byte array
            byte[] src = Encoding.Unicode.GetBytes(text);
 
            // encryption
            using (ICryptoTransform encrypt = aes.CreateEncryptor())
            {
                byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
 
                // Convert byte array to Base64 strings
                return Convert.ToBase64String(dest);
            }
        }
 

wl

Well-Known Member
Licensed User
Longtime User
Solved.
Thanks to this post: http://zenu.wordpress.com/2011/09/21/aes-128bit-cross-platform-java-and-c-encryption-compatibility/
I found out I needed to use RijndaelManaged class in C#.

this is the compatible C#code:

B4X:
      public byte[] Encrypt(byte[] plainBytes)
        {
            RijndaelManaged rm = new RijndaelManaged
            {
                Mode = CipherMode.CBC,
                Padding = PaddingMode.PKCS7,
                KeySize = 128,
                BlockSize = 128,
                Key = Encoding.UTF8.GetBytes(AesKey),
                IV = Encoding.UTF8.GetBytes(AesIV)
            };
 
            return rm.CreateEncryptor().TransformFinalBlock(plainBytes, 0, plainBytes.Length);
        }
 
Upvote 0
Top