private static byte[] SimpleEncrypt(byte[] secretMessage, byte[] cryptKey, byte[] nonSecretPayload) { //User Error Checks if (cryptKey == null || cryptKey.Length != KeyBitSize / 8) { throw new ArgumentException($"Key needs to be {KeyBitSize} bit!", nameof(cryptKey)); } if (secretMessage == null || secretMessage.Length < 1) { throw new ArgumentException("Secret Message Required!", nameof(secretMessage)); } //non-secret payload optional nonSecretPayload = nonSecretPayload ?? new byte[] { }; byte[] cipherText; byte[] iv; using (var aes = new AesCng() { KeySize = KeyBitSize, BlockSize = BlockBitSize, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }) { //Use random IV aes.GenerateIV(); iv = aes.IV; using (var encrypter = aes.CreateEncryptor(cryptKey, iv)) { using (var cipherStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write)) { using (var binaryWriter = new BinaryWriter(cryptoStream)) binaryWriter.Write(secretMessage); } cipherText = cipherStream.ToArray(); } } using (var encryptedStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(encryptedStream)) { binaryWriter.Write(nonSecretPayload); //Prepend IV binaryWriter.Write(iv); binaryWriter.Write(cipherText); binaryWriter.Flush(); } return(encryptedStream.ToArray()); } } }
// Генерировать вектор инициализации IV private void btn_generate_iv_Click(object sender, EventArgs e) { if (AlgName == "AES") { aescng.GenerateIV(); this.txt_iv.Text = alg.ByteArrayTOStringHEX(aescng.IV); } if (AlgName == "3DES") { tripledes.GenerateIV(); this.txt_iv.Text = alg.ByteArrayTOStringHEX(tripledes.IV); } }
public override string Encrypt(string Message) { // Generate new initialization vector for each encryption to prevent identical plaintexts from producing identical ciphertexts when encrypted using the same key. _cipher.GenerateIV(); using (var stream = new MemoryStream()) using (var encryptor = _cipher.CreateEncryptor(SharedKey, _cipher.IV)) using (var cryptoStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write)) using (var streamWriter = new StreamWriter(cryptoStream)) { stream.Write(_cipher.IV, 0, _cipher.IV.Length); streamWriter.Write(Message); return(Convert.ToBase64String(stream.ToArray())); } }
public void AesCngCreateEncryptor() { using var aes = new AesCng(); using var rng = new RNGCryptoServiceProvider(); var noParams = aes.CreateEncryptor(); // Compliant aes.GenerateKey(); var withGeneratedKey = aes.CreateEncryptor(); // Compliant var constantIV = new byte[16]; var withConstant = aes.CreateEncryptor(aes.Key, constantIV); // Noncompliant aes.GenerateIV(); aes.CreateEncryptor(); var withGeneratedKeyAndIV = aes.CreateEncryptor(aes.Key, aes.IV); aes.CreateDecryptor(aes.Key, constantIV); // Compliant, we do not check CreateDecryptor rng.GetBytes(constantIV); var fromRng = aes.CreateEncryptor(aes.Key, constantIV); }