Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class AEScbcCipher
- {
- private int AESblockSize;
- private byte[] keyByte = new byte[16];
- private byte[] ivByte = new byte[16];
- private string keyString = "xxx";
- private string ivString = "xxx";
- public AEScbcCipher(int AESblockSize)
- {
- this.AESblockSize = AESblockSize;
- setKey();
- setIV();
- }
- public AEScbcCipher()
- {
- this.AESblockSize = 16;
- setKey();
- setIV();
- }
- private void setKey()
- {
- for (int j = 0; j < keyByte.Length; j += 2)
- {
- byte result;
- if (byte.TryParse(keyString.Substring(j, 2), System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.CreateSpecificCulture("en-US"), out result) == true)
- {
- keyByte[j / 2] = result;
- }
- }
- }
- private void setIV()
- {
- for (int j = 0; j < ivByte.Length; j += 2)
- {
- byte result;
- if (byte.TryParse(ivString.Substring(j, 2), System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.CreateSpecificCulture("en-US"), out result) == true)
- {
- ivByte[j / 2] = result;
- }
- }
- }
- private byte[] PerformCryptography(ICryptoTransform cryptoTransform, byte[] data)
- {
- using (var memoryStream = new MemoryStream())
- {
- using (var cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
- {
- //I get Exception here
- cryptoStream.Write(data, 0, data.Length);
- cryptoStream.FlushFinalBlock();
- return memoryStream.ToArray();
- }
- }
- }
- public byte[] Encrypt(byte[] data)
- {
- if (data == null || data.Length <= 0)
- throw new ArgumentNullException("plainText");
- if (keyByte == null || keyByte.Length <= 0)
- throw new ArgumentNullException("Key");
- if (ivByte == null || ivByte.Length <= 0)
- throw new ArgumentNullException("IV");
- using (Aes aesAlg = Aes.Create())
- {
- aesAlg.Key = keyByte;
- aesAlg.IV = ivByte;
- using (var encryptor = aesAlg.CreateEncryptor(keyByte, ivByte))
- {
- return PerformCryptography(encryptor, data);
- }
- //unreachable code
- return data;
- }
- }
- public byte[] Decrypt(byte[] data)
- {
- using (Aes aesAlg = Aes.Create())
- {
- aesAlg.Key = keyByte;
- aesAlg.IV = ivByte;
- using (var decryptor = aesAlg.CreateDecryptor(keyByte, ivByte))
- {
- return PerformCryptography(decryptor, data);
- }
- //unreachable code
- return data;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement