Encrypt a String Using an AES Key
AES is a block cipher, therefore, you must send data to the server in chunks of 16 bytes. If String size is not multiple of 16, set to CBC mode. This will use padding to meet the 16-byte requirement. In the CBC mode, the AES algorithm requires a 16-byte initialization vector (IV).
To encrypt a string:
Create a NAE Session. Pass the NAE username, password, and property file path as arguments.
NaeSession session = new NaeSession(user, passwd, propFilePath);
Create an
NaeRijndaelKey
object. Pass theNaeSession
object andkeyname
as arguments.NaeRijndaelKey key = new NaeRijndaelKey(session, keyname);
Specify an IV, if necessary, by creating a new byte array.
byte[] iv = { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35 }; key.IV = iv;
Set key mode and padding.
key.Padding = PaddingMode.PKCS7; key.Mode = CipherMode.CBC;
Encrypt the data.
ICryptoTransform encryptor = key.CreateEncryptor(); System.IO.MemoryStream memstr = new System.IO.MemoryStream(); CryptoStream encrstr = new CryptoStream(memstr, encryptor, CryptoStreamMode.Write); encrstr.Write(inputBytes, 0, inputBytes.Length); encrstr.Close(); encrBytes = memstr.ToArray(); Console.WriteLine("Encrypted Data (B64 encoded): {0}", Convert.ToBase64String(encrBytes));
Note
The CreateEncryptor
API doesn't support encrypting large data using chunking mechanism. To encrypt large data, refer to Encrypting/Decrypting a File.