Click here to Skip to main content
15,887,836 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am doing AES Key Generation in c# and passing the key generated for AES 128 bit Encryption. The case is while generating the key I am getting byte length as 16 while the key string length is getting higher than 16. While trying online I am getting length as 16 itself.

What I have tried:

Core Code is as below:
AES Key 128 bit Generation
System.Security.Cryptography.AesCryptoServiceProvider crypto = new System.Security.Cryptography.AesCryptoServiceProvider();
crypto.KeySize = 128;
crypto.BlockSize = 128;
crypto.GenerateKey();
byte[] keyGenerated = crypto.Key;
Key = Convert.ToBase64String(keyGenerated);


AES 128 bit Key Encryption
RijndaelManaged aes = new RijndaelManaged();
         aes.BlockSize = 128;
         aes.KeySize = 128;

         /// In Java, Same with below code
         /// Cipher _Cipher = Cipher.getInstance("AES");  // Java Code
         aes.Mode = CipherMode.ECB;

         byte[] keyArr = Convert.FromBase64String(keyStr);
         byte[] KeyArrBytes16Value = new byte[16];
         Array.Copy(keyArr, KeyArrBytes16Value, 16);

         aes.Key = KeyArrBytes16Value;

         ICryptoTransform encrypto = aes.CreateEncryptor();

         byte[] plainTextByte = ASCIIEncoding.UTF8.GetBytes(PlainText);
         byte[] CipherText = encrypto.TransformFinalBlock(plainTextByte, 0, plainTextByte.Length);
         return Convert.ToBase64String(CipherText);
Posted
Comments
Bjørn 30-Jul-18 11:30am    
Hello ranio, what exactly is your question here? Are you asking why there is a difference in the length of the byte array and the Base64 string?
ranio 31-Jul-18 0:13am    
Th length of the bytes are 16 but while converting the bytes to base64 string the length varies for AES Key generated with 128 bit. It becomes greater than 64. The AES Key string length for 128 bit must be always 16.
Bjørn 1-Aug-18 3:38am    
Hello ranio, I cannot recreate this behaviour. The Base64 representation of 16 bytes must always be 24 characters long (as it uses only 6 of 8 bits) and using your example code I always get exactly 24 characters for the Base64 encoded key which always decode back to exactly 16 bytes. Do you use different code than posted above? Or do you do anything else with Key before it is written into keyStr?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900