// The CipherResult contains all important settings (options) and the resulting CipherText (in Byte Array) public static byte[] BasicAesDecryption(CipherResult cO, string passPhrase) { var myRijndael = new RijndaelManaged(); myRijndael.BlockSize = 128; myRijndael.KeySize = cO.KeySizeInBytes * 8; myRijndael.IV = cO.AesRijndaelIv; myRijndael.Padding = PaddingMode.PKCS7; myRijndael.Mode = CipherMode.CBC; var salt = cO.Salt; if (cO.DerivationType == "scrypt") { myRijndael.Key = ScryptHandler.GetOnlyHashBytes(System.Text.Encoding.UTF8.GetBytes(passPhrase), cO); } else { Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(System.Text.Encoding.UTF8.GetBytes(passPhrase), salt, cO.DerivationIterations); myRijndael.Key = rfc2898.GetBytes(cO.KeySizeInBytes); } var encryptedBytes = cO.CipherOutput; ICryptoTransform transform = myRijndael.CreateDecryptor(); byte[] cipherText = transform.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length); return(cipherText); }
// The resulting CipherResult contains all important settings (options) and the resulting CipherText (in Byte Array) public static CipherResult BasicAesEncryption(byte[] bytesToEncrypt, string passPhrase, EncryptionOptions eO = null) { // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text // so that the same Salt and IV values can be used when decrypting. var myRijndael = new RijndaelManaged(); myRijndael.BlockSize = 128; if (eO == null) { eO = new EncryptionOptions(); myRijndael.IV = GenerateXBytesOfRandomEntropy(16); //IV must be 16 bytes / 128 bit eO.RijndaelIv = myRijndael.IV; } else if (eO.RijndaelIv == null) { myRijndael.IV = GenerateXBytesOfRandomEntropy(16); //IV must be 16 bytes / 128 bit eO.RijndaelIv = myRijndael.IV; } else { myRijndael.IV = eO.RijndaelIv; } myRijndael.Padding = PaddingMode.PKCS7; myRijndael.Mode = CipherMode.CBC; // Using Scrypt for Key Derivation if (eO.DerivationType == null || eO.DerivationType == "scrypt") { eO.DerivationType = "scrypt"; myRijndael.Key = ScryptHandler.GetOnlyHashBytes(System.Text.Encoding.UTF8.GetBytes(passPhrase), eO); } // Using RFC2898 for Key Derivation else { if (eO.Salt == null) { eO.Salt = GenerateXBytesOfRandomEntropy(32); } myRijndael.KeySize = eO.KeySizeInBytes * 8; Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(System.Text.Encoding.UTF8.GetBytes(passPhrase), eO.Salt, eO.DerivationIterations); myRijndael.Key = rfc2898.GetBytes(eO.KeySizeInBytes); } byte[] utf8Text = bytesToEncrypt; ICryptoTransform transform = myRijndael.CreateEncryptor(); byte[] cipherText = transform.TransformFinalBlock(utf8Text, 0, utf8Text.Length); var cipherWithSaltAndIvObject = new CipherResult(eO, cipherText); return(cipherWithSaltAndIvObject); }