Android Question AES with 256 bits encoding

peacemaker

Expert
Licensed User
Longtime User
Any solution ?
IV cannot be 32 bytes, only 16 in the standard AES code sample.
 

peacemaker

Expert
Licensed User
Longtime User
B4X:
Sub Encrypt (s As String, key_val As String, iv_val As String)
Dim Bconv As ByteConverter
Dim B64 As Base64
Dim kg As KeyGenerator

Dim key(32), key1() As Byte
Dim data(0) As Byte
Dim iv(32), iv1() As Byte
iv1 = iv_val.GetBytes("ASCII")
Log(iv.Length)
Bconv.ArrayCopy(iv1, 0, iv, 0, iv1.Length)

Dim c As Cipher
c.Initialize("AES/CBC/PKCS5Padding") 'AES/CBC/PKCS5Padding replace "DES/" with "AES/" for Rijndael or "DESEDE/" for triple DES
' CBC needs an initialisation vector
Log(c.GetAlgorithms
c.InitialisationVector = iv
kg.Initialize("AES") ' replace "DES" with "AES" for Rijndael or "DESEDE" for triple DES
key1 = key_val.GetBytes("ASCII")    'ISO-8859-1
Bconv.ArrayCopy(key1, 0, key, 0, key1.Length)

kg.KeyFromBytes(key)
Log(Bconv.HexFromBytes(key) & " Key " & key.Length & " bytes")

data = Bconv.StringToBytes(s, "ASCII")    'ISO-8859-1
data = c.Encrypt(data, kg.key, True)
Dim res As String
res = B64.EncodeBtoS(data, 0, data.Length)
Log(res)
End Sub

c.Encrypt gives error that iv(32) only 16 bype can be.
Problem is that i have to make the same coding as on a server:
B4X:
public static string Encrypt(string s, string key_val, string iv_val)
        {
            RijndaelManaged Algorithm;
            MemoryStream memStream;
            ICryptoTransform EncryptorDecryptor;
            CryptoStream crStream;
            StreamWriter strWriter;

            string m_key;
            string m_iv;
            byte[] key;
            byte[] iv;
            byte[] pwd_byte;

            key = new byte[32];
            iv = new byte[32];

            int i;
            m_key = key_val;
            m_iv = iv_val;

            for (i = 0; i < m_key.Length; i++)
            {
                key[i] = Convert.ToByte(m_key[i]);
            }
            for (i = 0; i < m_iv.Length; i++)
            {
                iv[i] = Convert.ToByte(m_iv[i]);
            }

            Algorithm = new RijndaelManaged();
            Algorithm.BlockSize = 256;
            Algorithm.KeySize = 256;

            memStream = new MemoryStream();
            EncryptorDecryptor = Algorithm.CreateEncryptor(key, iv);
            crStream = new CryptoStream(memStream, EncryptorDecryptor, CryptoStreamMode.Write);
            strWriter = new StreamWriter(crStream);
            strWriter.Write(s);
            strWriter.Flush();
            crStream.FlushFinalBlock();
            pwd_byte = new byte[memStream.Length];
            memStream.Position = 0;
            memStream.Read(pwd_byte, 0, (int)pwd_byte.Length);
            return Convert.ToBase64String;
        }
 
Last edited:
Upvote 0

peacemaker

Expert
Licensed User
Longtime User
Thanks, Erel, changing to 128 bit (iv(16) also) on the server side solved the issue.
 
Upvote 0
Top