diff --git a/Encrypt/AesEncryption/BaseAesEncryption.cs b/Encrypt/AesEncryption/BaseAesEncryption.cs index 700cdcb..b1919d2 100644 --- a/Encrypt/AesEncryption/BaseAesEncryption.cs +++ b/Encrypt/AesEncryption/BaseAesEncryption.cs @@ -33,5 +33,18 @@ public virtual byte[] EncryptAES(byte[] data, byte[] key, byte[] iv) throw; } } + + // Method to generate a random byte array of given length + // Used to get the IV + // Generate a random 16-byte IV for AES in CBC mode + public static byte[] GenerateRandomBytes(int length) + { + byte[] randomBytes = new byte[length]; + using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider()) + { + rng.GetBytes(randomBytes); + } + return randomBytes; + } } } diff --git a/Encrypt/AesEncryption/Encrypt.cs b/Encrypt/AesEncryption/Encrypt.cs index 96fcec4..ad7db94 100644 --- a/Encrypt/AesEncryption/Encrypt.cs +++ b/Encrypt/AesEncryption/Encrypt.cs @@ -20,6 +20,25 @@ public byte[] AesEncrypt(string data, string secretKey, string iv) return EncryptAES(aesData, aesKey, aesIv); } + public AesData AesEncrypt(string data, string secretKey) + { + NullChecks(data, secretKey); + + var aesIv = GenerateRandomBytes(16); + var aesKey = Encoding.UTF8.GetBytes(secretKey); + var aesData = data.HexadecimalStringToByteArray(); + + var response = EncryptAES(aesData, aesKey, aesIv); + + var responseData = new AesData + { + Data = response, + Iv = aesIv + }; + + return responseData; + } + public string AesEncryptByteToHexString(byte[] data, byte[] secretKey, byte[] iv) { var cipherText = EncryptAES(data, secretKey, iv); @@ -53,9 +72,24 @@ private void NullChecks(string data, string secretKey, string iv) throw new ArgumentNullException("IV"); } + private void NullChecks(string data, string secretKey) + { + if (data == null || data.Length <= 0) + throw new ArgumentNullException("plainText"); + + if (secretKey == null || secretKey.Length <= 0) + throw new ArgumentNullException("Key"); + } + //public byte[] AesEncrypt(byte[] data, byte[] key, byte[] iv, ReturnType returnType) //{ //} } + + public class AesData + { + public byte[] Data { get; set; } + public byte[] Iv { get; set; } + } }