private static string EncryptPrivateKey(string content, string password) { byte[] passwordHash = GenerateHash(password); byte[] contentBytes = Encoding.UTF8.GetBytes(content); byte[] encrypted; using (Aes aes = Aes.Create()) { try { aes.Key = passwordHash; aes.GenerateIV(); aes.Mode = CipherMode.ECB; aes.CreateEncryptor(aes.Key, aes.IV); using (ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV)) { using (MemoryStream to = new MemoryStream()) { to.Write(aes.IV, 0, 16); using (CryptoStream writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write)) { writer.Write(contentBytes, 0, contentBytes.Length); writer.FlushFinalBlock(); encrypted = to.ToArray(); } } } } finally { aes.Clear(); } } return(Convert.ToBase64String(encrypted)); }
private static string DecryptString(byte[] toDecrypt) { byte[] result; byte[] DataToDecrypt = toDecrypt; byte[] AESkey = Encoding.UTF8.GetBytes(cipherKey); using (Aes aes = Aes.Create()) { aes.Key = AESkey; byte[] IV = new byte[aes.BlockSize / 8]; byte[] cipherText = new byte[DataToDecrypt.Length - IV.Length]; Array.Copy(DataToDecrypt, IV, IV.Length); Array.Copy(DataToDecrypt, IV.Length, cipherText, 0, cipherText.Length); aes.IV = IV; aes.Mode = CipherMode.CBC; try { ICryptoTransform Encryptor = aes.CreateDecryptor(); result = Encryptor.TransformFinalBlock(cipherText, 0, cipherText.Length); } finally { aes.Clear(); } } return(Encoding.UTF8.GetString(result)); }
public async Task <(byte[] Iv, byte[] EncryptedData)> GetSecretMessageAsync(ECDiffieHellmanPublicKey otherPublicKey) { string message = "secret message from Alice"; _logger.LogInformation($"Alice sends message {message}"); byte[] plainData = Encoding.UTF8.GetBytes(message); byte[] symmKey = _algorithm.DeriveKeyMaterial(otherPublicKey); _logger.LogInformation($"Alice creates this symmetric key with " + $"Bobs public key information: {Convert.ToBase64String(symmKey)}"); using Aes aes = Aes.Create(); _logger.LogInformation($"Using this Aes class: {aes.GetType().Name}"); aes.Key = symmKey; aes.GenerateIV(); using ICryptoTransform encryptor = aes.CreateEncryptor(); using MemoryStream ms = new(); using (CryptoStream cs = new(ms, encryptor, CryptoStreamMode.Write)) { await cs.WriteAsync(plainData.AsMemory()); } // need to close the CryptoStream before using the MemoryStream byte[] encryptedData = ms.ToArray(); _logger.LogInformation($"Alice: message is encrypted: {Convert.ToBase64String(encryptedData)}"); var returnData = (aes.IV, encryptedData); aes.Clear(); return(returnData); }
private static string EncryptData(byte[] toEncrypt) { byte[] result; byte[] IV; byte[] AESkey = Encoding.UTF8.GetBytes(cipherKey); using (Aes aes = Aes.Create()) { aes.Key = AESkey; aes.GenerateIV(); aes.Mode = CipherMode.CBC; IV = aes.IV; try { ICryptoTransform Encryptor = aes.CreateEncryptor(); result = Encryptor.TransformFinalBlock(toEncrypt, 0, toEncrypt.Length); } finally { aes.Clear(); } } byte[] cmbIV = new byte[IV.Length + result.Length]; Array.Copy(IV, 0, cmbIV, 0, IV.Length); Array.Copy(result, 0, cmbIV, IV.Length, result.Length); return(Convert.ToBase64String(cmbIV)); }
static public byte[] encryptPrivateKey(string content, byte[] password) { byte[] valueBytes = Encoding.UTF8.GetBytes(content); byte[] encrypted; using (Aes aes = Aes.Create()) { aes.Key = password; aes.GenerateIV(); aes.Mode = CipherMode.ECB; aes.CreateEncryptor(aes.Key, aes.IV); using (ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV)) { using (MemoryStream to = new MemoryStream()) { to.Write(aes.IV, 0, 16); using (CryptoStream writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write)) { writer.Write(valueBytes, 0, valueBytes.Length); writer.FlushFinalBlock(); encrypted = to.ToArray(); } } } aes.Clear(); } return(encrypted); }
/// <summary> /// Decrypts an AES encrypted message /// </summary> /// <param name="encryptedMessage">Encrypted byte buffer</param> /// <param name="key">Key used for decryption</param> /// <returns>Decrypted message</returns> public byte[] Decrypt(byte[] encryptedMessage, byte[] key) { int blockSize = int.Parse(Config.GetValue(ConfigConstants.ENCRYPTION_BLOCK_SIZE_BYTES)); Aes aes = CreateAes(key, blockSize); byte[] decrypted = null; //read iv out of cipher buffer byte[] iv = new byte[encryptedMessage[0]]; //1st byte for iv length for (int i = 1; i <= iv.Length; i++) { iv[i - 1] = encryptedMessage[i]; } aes.IV = iv; using (ICryptoTransform crypto = aes.CreateDecryptor()) { //decrypt message using (MemoryStream ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, crypto, CryptoStreamMode.Write)) { cs.Write(encryptedMessage, iv.Length + 1, encryptedMessage.Length - iv.Length - 1); } decrypted = ms.ToArray(); } } aes.Clear(); return(decrypted); }
private static readonly byte[] salt = ASCIIEncoding.ASCII.GetBytes("b37vrg37r83g8v36"); // salt as byte array internal static string Encrypt(string input, string password) { byte[] output; byte[] inputAsBytes = UTF8Encoding.UTF8.GetBytes(input); using (Aes aesAlgo = Aes.Create()) { byte[] keyBytes = new PasswordDeriveBytes(password, salt, hashMethod, iterations).GetBytes(nofKeyBytes); aesAlgo.Mode = CipherMode.ECB; using (MemoryStream memoryStreamDestination = new MemoryStream()) { using (ICryptoTransform encryptor = aesAlgo.CreateEncryptor(keyBytes, iv)) { using (CryptoStream writer = new CryptoStream(memoryStreamDestination, encryptor, CryptoStreamMode.Write)) { writer.Write(inputAsBytes, 0, inputAsBytes.Length); writer.FlushFinalBlock(); output = memoryStreamDestination.ToArray(); } } } aesAlgo.Clear(); } return(Convert.ToBase64String(output)); }
/// <summary> /// 解密字节数组 /// </summary> public static byte[] Decrypt(byte[] encodeBytes, string key, bool needIV = false) { encodeBytes.CheckNotNull("source"); using (Aes aes = Aes.Create()) { aes.Key = CheckKey(key); aes.Padding = PaddingMode.PKCS7; aes.Mode = CipherMode.ECB; if (needIV) { aes.Mode = CipherMode.CBC; const int ivLength = 16; byte[] ivBytes = new byte[ivLength], newEncodeBytes = new byte[encodeBytes.Length - ivLength]; Array.Copy(encodeBytes, 0, ivBytes, 0, ivLength); aes.IV = ivBytes; Array.Copy(encodeBytes, ivLength, newEncodeBytes, 0, newEncodeBytes.Length); encodeBytes = newEncodeBytes; } using (ICryptoTransform decryptor = aes.CreateDecryptor()) { byte[] decodeBytes = decryptor.TransformFinalBlock(encodeBytes, 0, encodeBytes.Length); aes.Clear(); return(decodeBytes); } } }
public static string DecryptStringAES256(string base64String, string key, string iv) { byte[] result = null; byte[] bEnBase64String = null; Aes aes256Item = null; try { aes256Item = Aes.Create(); aes256Item.Padding = PaddingMode.PKCS7; aes256Item.Mode = CipherMode.CBC; ICryptoTransform transform = aes256Item.CreateDecryptor(Encoding.UTF8.GetBytes(key), Encoding.UTF8.GetBytes(iv)); bEnBase64String = Convert.FromBase64String(base64String); result = transform.TransformFinalBlock(bEnBase64String, 0, bEnBase64String.Length); } catch (Exception ex) { throw new Exception($@"Decrypt Fail:{ex.Message}"); } finally { if (aes256Item != null) { aes256Item.Clear(); } } return(Encoding.UTF8.GetString(result)); }
public static bool TestClear(Aes aes) { byte[] key = aes.Key; byte[] IV = aes.IV; try { aes.Clear(); // AESCSP will throw an ObjectDisposedException after class is used after Clear is called. This is reasonable behavior even though // it's different than DESCSP, etc. If the class is still usable (ie the managed version) then make sure the key and IV are not // the same. // if (CompareBytes(aes.Key, key)) { Console.WriteLine("Error - key not reset after Clear"); return(false); } if (CompareBytes(aes.IV, IV)) { Console.WriteLine("Error - IV not reset after Clear"); return(false); } } catch (ObjectDisposedException) { } return(true); }
private static void DecryptPrivateKey(ref FileData fileData) { switch (fileData.privateKeyAlgorithm) { case PrivateKeyAlgorithm.None: return; case PrivateKeyAlgorithm.AES256_CBC: /* create key from passphrase */ SHA1 sha = SHA1.Create(); sha.Initialize(); List <byte> key = new List <byte>(); using (PinnedArray <byte> hashData = new PinnedArray <byte>(cPrivateKeyDecryptSalt1.Length + fileData.passphrase.Length)) { Array.Copy(Encoding.UTF8.GetBytes(cPrivateKeyDecryptSalt1), hashData.Data, cPrivateKeyDecryptSalt1.Length); IntPtr passphrasePtr = Marshal.SecureStringToGlobalAllocUnicode(fileData.passphrase); for (int i = 0; i < fileData.passphrase.Length; i++) { int unicodeChar = Marshal.ReadInt16(passphrasePtr + i * 2); byte ansiChar = Util.UnicodeToAnsi(unicodeChar); hashData.Data[cPrivateKeyDecryptSalt1.Length + i] = ansiChar; Marshal.WriteByte(passphrasePtr, i, 0); } Marshal.ZeroFreeGlobalAllocUnicode(passphrasePtr); sha.ComputeHash(hashData.Data); key.AddRange(sha.Hash); Array.Copy(Encoding.UTF8.GetBytes(cPrivateKeyDecryptSalt2), hashData.Data, cPrivateKeyDecryptSalt2.Length); sha.ComputeHash(hashData.Data); key.AddRange(sha.Hash); } sha.Clear(); /* decrypt private key */ Aes aes = Aes.Create(); aes.KeySize = 256; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.None; int keySize = aes.KeySize / 8; // convert bits to bytes key.RemoveRange(keySize, key.Count - keySize); // remove extra bytes aes.Key = key.ToArray(); Util.ClearByteList(key); aes.IV = new byte[aes.IV.Length]; ICryptoTransform decryptor = aes.CreateDecryptor(); fileData.privateKeyBlob.Data = Util.GenericTransform(decryptor, fileData.privateKeyBlob.Data); decryptor.Dispose(); aes.Clear(); break; default: throw new PpkFormatterException(PpkFormatterException.PpkErrorType.PrivateKeyEncryption); } }
public static byte[] Decrypt(byte[] bytes, string password) { byte[] vectorBytes = Encoding.ASCII.GetBytes(_vector); byte[] saltBytes = Encoding.ASCII.GetBytes(_salt); byte[] decrypted; int decryptedByteCount = 0; using (Aes cipher = Aes.Create()) { PasswordDeriveBytes _passwordBytes = new PasswordDeriveBytes(password, saltBytes, _hash, _iterations); byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8); cipher.Mode = CipherMode.CBC; try { using ICryptoTransform decryptor = cipher.CreateDecryptor(keyBytes, vectorBytes); using MemoryStream from = new MemoryStream(bytes); using (CryptoStream reader = new CryptoStream(from, decryptor, CryptoStreamMode.Read)) { decrypted = new byte[bytes.Length]; decryptedByteCount = reader.Read(decrypted, 0, decrypted.Length); } } catch (Exception ex) { return(null); } cipher.Clear(); } return(decrypted); }
public static byte[] Encrypt(byte[] bytes, string password) { byte[] vectorBytes = Encoding.ASCII.GetBytes(_vector); byte[] saltBytes = Encoding.ASCII.GetBytes(_salt); byte[] encrypted; using (Aes cipher = Aes.Create()) { PasswordDeriveBytes _passwordBytes = new PasswordDeriveBytes(password, saltBytes, _hash, _iterations); byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8); cipher.Mode = CipherMode.CBC; using (ICryptoTransform encryptor = cipher.CreateEncryptor(keyBytes, vectorBytes)) { using MemoryStream to = new MemoryStream(); using (CryptoStream writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write)) { writer.Write(bytes, 0, bytes.Length); writer.FlushFinalBlock(); encrypted = to.ToArray(); } } cipher.Clear(); } return(encrypted); }
/// <summary> /// 加密字节数组 /// </summary> public static byte[] Encrypt(byte[] decodeBytes, string key, bool needIV = false) { decodeBytes.CheckNotNull("decodeBytes"); using (Aes aes = Aes.Create()) { if (aes == null) { throw new HybridException("AES加密时获取加密实例失败"); } aes.Key = CheckKey(key); aes.Padding = PaddingMode.PKCS7; aes.Mode = CipherMode.ECB; byte[] ivBytes = { }; if (needIV) { aes.Mode = CipherMode.CBC; aes.GenerateIV(); ivBytes = aes.IV; } using (ICryptoTransform encryptor = aes.CreateEncryptor()) { byte[] encodeBytes = encryptor.TransformFinalBlock(decodeBytes, 0, decodeBytes.Length); aes.Clear(); return(needIV ? ivBytes.Concat(encodeBytes).ToArray() : encodeBytes); } } }
/// <summary> /// Encrypts a message using AES /// </summary> /// <param name="message">Message byte buffer</param> /// <param name="key">Key used for encryption</param> /// <returns>Encrypted message</returns> public byte[] Encrypt(byte[] message, byte[] key) { int blockSize = int.Parse(Config.GetValue(ConfigConstants.ENCRYPTION_BLOCK_SIZE_BYTES)); Aes aes = CreateAes(key, blockSize); byte padLength = (byte)(message.Length < blockSize ? blockSize - message.Length : message.Length % blockSize); byte[] encrypted = null; using (ICryptoTransform crypto = aes.CreateEncryptor()) { using (MemoryStream ms = new MemoryStream()) { //encrypt using (var cs = new CryptoStream(ms, crypto, CryptoStreamMode.Write)) { //add iv length and iv to buffer unencrypted ms.Write(new byte[] { (byte)aes.IV.Length }, 0, 1); ms.Write(aes.IV, 0, aes.IV.Length); cs.Write(message, 0, message.Length); } encrypted = ms.ToArray(); } } aes.Clear(); return(encrypted); }
private static string DecryptString(string cipherText, byte[] key, byte[] iv) { Aes encryptor = Aes.Create(); if (encryptor != null) { encryptor.Mode = CipherMode.CBC; encryptor.BlockSize = 128; byte[] aesKey = new byte[32]; Array.Copy(key, 0, aesKey, 0, 32); encryptor.Key = aesKey; encryptor.IV = iv; ICryptoTransform aesDecryptor = encryptor.CreateDecryptor(); string plaintext = string.Empty; byte[] cipherBytes = Convert.FromBase64String(cipherText); using (MemoryStream memoryStream = new MemoryStream(cipherBytes)) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aesDecryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(cryptoStream)) { plaintext = srDecrypt.ReadToEnd(); } } } encryptor.Clear(); return(plaintext); } return(null); }
/// <summary> /// /// </summary> /// <param name="plainText">Текст для шифрования</param> /// <param name="key">Ключ шифрования</param> /// <param name="iv">Вектор инициализации</param> /// <returns></returns> private static string EncryptString(string plainText, byte[] key, byte[] iv) { // Instantiate a new Aes object to perform string symmetric encryption Aes encryptor = Aes.Create(); if (encryptor != null) { encryptor.Mode = CipherMode.CBC; encryptor.BlockSize = 128; // Set key and IV byte[] aesKey = new byte[32]; Array.Copy(key, 0, aesKey, 0, 32); encryptor.Key = aesKey; encryptor.IV = iv; // Instantiate a new encryptor from our Aes object ICryptoTransform aesEncryptor = encryptor.CreateEncryptor(); byte[] plainBytes = Encoding.UTF8.GetBytes(plainText); byte[] result = null; using (MemoryStream memoryStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write)) { cryptoStream.Write(plainBytes, 0, plainBytes.Length); cryptoStream.FlushFinalBlock(); result = memoryStream.ToArray(); } } encryptor.Clear(); return(Convert.ToBase64String(result, 0, result.Length));; } return(null); }
public void Dispose() { encryptor.Dispose(); aes.Clear(); CryptoPool.Return(l_dollar); CryptoPool.Return(l_star); }
public static byte[] DecryptAES128(byte[] data, string key, string iv) { byte[] result; Aes aes128Item = null; try { aes128Item = Aes.Create(); aes128Item.Padding = PaddingMode.PKCS7; aes128Item.Mode = CipherMode.CBC; ICryptoTransform tf = aes128Item.CreateDecryptor(Encoding.UTF8.GetBytes(key), Encoding.UTF8.GetBytes(iv)); using (var ms = new MemoryStream()) using (var cryptoStream = new CryptoStream(ms, tf, CryptoStreamMode.Write)) { cryptoStream.Write(data, 0, data.Length); cryptoStream.FlushFinalBlock(); result = ms.ToArray(); } } finally { if (aes128Item != null) { aes128Item.Clear(); } } return(result); }
private static string encryptStringToBytes_AES(string text) { if (text == null || text.Length <= 0) { throw new ArgumentNullException("text"); } // Declare the Aes object // used to encrypt the data. Aes aesAlg = null; // Declare the bytes used to hold the // encrypted data. string encrypted = null; try { Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(_secret, _salt); // Create an Aes object // with the specified key and IV. aesAlg = Aes.Create(); aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8); var iv = aesAlg.IV; aesAlg.IV = iv; // Create a decrytor to perform the stream transform. ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msEncrypt = new MemoryStream()) { //prepend the IV msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int)); msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length); using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(text); } } encrypted = Convert.ToBase64String(msEncrypt.ToArray()); } } finally { // Clear the Aes object. if (aesAlg != null) { aesAlg.Clear(); } } return(encrypted); }
protected override void Dispose(bool disposing) { if (disposing) { #if !OS_WINDOWS _impl.Dispose(); #else _impl.Clear(); #endif } }
/// <summary> /// Decrypts a byte array to a byte array. /// </summary> /// <param name="source"></param> /// <returns></returns> public static byte[] Decrypt(byte[] source, string key) { Aes aes = null; MemoryStream memoryStream = null; try { //Generate a Key based on a Password and HMACSHA1 pseudo-random number generator //Salt must be at least 8 bytes long //Use an iteration count of at least 1000 Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(key, Encoding.UTF8.GetBytes(ItsCrypto.EncryptionSalt), 1000); //Create AES algorithm aes = Aes.Create(); //Key derived from byte array with 32 pseudo-random key bytes aes.Key = rfc2898.GetBytes(32); //IV derived from byte array with 16 pseudo-random key bytes aes.IV = rfc2898.GetBytes(16); //Create Memory and Crypto Streams memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write); //Decrypt Data byte[] data = source; // Convert.FromBase64String(this.textBoxEncrypt.Text);//dataToDecrypt); cryptoStream.Write(data, 0, data.Length); cryptoStream.FlushFinalBlock(); //Return Decrypted String byte[] decryptBytes = memoryStream.ToArray(); //Dispose if (cryptoStream != null) { cryptoStream.Dispose(); } //Retval return(decryptBytes); //this.textBoxResult.Text = Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length); } finally { if (memoryStream != null) { memoryStream.Dispose(); } if (aes != null) { aes.Clear(); } } }
private static string deAes(byte[] cipherText, byte[] key, byte[] iv) { if (cipherText == null || cipherText.Length <= 0) { throw new ArgumentNullException("cipherText"); } if (key == null || key.Length <= 0) { throw new ArgumentNullException("key"); } if (iv == null || iv.Length <= 0) { throw new ArgumentNullException("iv"); } MemoryStream msDecrypt = null; CryptoStream csDecrypt = null; StreamReader srDecrypt = null; Aes aesAlg = null; string plaintext = null; try { aesAlg = Aes.Create(); aesAlg.Key = key; aesAlg.IV = iv; ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); msDecrypt = new MemoryStream(cipherText); csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); srDecrypt = new StreamReader(csDecrypt); plaintext = srDecrypt.ReadToEnd(); } finally { if (srDecrypt != null) { srDecrypt.Close(); } if (csDecrypt != null) { csDecrypt.Close(); } if (msDecrypt != null) { msDecrypt.Close(); } if (aesAlg != null) { aesAlg.Clear(); } } return(plaintext); }
protected virtual void Dispose(bool disposing) { if (_aes == null) { return; } if (disposing) { _aes.Clear(); _aes = null; } }
private static byte[] enAes(string plainText, byte[] key, byte[] iv) { if (plainText == null || plainText.Length <= 0) { throw new ArgumentNullException("plainText"); } if (key == null || key.Length <= 0) { throw new ArgumentNullException("key"); } if (iv == null || iv.Length <= 0) { throw new ArgumentNullException("iv"); } MemoryStream msEncrypt = null; CryptoStream csEncrypt = null; StreamWriter swEncrypt = null; Aes aesAlg = null; try { aesAlg = Aes.Create(); aesAlg.Key = key; aesAlg.IV = iv; ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); msEncrypt = new MemoryStream(); csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write); swEncrypt = new StreamWriter(csEncrypt); swEncrypt.Write(plainText); } finally { if (swEncrypt != null) { swEncrypt.Close(); } if (csEncrypt != null) { csEncrypt.Close(); } if (msEncrypt != null) { msEncrypt.Close(); } if (aesAlg != null) { aesAlg.Clear(); } } return(msEncrypt.ToArray()); }
// Carries out disposing of AES object protected virtual void Dispose(bool isDisposing) { if (!_isDisposed) { if (isDisposing) { if (_aes != null) { _aes.Clear(); } } _isDisposed = true; } }
private static string DecryptFile(string cipherTextFile, string decryptedOutput, byte[] key) { string plaintext = null; using (Aes aesAlg = Aes.Create()) { try { aesAlg.Key = key; // Wipe out key material from memory Array.Clear(key, 0, key.Length); // calculate IV Size and Extract from ciphertext byte[] iv = new byte[aesAlg.BlockSize / 8]; using (var fsCrypt = new FileStream(cipherTextFile, FileMode.Open)) { // Read in IV from file stream. fsCrypt.Read(iv, 0, iv.Length); aesAlg.IV = iv; aesAlg.Mode = CIPHER_MODE_CBC; using (FileStream fsOut = new FileStream(decryptedOutput, FileMode.Create)) { using (ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV)) { using (var cs = new CryptoStream(fsCrypt, decryptor, CryptoStreamMode.Read)) { using (var sr = new StreamReader(cs)) { int data; while ((data = cs.ReadByte()) != -1) { fsOut.WriteByte((byte)data); } } } } } } } finally { aesAlg.Clear(); } } return(plaintext); }
public static string RFIDecrypt(string cipherText, string encryptionKey) { // will return plain text string plainText = string.Empty; try { if (!String.IsNullOrWhiteSpace(cipherText)) { // get salted cipher array byte[] saltedCipherBytes = Convert.FromBase64String(cipherText); // create array to hold salt byte[] salt = new byte[16]; // create array to hold cipher byte[] cipherBytes = new byte[saltedCipherBytes.Length - salt.Length]; // copy salt/cipher to arrays Array.Copy(saltedCipherBytes, 0, salt, 0, salt.Length); Array.Copy(saltedCipherBytes, salt.Length, cipherBytes, 0, saltedCipherBytes.Length - salt.Length); // create new password derived bytes using password/salt using (Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(encryptionKey, salt)) { using (Aes aes = AesManaged.Create()) { // Generate key and iv from password/salt and pass to aes aes.Key = pdb.GetBytes(aes.KeySize / 8); aes.IV = pdb.GetBytes(aes.BlockSize / 8); // Open a new memory stream to write the encrypted data to using (MemoryStream ms = new MemoryStream()) { // Create a crypto stream to perform decryption using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write)) { // write decrypted data to memory cs.Write(cipherBytes, 0, cipherBytes.Length); } // convert decrypted array to plain text string plainText = Encoding.Unicode.GetString(ms.ToArray()); } aes.Clear(); } } } } catch (Exception) { return(string.Empty); } return(plainText); }
public static string AESDecrypt(string cipher) { MemoryStream msDecrypt = null; CryptoStream csDecrypt = null; StreamReader srDecrypt = null; Aes aesAlg = null; string letter = null; try { var decryptedBuffer = Base64ToBytes(cipher); aesAlg = Aes.Create(); aesAlg.Key = Encoding.UTF8.GetBytes(Key); aesAlg.IV = Encoding.UTF8.GetBytes(IV); var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); msDecrypt = new MemoryStream(decryptedBuffer); csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); srDecrypt = new StreamReader(csDecrypt); letter = srDecrypt.ReadToEnd(); } catch (Exception ex) { AppConnectLogHelper.Error("AES解密失败:cipher=" + cipher, ex); return(null); } finally { if (srDecrypt != null) { srDecrypt.Close(); } if (csDecrypt != null) { csDecrypt.Close(); } if (msDecrypt != null) { msDecrypt.Close(); } if (aesAlg != null) { aesAlg.Clear(); } } return(letter); }
public string AESdecrypt(byte[] cipherText, byte[] Key, byte[] IV) { if (cipherText == null || cipherText.Length <= 0) { throw new ArgumentNullException("cipherText"); } ValidarArgumentos(Key, IV); MemoryStream msDecrypt = null; CryptoStream csDecrypt = null; StreamReader srDecrypt = null; Aes aesAlg = null; string plaintext = null; try { aesAlg = Aes.Create(); aesAlg.Key = Key; aesAlg.IV = IV; ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); msDecrypt = new MemoryStream(cipherText); csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); srDecrypt = new StreamReader(csDecrypt); plaintext = srDecrypt.ReadToEnd(); } finally { if (srDecrypt != null) { srDecrypt.Close(); } if (csDecrypt != null) { csDecrypt.Close(); } if (msDecrypt != null) { msDecrypt.Close(); } if (aesAlg != null) { aesAlg.Clear(); } } return(plaintext); }