/// <summary> /// test using user-provided keys and init vectors /// </summary> private static string SymmetricWithKey(SymmetricProvider p, string targetString) { var keyData = new SymmetricKeyData("MySecretPassword"); var ivData = new SymmetricKeyData("MyInitializationVector"); Data encryptedData; using (var sym = new Symmetric(p, false)) { sym.IntializationVector = ivData; encryptedData = sym.Encrypt(new Data(targetString), keyData); } Data decryptedData; using (var sym2 = new Symmetric(p, false)) { sym2.IntializationVector = ivData; decryptedData = sym2.Decrypt(encryptedData, keyData); } ////-- the data will be padded to the encryption blocksize, so we need to trim it back down. //return decryptedData.ToString().Substring(0, _TargetData.Bytes.Length); return decryptedData.ToString(); }
/// <summary> /// Ensures that the _crypto object has valid Key and IV prior to any attempt to encrypt or decrypt. /// </summary> private void ValidateKeyAndIv(bool isEncrypting) { if (_key.IsEmpty) { if (isEncrypting) { _key = RandomKey(); } else { throw new CryptographicException("No key was provided for the decryption operation!"); } } if (_iv.IsEmpty) { if (isEncrypting) { _iv = RandomInitializationVector(); } else { throw new CryptographicException("No initialization vector was provided for the decryption operation!"); } } _crypto.Key = _key.Bytes; _crypto.IV = _iv.Bytes; }
/// <summary> /// Encrypts the specified stream to memory using the provided key. /// </summary> /// <exception cref="T:System.ArgumentNullException">stream is null.</exception> public Data Encrypt(Stream stream, SymmetricKeyData key) { Key = key; return Encrypt(stream); }
/// <summary> /// Encrypts the specified stream to memory using the provided key and initialization vector. /// </summary> /// <exception cref="T:System.ArgumentNullException">stream is null.</exception> public Data Encrypt(Stream stream, SymmetricKeyData key, SymmetricKeyData iv) { IntializationVector = iv; Key = key; return Encrypt(stream); }
/// <summary> /// Encrypts the specified data using the provided key. /// </summary> /// <exception cref="T:System.ArgumentNullException">data is null.</exception> public Data Encrypt(Data d, SymmetricKeyData key) { Key = key; return Encrypt(d); }
/// <summary> /// Decrypts the specified data using provided key and preset initialization vector. /// </summary> /// <exception cref="T:System.ArgumentNullException">data is null.</exception> /// <exception cref="T:System.Security.Cryptography.CryptographicException">Unable to decrypt data.</exception> public Data Decrypt(Data data, SymmetricKeyData key) { Key = key; return Decrypt(data); }