private String Encrypt(string _inputText, string _encryptionKey, string _initVector) { string _out = ""; _pwd = Encoding.UTF8.GetBytes(_encryptionKey); _ivBytes = Encoding.UTF8.GetBytes(_initVector); int len = _pwd.Length; if (len > _key.Length) { len = _key.Length; } int ivLenth = _ivBytes.Length; if (ivLenth > _iv.Length) { ivLenth = _iv.Length; } Array.Copy(_pwd, _key, len); Array.Copy(_ivBytes, _iv, ivLenth); _rcipher.Key = _key; _rcipher.IV = _iv; byte[] plainText = _rcipher.CreateEncryptor().TransformFinalBlock(_enc.GetBytes(_inputText), 0, _inputText.Length); _out = Convert.ToBase64String(plainText); _rcipher.Clear(); _rcipher.Dispose(); return(_out); }
} //end StringToByteArray /// <summary> /// Dispose RijndaelManaged object initialized in the constructor /// </summary> public void Dispose() { if (rijn != null) { rijn.Dispose(); } } //end Dispose()
public static byte[] DecrypteCBC(byte[] toDecryptArray, byte[] keyArray, byte[] ivArray, bool isPadding = false) { if (toDecryptArray.Length % 16 > 0) { Trace.WriteLine("AESdecryptCBC: data length not /16, truncating"); toDecryptArray = new byte[toDecryptArray.Length / 16 * 16]; } RijndaelManaged rijndael = new RijndaelManaged { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros, Key = keyArray, IV = ivArray ?? ZEROIV }; byte[] result; using (ICryptoTransform cTransform = rijndael.CreateDecryptor()) { result = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length); } rijndael.Dispose(); if (isPadding) { return(RemovePadding(16, result)); } return(result); }
public int RSAStorePrivateKey(string filename, string PrivateKey, string password) { try { RijndaelManaged AES = new RijndaelManaged(); AES.KeySize = 256; AES.GenerateIV(); byte[] Passkey = AESCreateKey(password); string pKey = Convert.ToBase64String(IVCipher(AES.IV, AESEncrypt(Encoding.UTF8.GetBytes(PrivateKey), Passkey, AES.IV)), Base64FormattingOptions.InsertLineBreaks); if (AES != null) { AES.Dispose(); } using (StreamWriter sw = new StreamWriter(filename)) { sw.WriteLine("-----BEGIN PRIVATE KEY-----"); sw.WriteLine(pKey); sw.WriteLine("-----END PRIVATE KEY-----"); } return(0); } catch { return(1); } }
public void Dispose() { Engine.Dispose(); HashProvider.Dispose(); HashBytes = null; _Password = null; }
private string Encrypt(string textToEncrypt, string key) { RijndaelManaged rijndaelCipher = new RijndaelManaged { Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7, KeySize = 128, BlockSize = 128 }; byte[] pwdBytes = Encoding.UTF8.GetBytes(key); byte[] keyBytes = new byte[16]; int len = pwdBytes.Length; if (len > keyBytes.Length) { len = keyBytes.Length; } Array.Copy(pwdBytes, keyBytes, len); rijndaelCipher.Key = pwdBytes; rijndaelCipher.IV = keyBytes; ICryptoTransform transform = rijndaelCipher.CreateEncryptor(); byte[] plainText = Encoding.UTF8.GetBytes(textToEncrypt); rijndaelCipher.Dispose(); return(Convert.ToBase64String(transform.TransformFinalBlock(plainText, 0, plainText.Length))); }
/// <summary> /// aes256 解密 /// </summary> /// <param name="encryptStr"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <returns></returns> public static string Decrypt(string encryptStr, byte[] key, byte[] iv) { byte[] toEncryptArray = Convert.FromBase64String(encryptStr); using (var rijAlg = new RijndaelManaged()) { //Settings rijAlg.Mode = CipherMode.CBC; //rijAlg.Padding = PaddingMode.PKCS7; rijAlg.KeySize = 256; // Create a decrytor to perform the stream transform. var decryptor = rijAlg.CreateDecryptor(key, iv); // Create the streams used for decryption. using (var msDecrypt = new MemoryStream(toEncryptArray)) { using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (var srDecrypt = new StreamReader(csDecrypt)) { // Read the decrypted bytes from the decrypting stream // and place them in a string. encryptStr = srDecrypt.ReadToEnd(); srDecrypt.Dispose(); } csDecrypt.Dispose(); } msDecrypt.Dispose(); } rijAlg.Dispose(); } return(encryptStr); }
private static string encryptDecrypt(string _inputText, string _encryptionKey, EncryptMode _mode, string _initVector) { string _out = ""; // output string //_encryptionKey = MD5Hash (_encryptionKey); using (RijndaelManaged _rcipher = GetProvider(_encryptionKey, _initVector)) { UTF8Encoding _enc = new UTF8Encoding(); try { if (_mode.Equals(EncryptMode.ENCRYPT)) { //encrypt byte[] plainText = _rcipher.CreateEncryptor().TransformFinalBlock(_enc.GetBytes(_inputText), 0, _inputText.Length); _out = Convert.ToBase64String(plainText); } if (_mode.Equals(EncryptMode.DECRYPT)) { //decrypt byte[] plainText = _rcipher.CreateDecryptor().TransformFinalBlock(Convert.FromBase64String(_inputText), 0, Convert.FromBase64String(_inputText).Length); _out = _enc.GetString(plainText); } } catch (Exception ex) { throw; } finally { _rcipher.Dispose(); } } return(_out); // return encrypted/decrypted string }
/// <summary> /// /// </summary> /// <param name="text"></param> /// <param name="saltValue"></param> /// <param name="passPhrase"></param> /// <param name="hashAlgorithm"></param> /// <param name="passwordIterations"></param> /// <param name="initVector"></param> /// <returns></returns> private static string Decryption(string text, string saltValue, string passPhrase, string hashAlgorithm, int passwordIterations, string initVector) { try { saltValue = saltValue.ToLower(); var bytes = Encoding.ASCII.GetBytes(initVector); var rgbSalt = Encoding.ASCII.GetBytes(saltValue); var buffer = Convert.FromBase64String(text); var rgbKey = new PasswordDeriveBytes(passPhrase, rgbSalt, hashAlgorithm, passwordIterations).GetBytes(KeySize / 8); var managed = new RijndaelManaged { Mode = CipherMode.CBC }; var transform = managed.CreateDecryptor(rgbKey, bytes); var stream = new MemoryStream(buffer); var stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Read); var buffer5 = new byte[buffer.Length]; var count = stream2.Read(buffer5, 0, buffer5.Length); stream.Close(); stream.Dispose(); stream2.Close(); stream2.Dispose(); transform.Dispose(); managed.Dispose(); return(Encoding.UTF8.GetString(buffer5, 0, count)); } catch (Exception) { return(text); } }
private string Decrypt(string textToDecrypt, string key) { RijndaelManaged rijndaelCipher = new RijndaelManaged { Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7, KeySize = 128, BlockSize = 128 }; byte[] encryptedData = Convert.FromBase64String(textToDecrypt); byte[] pwdBytes = Encoding.UTF8.GetBytes(key); byte[] keyBytes = new byte[16]; int len = pwdBytes.Length; if (len > keyBytes.Length) { len = keyBytes.Length; } Array.Copy(pwdBytes, keyBytes, len); rijndaelCipher.Key = pwdBytes; rijndaelCipher.IV = keyBytes; byte[] plainText = rijndaelCipher.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length); rijndaelCipher.Dispose(); return(Encoding.UTF8.GetString(plainText)); }
/// <summary> /// /// </summary> /// <param name="text"></param> /// <param name="saltValue"></param> /// <param name="passPhrase"></param> /// <param name="hashAlgorithm"></param> /// <param name="passwordIterations"></param> /// <param name="initVector"></param> /// <returns></returns> private static string Encrypt(string text, string saltValue, string passPhrase, string hashAlgorithm, int passwordIterations, string initVector) { try { saltValue = saltValue.ToLower(); var bytes = Encoding.ASCII.GetBytes(initVector); var rgbSalt = Encoding.ASCII.GetBytes(saltValue); var buffer = Encoding.UTF8.GetBytes(text); var rgbKey = new PasswordDeriveBytes(passPhrase, rgbSalt, hashAlgorithm, passwordIterations).GetBytes(KeySize / 8); var managed = new RijndaelManaged { Mode = CipherMode.CBC }; var transform = managed.CreateEncryptor(rgbKey, bytes); var stream = new MemoryStream(); var stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write); stream2.Write(buffer, 0, buffer.Length); stream2.FlushFinalBlock(); var inArray = stream.ToArray(); stream.Close(); stream.Dispose(); stream2.Close(); stream2.Dispose(); transform.Dispose(); managed.Dispose(); return(Convert.ToBase64String(inArray)); } catch { return(text); } }
public static string Decrypt(string encyrptedText, string key) { byte[] cipherTextBytesWithSaltAndIv = Convert.FromBase64String(encyrptedText); byte[] saltStringBytes = cipherTextBytesWithSaltAndIv.Take(KEY_SIZE / 8).ToArray(); byte[] ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(KEY_SIZE / 8) .Take(KEY_SIZE / 8).ToArray(); byte[] cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip(KEY_SIZE / 8 * 2) .Take(cipherTextBytesWithSaltAndIv.Length - KEY_SIZE / 8 * 2).ToArray(); Rfc2898DeriveBytes password = new Rfc2898DeriveBytes(key, saltStringBytes, ITERATIONS_COUNT); byte[] keyBytes = password.GetBytes(KEY_SIZE / 8); RijndaelManaged symmetricKey = new RijndaelManaged { BlockSize = 256, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }; ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes); MemoryStream memoryStream = new MemoryStream(cipherTextBytes); CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read); byte[] plainTextBytes = new byte[cipherTextBytes.Length]; int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); memoryStream.Close(); cryptoStream.Close(); password.Dispose(); symmetricKey.Dispose(); decryptor.Dispose(); memoryStream.Dispose(); cryptoStream.Dispose(); return(Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)); }
public static string Encrypt(string plainText, string key) { byte[] saltStringBytes = Generate256BitsOfRandomEntropy(); byte[] ivStringBytes = Generate256BitsOfRandomEntropy(); byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); Rfc2898DeriveBytes password = new Rfc2898DeriveBytes(key, saltStringBytes, ITERATIONS_COUNT); byte[] keyBytes = password.GetBytes(KEY_SIZE / 8); RijndaelManaged symmetricKey = new RijndaelManaged { BlockSize = 256, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }; ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write); cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); byte[] cipherTextBytes = saltStringBytes; cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray(); cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray(); memoryStream.Close(); cryptoStream.Close(); cryptoStream.Dispose(); memoryStream.Dispose(); encryptor.Dispose(); symmetricKey.Dispose(); password.Dispose(); return(Convert.ToBase64String(cipherTextBytes)); }
/// <summary> /// AES对称解密 /// </summary> /// <param name="encryptBytes">要解密的二进制数据,如果是一个对象,该对象必须实现了<see cref="SerializableAttribute"/></param> /// <param name="privateKey">加密的私钥</param> /// <returns></returns> public static object DeEncryptAES(byte[] encryptBytes, string privateKey) { object result = null; if (StringUtil.IsNullOrEmpty(encryptBytes)) { return(result); } RijndaelManaged managed = (RijndaelManaged)GetEncryptFactory <RijndaelManaged>(privateKey, 16); try { byte[] deencryptResult = Encrypt(managed.CreateDecryptor(), encryptBytes); result = SerializeUtil.FromBinary <object>(deencryptResult); } catch (CryptographicException ex) { throw ex; } catch (SerializationException ex) { throw new SerializationException("解密时序列化失败,无法反序列化对象", ex); } finally { managed.Dispose(); } return(result); }
public static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes) { byte[] result = null; byte[] salt = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8 }; MemoryStream val = new MemoryStream(); try { RijndaelManaged val2 = new RijndaelManaged(); try { val2.KeySize = 256; val2.BlockSize = 128; Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(passwordBytes, salt, 1000); val2.Key = rfc2898DeriveBytes.GetBytes(val2.KeySize / 8); val2.IV = rfc2898DeriveBytes.GetBytes(val2.BlockSize / 8); val2.Mode = CipherMode.CBC; using (CryptoStream cryptoStream = new CryptoStream(val, val2.CreateDecryptor(), CryptoStreamMode.Write)) { cryptoStream.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length); cryptoStream.Close(); } result = val.ToArray(); } finally { val2?.Dispose(); } } finally { val?.Dispose(); } return(result); }
protected virtual void Dispose(bool disposing) { if (disposing) { _rijndaelManaged.Dispose(); _rsa.Dispose(); } }
private String encryptDecrypt(string _inputText, string _encryptionKey, EncryptMode _mode, string _initVector) { string _out = ""; //get hashed pin code to bytes array _pwd = Encoding.UTF8.GetBytes(_encryptionKey); //get IV to byte array _ivBytes = Encoding.UTF8.GetBytes(_initVector); //check that the IV and hashed key are the correct size in bytes int len = _pwd.Length; if (len > _key.Length) { len = _key.Length; } int ivLenth = _ivBytes.Length; if (ivLenth > _iv.Length) { ivLenth = _iv.Length; } //copy hashed pincode and IV bytes to AES key and IV Array.Copy(_pwd, _key, len); Array.Copy(_ivBytes, _iv, ivLenth); _rcipher.Key = _key; _rcipher.IV = _iv; //encrypt mode if (_mode.Equals(EncryptMode.ENCRYPT)) { //encrypt the password byte[] plainText = _rcipher.CreateEncryptor().TransformFinalBlock(_enc.GetBytes(_inputText), 0, _inputText.Length); //combine the ciphertext and the IV so we can use it later byte[] combined = new byte[_iv.Length + plainText.Length]; System.Buffer.BlockCopy(_iv, 0, combined, 0, _iv.Length); System.Buffer.BlockCopy(plainText, 0, combined, _iv.Length, plainText.Length); //convert ciphertext bytes to hex _out = Convert.ToBase64String(combined); } //decrypt mode if (_mode.Equals(EncryptMode.DECRYPT)) { //decrypt the ciphertext back to plaintext using the same IV byte[] plainText = _rcipher.CreateDecryptor().TransformFinalBlock(Convert.FromBase64String(_inputText), 0, Convert.FromBase64String(_inputText).Length); //convert plaintext bytes back to hex String outputToString = _enc.GetString(plainText); //remove IV from plaintext String trimmed = outputToString.Remove(0, _iv.Length - 1); _out = trimmed; } _rcipher.Dispose(); return(_out); }
/// <summary> /// Decrypt the given string. Assumes the string was encrypted using /// EncryptStringAES(), using an identical sharedSecret. /// </summary> /// <param name="cipherText">The text to decrypt.</param> /// <param name="sharedSecret">A password used to generate a key for decryption.</param> public static string DecryptStringAES(string cipherText, string sharedSecret) { if (string.IsNullOrEmpty(cipherText)) { throw new ArgumentNullException("cipherText"); } if (string.IsNullOrEmpty(sharedSecret)) { throw new ArgumentNullException("sharedSecret"); } // Declare the RijndaelManaged object // used to decrypt the data. RijndaelManaged aesAlg = null; // Declare the string used to hold // the decrypted text. string plaintext = null; try { // generate the key from the shared secret and the salt var key = new Rfc2898DeriveBytes(sharedSecret, Salt); // Create the streams used for decryption. byte[] bytes = Convert.FromBase64String(cipherText); using (var msDecrypt = new MemoryStream(bytes)) { // Create a RijndaelManaged object // with the specified key and IV. aesAlg = new RijndaelManaged(); aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8); // Get the initialization vector from the encrypted stream aesAlg.IV = ReadByteArray(msDecrypt); // Create a decrytor to perform the stream transform. ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (var srDecrypt = new StreamReader(csDecrypt)) // Read the decrypted bytes from the decrypting stream // and place them in a string. plaintext = srDecrypt.ReadToEnd(); } } } finally { // Clear the RijndaelManaged object. if (aesAlg != null) { aesAlg.Clear(); aesAlg.Dispose(); } } return(plaintext); }
public static string EncryptStringAES(string plainText) { if (string.IsNullOrEmpty(plainText)) { throw new ArgumentNullException("plainText"); } string encryptedString = null; // Encrypted string to return. RijndaelManaged aesAlgorithm = null; // RijndaelManaged object used to encrypt the data. try { // Generate the key from a shared secret and initilization vector. Rfc2898DeriveBytes key = new Rfc2898DeriveBytes("https://github.com/R-Smith/vmPing" + Environment.MachineName, Encoding.ASCII.GetBytes(Environment.UserName + "@@vmping-salt@@")); // Create a RijndaelManaged object. aesAlgorithm = new RijndaelManaged(); aesAlgorithm.Padding = PaddingMode.PKCS7; aesAlgorithm.Key = key.GetBytes(aesAlgorithm.KeySize / 8); if (key != null) { key.Dispose(); } // Create a decryptor to perform the stream transform. ICryptoTransform encryptor = aesAlgorithm.CreateEncryptor(aesAlgorithm.Key, aesAlgorithm.IV); // Create the streams used for encryption. using (MemoryStream memoryStream = new MemoryStream()) { // Prepend the IV. memoryStream.Write(BitConverter.GetBytes(aesAlgorithm.IV.Length), 0, sizeof(int)); memoryStream.Write(aesAlgorithm.IV, 0, aesAlgorithm.IV.Length); using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { using (StreamWriter streamWriter = new StreamWriter(cryptoStream)) { // Write all data to the stream. streamWriter.Write(plainText); } } encryptedString = Convert.ToBase64String(memoryStream.ToArray()); } } finally { // Clear the RijndaelManaged object. if (aesAlgorithm != null) { aesAlgorithm.Clear(); } aesAlgorithm.Dispose(); } // Return the encrypted bytes from the memory stream. return(encryptedString); }
public void Dispose() { if (m_aesAlg != null) { m_aesAlg.Clear(); m_aesAlg.Dispose(); m_aesAlg = null; } }
/// <inheritdoc /> public void Dispose() { CryptoStream.Flush(); CryptoStream.Dispose(); _transform.Dispose(); _symmetricKey.Dispose(); _key.Dispose(); }
public byte[] CreateIV() { var r = new RijndaelManaged(); r.GenerateIV(); var result = r.IV; r.Dispose(); return(result); }
public PasswordSheet DecryptFile() { PasswordSheet decryptedData = null; FileStream stream = null; PasswordDeriveBytes secretKey = null; RijndaelManaged rijndaelCipher = null; ICryptoTransform decryptor = null; CryptoStream cryptoStream = null; try { rijndaelCipher = new RijndaelManaged(); // Making of the key for decryption secretKey = GetPasswordBytes(); // Creates a symmetric Rijndael decryptor object. decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)); stream = new FileStream(_fileName, FileMode.Open, FileAccess.Read); // Defines the cryptographics stream for decryption.THe stream contains decrpted data cryptoStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read); XmlSerializer serializer = new XmlSerializer(typeof(PasswordSheet)); decryptedData = (PasswordSheet)serializer.Deserialize(cryptoStream); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } finally { if (stream != null) { stream.Dispose(); } if (secretKey != null) { secretKey.Dispose(); } if (rijndaelCipher != null) { rijndaelCipher.Dispose(); } if (cryptoStream != null) { cryptoStream.Dispose(); } } return(decryptedData); }
public void EncryptFile(PasswordSheet sheet) { FileStream stream = null; PasswordDeriveBytes secretKey = null; RijndaelManaged rijndaelCipher = null; ICryptoTransform encryptor = null; CryptoStream cryptoStream = null; try { stream = new FileStream(_fileName, FileMode.OpenOrCreate, FileAccess.Write); stream.SetLength(0); secretKey = GetPasswordBytes(); rijndaelCipher = new RijndaelManaged(); encryptor = rijndaelCipher.CreateEncryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)); // Defines a stream that links data streams to cryptographic transformations cryptoStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write); byte[] data = null; using (var sheetStream = new MemoryStream()) { XmlSerializer serializer = new XmlSerializer(typeof(PasswordSheet)); serializer.Serialize(sheetStream, sheet); data = sheetStream.GetBuffer(); } cryptoStream.Write(data, 0, data.Length); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } finally { if (secretKey != null) { secretKey.Dispose(); } if (rijndaelCipher != null) { rijndaelCipher.Dispose(); } if (cryptoStream != null) { cryptoStream.Dispose(); } } }
/// <summary> /// Protected implementation of Dispose pattern. /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (disposed) { return; } rijndael?.Dispose(); disposed = true; }
void Dispose(bool disposing) { // would be protected virtual if not sealed if (disposing && !_disposed) { // only run this logic when Dispose is called // and anything else that touches managed objects _rijndael.Dispose(); //_encryptor.Dispose(); _disposed = true; GC.SuppressFinalize(this); } }
protected virtual void Dispose(bool disposing) { if (disposing) { if (_aes != null) { _aes.Dispose(); _aes = null; } } }
/// <summary> /// バイト配列を復号化する /// </summary> /// <param name="tCryptoData">暗号化されたバイト配列</param> /// <param name="tKey">暗号化キー</param> /// <param name="tVector">暗号化ベクター</param> /// <returns>復号化されたバイト配列</returns> public static byte[] Decrypt(byte[] cryptoData, string key, string vector) { // 暗号化用の種別オブジェクト生成 // TripleDESCryptoServiceProvider tKind = new TripleDESCryptoServiceProvider() ; RijndaelManaged kind = new RijndaelManaged() { Padding = PaddingMode.Zeros, Mode = CipherMode.CBC, KeySize = 256, BlockSize = 256 }; //----------------------------------------------------- // 暗号用のキー情報をセットする byte[] aKey = Encoding.UTF8.GetBytes(key); byte[] aVector = Encoding.UTF8.GetBytes(vector); ICryptoTransform decryptor = kind.CreateDecryptor(aKey, aVector); //----------------------------------------------------- byte[] data = new byte[cryptoData.Length]; //----------------------------------------------------- MemoryStream memoryStream = new MemoryStream(cryptoData); // 復号化 CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read); cryptoStream.Read(data, 0, data.Length); cryptoStream.Close(); memoryStream.Close(); //----------------------------------------------------- decryptor.Dispose(); kind.Clear(); kind.Dispose(); //----------------------------------------------------- long size = (( long )data[0] << 0) | (( long )data[1] << 8) | (( long )data[2] << 16) | (( long )data[3]); byte[] originalData = new byte[size]; System.Array.Copy(data, 4, originalData, 0, size); return(originalData); }
/// <summary> /// static declerations for this scope only /// </summary> /// <param name="textToBeDecrypted">this is decrypted text</param> /// <returns>it return th string</returns> public static string Decrypt(string textToBeDecrypted) { RijndaelManaged rijndaelCipher = null; const string Password = "******"; string decryptedData; MemoryStream memoryStream = null; PasswordDeriveBytes secretKey = null; try { byte[] encryptedData = Convert.FromBase64String(textToBeDecrypted); rijndaelCipher = new RijndaelManaged(); byte[] salt = Encoding.ASCII.GetBytes(Password.Length.ToString(CultureInfo.InvariantCulture)); ////Making of the key for decryption secretKey = new PasswordDeriveBytes(Password, salt); ////Creates a symmetric Rijndael decryptor object. ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)); memoryStream = new MemoryStream(encryptedData); ////Defines the cryptographics stream for decryption.THe stream contains decrpted data CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read); byte[] plainText = new byte[encryptedData.Length]; int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length); ////Converting to string decryptedData = Encoding.UTF8.GetString(plainText, 0, decryptedCount); return(decryptedData); } catch { decryptedData = textToBeDecrypted; throw; } finally { // cryptoStream.Close(); if (rijndaelCipher != null) { rijndaelCipher.Dispose(); } if (memoryStream != null) { memoryStream.Dispose(); } if (secretKey != null) { secretKey.Dispose(); } } }
/// <summary> /// AES对称加密 /// </summary> /// <param name="content">要加密的内容,如果是一个对象必须要实现<see cref="SerializableAttribute"/></param> /// <param name="privateKey">加密的密钥</param> /// <returns></returns> public static byte[] EncryptAES(object content, string privateKey) { byte[] result = new byte[0]; if (StringUtil.IsNullOrEmpty(content)) { return(result); } RijndaelManaged managed = (RijndaelManaged)GetEncryptFactory <RijndaelManaged>(privateKey, 16); result = Encrypt(managed.CreateEncryptor(), SerializeUtil.ToBinary(content)); managed.Dispose(); return(result); }