public string Decrypt(string encryptedContent, string password) { if (!KeyProvider.CorrectPassword(password)) { throw new Exception("Password isn`t correct"); } var buffer = Convert.FromBase64String(encryptedContent); string decrypted; var transform = GetDecryptor(); using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, transform, CryptoStreamMode.Write)) { cs.Write(buffer, 0, buffer.Length); cs.FlushFinalBlock(); cs.Clear(); cs.Close(); decrypted = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); } } return(decrypted); }
/// <summary> /// EncryptBase64 /// </summary> /// <param name="StringToEncrypt"></param> /// <param name="Key"></param> /// <param name="IV"></param> /// <returns></returns> private static string EncryptBase64(string StringToEncrypt, byte[] Key, byte[] IV) { TripleDESCryptoServiceProvider tripledes; MemoryStream ms; CryptoStream cs; try { tripledes = new TripleDESCryptoServiceProvider(); byte[] inputByteArray = Encoding.UTF8.GetBytes(StringToEncrypt); ms = new MemoryStream(); cs = new CryptoStream(ms, tripledes.CreateEncryptor(Key, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); String str = Convert.ToBase64String(ms.ToArray()); cs.Clear(); tripledes.Dispose(); return(str); } catch (Exception) { throw; } finally { tripledes = null; ms = null; cs = null; } }
/// <summary> /// Encrypto byte array /// </summary> /// <param name="source">The source bytes need to encrypto</param> /// <returns>The bytes after crypto</returns> public byte[] Encrypto(byte[] source) { if (source == null || source.Length == 0) { return(null); } byte[] bytIn = source; byte[] bytOut = null; try { using (MemoryStream ms = new MemoryStream()) { _objCryptoService.Key = GetLegalKey(); _objCryptoService.IV = GetLegalIV(); ICryptoTransform encrypto = _objCryptoService.CreateEncryptor(); using (CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write)) { cs.Write(bytIn, 0, bytIn.Length); cs.FlushFinalBlock(); bytOut = ms.ToArray(); cs.Clear(); cs.Close(); } ms.Close(); } return(bytOut); } catch (Exception) { return(null); } }
Encrypt( byte[] data) { byte[] result = null; using (MemoryStream encryptionStream = new MemoryStream()) { // Create the crypto stream using (CryptoStream encrypt = new CryptoStream( encryptionStream, _encryptor, CryptoStreamMode.Write)) { encrypt.Write(data, 0, data.Length); encrypt.FlushFinalBlock(); encrypt.Clear(); //encrypt.Close(); } result = encryptionStream.ToArray(); } return result; }
public T Encrypt <T>(T obj) { manager.Key = ToByte(context.Session.GetString("StorageKey")); manager.IV = ToByte(context.Session.GetString("StorageIV")); Type type = obj.GetType(); MemoryStream memoryStream; CryptoStream cryptoStream; foreach (PropertyInfo p in type.GetProperties()) { if (p.PropertyType != typeof(string)) { continue; } if (p.GetValue(obj) == null) { continue; } memoryStream = new MemoryStream(); cryptoStream = new CryptoStream(memoryStream, manager.CreateEncryptor(manager.Key, manager.IV), CryptoStreamMode.Write); byte[] property = ToByte(p.GetValue(obj).ToString()); cryptoStream.Write(property, 0, property.Length); cryptoStream.FlushFinalBlock(); cryptoStream.Clear(); p.SetValue(obj, ToString(memoryStream.ToArray())); memoryStream.Close(); } return(obj); }
/// <summary> /// DES算法解密 /// </summary> /// <param name="pToDecrypt">密文</param> /// <param name="sKey">加密Key</param> /// <returns></returns> public static string DesDecrypt(string pToDecrypt, string sKey) { TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider(); byte[] buffer = new byte[pToDecrypt.Length / 2]; for (int i = 0; i < (pToDecrypt.Length / 2); i++) { int num2 = Convert.ToInt32(pToDecrypt.Substring(i * 2, 2), 0x10); buffer[i] = (byte)num2; } provider.Key = new MD5CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(sKey)); provider.Mode = CipherMode.ECB; provider.Padding = PaddingMode.PKCS7; MemoryStream stream = new MemoryStream(); CryptoStream crypto = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write); crypto.Write(buffer, 0, buffer.Length); crypto.FlushFinalBlock(); string builder = Encoding.UTF8.GetString(stream.ToArray()); stream.Close(); crypto.Clear(); crypto.Close(); provider.Clear(); return(builder); }
public byte[] ConvertFile(byte[] plain, string password, AESProcess process) { try { using (var pass = new PasswordDeriveBytes(password, this.GenerateSalt(this.aes.BlockSize / 8, password))) { using (var stream = new MemoryStream()) { this.aes.Key = pass.GetBytes(this.aes.KeySize / 8); this.aes.IV = pass.GetBytes(this.aes.BlockSize / 8); var proc = (process == AESProcess.Encryption) ? this.aes.CreateEncryptor() : this.aes.CreateDecryptor(); using (var crypto = new CryptoStream(stream, proc, CryptoStreamMode.Write)) { crypto.Write(plain, 0, plain.Length); crypto.Clear(); crypto.Close(); } stream.Close(); return(stream.ToArray()); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); return(null); } }
public EncryptionResult Encrypt(string keyId, byte[] dataToEncrypt) { var key = _keyManager.GenerateDataKey(keyId); var result = new EncryptionResult { EncryptedDataKey = key.CipherTextKey }; using (var symmetricKey = CreateSymmetricKeyAlgorithm()) { symmetricKey.GenerateIV(); result.InitialisationVector = symmetricKey.IV; using (var encryptor = symmetricKey.CreateEncryptor(key.PlainTextKey, result.InitialisationVector)) using (var output = new MemoryStream()) using (var cryptoOut = new CryptoStream(output, encryptor, CryptoStreamMode.Write)) { cryptoOut.Write(dataToEncrypt, 0, dataToEncrypt.Length); cryptoOut.FlushFinalBlock(); result.EncryptedData = output.ToArray(); cryptoOut.Clear(); } symmetricKey.Clear(); } return(result); }
public static string Decrypt <T>(string value, string password) where T : SymmetricAlgorithm, new() { SetPassword(password); byte[] valueBytes = Convert.FromBase64String(value); byte[] decrypted = null; int decryptedByteCount = 0; using (T alghoritm = new T() { Mode = CipherMode.CBC }) { try { using (ICryptoTransform decryptor = alghoritm.CreateDecryptor(keyBytes, vectorBytes)) { using (MemoryStream stream = new MemoryStream(valueBytes)) { using (CryptoStream reader = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) { decrypted = new byte[valueBytes.Length]; decryptedByteCount = reader.Read(decrypted, 0, decrypted.Length); reader.Clear(); } } } } catch (Exception) { return(string.Empty); } alghoritm.Clear(); } return(Encoding.UTF8.GetString(decrypted, 0, decryptedByteCount)); }
/// <summary> /// 解密 /// </summary> /// <param name="srcData">源数据</param> /// <param name="strKey">密钥</param> /// <returns>解密后的字节数组,若解密失败则返回null</returns> public byte[] Decrypt(byte[] srcData, string strKey) { if (null == srcData || srcData.Length < 1) { return(null); } //将密钥散列 byte[] srcKeyData = HashDigest.StringDigest(strKey, DigestType.MD5); SymmetricAlgorithm symAlg = SymmetricAlgorithm.Create("3DES"); symAlg.Key = srcKeyData; symAlg.IV = Keys; DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream( mStream, symAlg.CreateDecryptor(), CryptoStreamMode.Write); cStream.Write(srcData, 0, srcData.Length); cStream.FlushFinalBlock(); cStream.Clear(); return(mStream.ToArray()); }
byte[] Desencriptar(byte[] bytesAdesencriptar, byte[] clave) { byte[] bytesDesencriptados = null; byte[] salt = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; using (var ms = new MemoryStream()) { using (var aes = new RijndaelManaged()) { aes.KeySize = 256; aes.BlockSize = 128; var key = new Rfc2898DeriveBytes(clave, salt, 1000); aes.Key = key.GetBytes(aes.KeySize / 8); aes.IV = key.GetBytes(aes.BlockSize / 8); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.Zeros; using (var crp = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write)) { crp.Write(bytesAdesencriptar, 0, bytesAdesencriptar.Length); crp.Clear(); // Arroja error cuando un fichero encriptado requiere una contraseña y no se proporciona } bytesDesencriptados = ms.ToArray(); } } return(bytesDesencriptados); }
/// <summary> /// Decrypt a byte array with the specified provider. /// </summary> /// <param name="provider">Symmetric provider</param> /// <param name="buffer">Encrypted buffer</param> /// <returns>Unicode string</returns> internal static string DecryptTransform(SymmetricAlgorithm provider, byte[] buffer) { string decrypted = buffer.ToString(); using (MemoryStream ms = new MemoryStream()) { try { using (CryptoStream cs = new CryptoStream(ms, provider.CreateDecryptor(), CryptoStreamMode.Write)) { try { cs.Write(buffer, 0, buffer.Length); cs.FlushFinalBlock(); decrypted = Encoding.Unicode.GetString(ms.ToArray()); } finally { cs.Close(); cs.Clear(); } } } finally { ms.Close(); } } return(decrypted); }
/// <summary> /// Encrypt a string with the specified provider. /// The IV can be inserted at the beginning of the encrypted string. /// </summary> /// <param name="provider">Symmetric provider</param> /// <param name="unicodeValue">Unicode string</param> /// <param name="includeIV">True to include IV in encrypted string</param> /// <returns>Base64 encrypted string</returns> internal static string EncryptTransform(SymmetricAlgorithm provider, string unicodeValue, bool includeIV) { string encrypted; using (MemoryStream ms = new MemoryStream()) { try { if (includeIV) { ms.Write(provider.IV, 0, provider.IV.Length); } using (CryptoStream cs = new CryptoStream(ms, provider.CreateEncryptor(), CryptoStreamMode.Write)) { try { byte[] buffer = Encoding.Unicode.GetBytes(unicodeValue); cs.Write(buffer, 0, buffer.Length); cs.FlushFinalBlock(); encrypted = Convert.ToBase64String(ms.ToArray(), Base64FormattingOptions.None); } finally { cs.Close(); cs.Clear(); } } } finally { ms.Close(); } } return(encrypted); }
public static string Decrypt(string strCipherText) { TripleDESCryptoServiceProvider crp = new TripleDESCryptoServiceProvider(); UnicodeEncoding uEncode = new UnicodeEncoding(); ASCIIEncoding aEncode = new ASCIIEncoding(); byte[] bytCipherText = Convert.FromBase64String(strCipherText.Trim()); MemoryStream stmPlainText = new MemoryStream(); MemoryStream stmCipherText = new MemoryStream(bytCipherText); byte[] slt = new byte[0]; PasswordDeriveBytes pdb = new PasswordDeriveBytes("159874269852056921753491", slt); byte[] bytDerivedKey = pdb.GetBytes(24); crp.Key = bytDerivedKey; crp.IV = pdb.GetBytes(8); CryptoStream csDecrypted = new CryptoStream(stmCipherText, crp.CreateDecryptor(), CryptoStreamMode.Read); StreamWriter sw = new StreamWriter(stmPlainText); StreamReader sr = new StreamReader(csDecrypted); sw.Write(sr.ReadToEnd()); sw.Flush(); csDecrypted.Clear(); crp.Clear(); return(uEncode.GetString(stmPlainText.ToArray())); }
/// <summary> /// Decrypts the specified STR cipher text. /// </summary> /// <param name="strCipherText">The STR cipher text.</param> /// <returns></returns> public static string Decrypt(string strCipherText) { string strKey16 = ConfigurationManager.AppSettings["Mediachase-EncryptionPrivateKey"]; TripleDESCryptoServiceProvider crp = new TripleDESCryptoServiceProvider(); UnicodeEncoding uEncode = new UnicodeEncoding(); ASCIIEncoding aEncode = new ASCIIEncoding(); // Store cipher text as a byte array byte[] bytCipherText = Convert.FromBase64String(strCipherText); MemoryStream stmPlainText = new MemoryStream(); MemoryStream stmCipherText = new MemoryStream(bytCipherText); // Private key crp.Key = aEncode.GetBytes(strKey16.Substring(0, 16)); // Initialization vector crp.IV = aEncode.GetBytes(strKey16.Substring(8, 8)); // Create a crypto stream decoder to decode a cipher text stream into a plain text stream CryptoStream csDecrypted = new CryptoStream(stmCipherText, crp.CreateDecryptor(), CryptoStreamMode.Read); StreamWriter sw = new StreamWriter(stmPlainText); StreamReader sr = new StreamReader(csDecrypted); sw.Write(sr.ReadToEnd()); // Clean up afterwards sw.Flush(); csDecrypted.Clear(); crp.Clear(); return(uEncode.GetString(stmPlainText.ToArray())); }
public byte[] Decrypt(byte[] cipherData) { MemoryStream memoryStream = (MemoryStream)null; CryptoStream cryptoStream = (CryptoStream)null; try { memoryStream = new MemoryStream(cipherData); cryptoStream = new CryptoStream((Stream)memoryStream, this.sa.CreateDecryptor(), CryptoStreamMode.Read); byte[] array = new byte[memoryStream.Length]; int newSize = cryptoStream.Read(array, 0, array.Length); cryptoStream.Close(); Array.Resize <byte>(ref array, newSize); return(array); } catch (Exception ex) { throw new Exception("SymmetricsSI.Decrypt :: ", ex); } finally { cryptoStream?.Clear(); memoryStream?.Dispose(); } }
/// <summary> /// DES算法加密 /// </summary> /// <param name="pToEncrypt">明文</param> /// <param name="sKey">加密Key</param> /// <returns></returns> public static string DesEncrypt(string pToEncrypt, string sKey) { TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider(); byte[] bytes = Encoding.UTF8.GetBytes(pToEncrypt); provider.Key = new MD5CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(sKey)); provider.Mode = CipherMode.ECB; provider.Padding = PaddingMode.PKCS7; MemoryStream stream = new MemoryStream(); CryptoStream crypto = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write); crypto.Write(bytes, 0, bytes.Length); crypto.FlushFinalBlock(); StringBuilder builder = new StringBuilder(); foreach (byte num in stream.ToArray()) { builder.AppendFormat("{0:X2}", num); } builder.ToString(); stream.Close(); crypto.Clear(); crypto.Close(); provider.Clear(); return(builder.ToString()); }
public byte[] Decrypt2(byte[] cipherData) { MemoryStream memoryStream1 = (MemoryStream)null; MemoryStream memoryStream2 = (MemoryStream)null; CryptoStream cryptoStream = (CryptoStream)null; try { memoryStream1 = new MemoryStream(cipherData); memoryStream2 = new MemoryStream(); cryptoStream = new CryptoStream((Stream)memoryStream1, this.sa.CreateDecryptor(), CryptoStreamMode.Read); cryptoStream.CopyTo((Stream)memoryStream2); cryptoStream.Flush(); if (!cryptoStream.HasFlushedFinalBlock) { cryptoStream.FlushFinalBlock(); } return(memoryStream2.ToArray()); } catch (Exception ex) { throw new Exception("SymmetricsSI.Decrypt2 :: ", ex); } finally { cryptoStream?.Clear(); memoryStream1?.Dispose(); memoryStream2?.Dispose(); } }
/// <summary> /// Triple-DES decrypts the cipher text using the provided key. /// </summary> /// <param name="cipherText">The cipher text to be decrypted.</param> /// <param name="key">The key to use in decrypting the text.</param> /// <returns>The plain text resultant from the decryption.</returns> public static string DecryptString(string cipherText, string key) { TripleDESCryptoServiceProvider tripProvider = new TripleDESCryptoServiceProvider(); UnicodeEncoding uEncode = new UnicodeEncoding(); // stores ciphertext as a byte array byte[] byteCipherText = Convert.FromBase64String(cipherText); // create a memory stream to hold encrypted text MemoryStream plainText = new MemoryStream(); MemoryStream cipherTextStream = new MemoryStream(byteCipherText); // private key byte[] slt = new byte[0]; Rfc2898DeriveBytes passwordderiveBytes = new Rfc2898DeriveBytes(key, slt); byte[] byteDeriveKey = passwordderiveBytes.GetBytes(24); tripProvider.Key = byteDeriveKey; // initialization vector is the encryption seed tripProvider.IV = passwordderiveBytes.GetBytes(8); // create a cryto-stream decoder to decode // a cipher text stream into a plain text stream CryptoStream decrypted = new CryptoStream(cipherTextStream, tripProvider.CreateDecryptor(), CryptoStreamMode.Read); StreamWriter writer = new StreamWriter(plainText); StreamReader reader = new StreamReader(decrypted); writer.Write(reader.ReadToEnd()); // clean up afterwards writer.Flush(); decrypted.Clear(); tripProvider.Clear(); // return result as a Base64 encoded string return(uEncode.GetString(plainText.ToArray())); }
public T Decrypt <T>(T obj) { manager.Key = ToByte(context.Session.GetString("StorageKey")); manager.IV = ToByte(context.Session.GetString("StorageIV")); Type type = obj.GetType(); MemoryStream memoryStream; CryptoStream cryptoStream; StreamReader streamReader; foreach (PropertyInfo p in type.GetProperties()) { if (p.PropertyType != typeof(string)) { continue; } byte[] property = ToByte(p.GetValue(obj).ToString()); memoryStream = new MemoryStream(property); cryptoStream = new CryptoStream(memoryStream, manager.CreateDecryptor(manager.Key, manager.IV), CryptoStreamMode.Read); streamReader = new StreamReader(cryptoStream); p.SetValue(obj, streamReader.ReadToEnd()); streamReader.Close(); cryptoStream.Clear(); memoryStream.Close(); } return(obj); }
/// <summary> /// 解密为字符串 /// </summary> /// <param name="s"></param> /// <returns></returns> public string DecryptString(string s) { CheckUtil.ArgumentNotNullOrEmpty(s, "s"); byte[] inputData = Convert.FromBase64String(s); string result = string.Empty; using (MemoryStream ms = new System.IO.MemoryStream(inputData)) { symmetricAlgorithmProvider.Key = GetLegalKey(); symmetricAlgorithmProvider.IV = GetLegalIV(); ICryptoTransform encrypto = symmetricAlgorithmProvider.CreateDecryptor(); CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read); StreamReader sr = new StreamReader(cs); result = sr.ReadLine(); //CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read); //byte[] outputData = new byte[inputData.Length]; //cs.Read(outputData, 0, outputData.Length); //result = Encoding.UTF8.GetString(outputData).TrimEnd(new char[] { '\0' }); cs.Clear(); cs.Close(); } return result; }
/// <summary> /// Decrypto string /// </summary> /// <param name="Source">The srouce need to decrypto</param> /// <returns>The result string after decrypto</returns> public string Decrypto(string Source) { if (string.IsNullOrWhiteSpace(Source)) { return(null); } byte[] bytIn = System.Convert.FromBase64String(Source); try { string strRet = null; using (MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length)) { _objCryptoService.Key = GetLegalKey(); _objCryptoService.IV = GetLegalIV(); ICryptoTransform encrypto = _objCryptoService.CreateDecryptor(); using (CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read)) { using (StreamReader sr = new StreamReader(cs)) { strRet = sr.ReadToEnd(); cs.Clear(); sr.Close(); } cs.Close(); } ms.Close(); } return(strRet); } catch (Exception) { return(null); } }
public byte[] Encrypt(byte[] input, bool preserveLength = true) { if (!CanEncrypt) { throw new CryptographicException(Resources.RSACryptographyProvider_Encryption_Not_Supported); } if (input == null) { return(null); } using (MemoryStream stream = new MemoryStream()) { using (CryptoStream cryptoStream = GetEncryptionStream(stream)) { cryptoStream.Write(input, 0, input.Length); // Add termination byte if the provider does not respect the length. if (preserveLength && !PreservesLength && CanDecrypt) { cryptoStream.WriteByte(0xFF); } cryptoStream.Clear(); } return(stream.ToArray()); } }
/// <summary> /// Encrypts the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="IV">The iv.</param> /// <param name="data">The data.</param> /// <param name="cm">The cm.</param> /// <param name="sa">The sa.</param> /// <returns></returns> public static byte[] Encrypt(byte[] key, byte[] IV, byte[] data, CipherMode cm, SymmetricAlgorithm sa) { ValidateKeyIV(key, IV, sa); sa.Mode = cm; sa.Key = key; sa.IV = IV; using (var ms = new MemoryStream()) { using (var ec = sa.CreateEncryptor()) { using (var cs = new CryptoStream(ms, ec, CryptoStreamMode.Write)) { try { cs.Write(data, 0, data.Length); cs.FlushFinalBlock(); return(ms.ToArray()); } finally { cs.Clear(); cs.Close(); } } } } }
/// <summary> /// Decrypts the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="IV">The iv.</param> /// <param name="data">The data.</param> /// <param name="cm">The cm.</param> /// <param name="sa">The sa.</param> /// <returns></returns> public static byte[] Decrypt(byte[] key, byte[] IV, byte[] data, CipherMode cm, SymmetricAlgorithm sa) { ValidateKeyIV(key, IV, sa); sa.Mode = cm; sa.Key = key; sa.IV = IV; using (var ms = new MemoryStream(data)) { using (var dc = sa.CreateDecryptor()) { using (var cs = new CryptoStream(ms, dc, CryptoStreamMode.Read)) { try { var rValue = new byte[data.Length]; cs.Read(rValue, 0, rValue.Length); return(rValue); } finally { cs.Clear(); cs.Close(); } } } } }
public static string Decrypt(string cipherText) { var initVectorBytes = Encoding.ASCII.GetBytes(INIT_VECTOR); var saltValueBytes = Encoding.ASCII.GetBytes(SALT_VALUE); var cipherTextBytes = Convert.FromBase64String(cipherText); var password = new PasswordDeriveBytes(PASSPHRASE, saltValueBytes, HASH_ALGORITM, PASSWORD_ITERATION); var keyBytes = password.GetBytes(KEY_SIZE / 8); var symmetricKey = new RijndaelManaged(); symmetricKey.Mode = CipherMode.CBC; symmetricKey.Padding = PaddingMode.None; var decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes); var memoryStream = new MemoryStream(cipherTextBytes); var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read); var plainTextBytes = new byte[cipherTextBytes.Length]; int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.Clear(); memoryStream.Close(); cryptoStream.Close(); var plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount); return(plainText); }
private const int KEY_SIZE = 256; // it can be 128 , 192 and 256 , longer keys are more secure than shorter keys /// <summary> /// to encrypt text /// </summary> /// <param name="plainText">text that should be encrypt</param> /// <param name="passPhrase">any character</param> /// <param name="saltValue">any character</param> /// <param name="hashAlgorithm">SHA1, MD5</param> /// <param name="passwordIterations">one or two</param> /// <param name="initVector">must be exactly 16 ascii character</param> /// <param name="keySize">128,192 and 256 , longer is better</param> /// <returns></returns> public static string Encrypt(string plainText) { var initVectorBytes = Encoding.ASCII.GetBytes(INIT_VECTOR); var saltValueBytes = Encoding.ASCII.GetBytes(SALT_VALUE); var plainTextBytes = Encoding.UTF8.GetBytes(plainText); var password = new PasswordDeriveBytes(PASSPHRASE, saltValueBytes, HASH_ALGORITM, PASSWORD_ITERATION); var keyBytes = password.GetBytes(KEY_SIZE / 8); var symmetricKey = new RijndaelManaged(); symmetricKey.Mode = CipherMode.CBC; var encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes); var memoryStream = new MemoryStream(); var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write); cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); cryptoStream.Clear(); var cipherTextBytes = memoryStream.ToArray(); memoryStream.Close(); cryptoStream.Close(); var cipherText = Convert.ToBase64String(cipherTextBytes); return(cipherText); }
public static byte[] EncryptStringToBytes(string s, byte[] key, byte[] iv) { byte[] encrypted; using var aes = Aes.Create(); aes.Key = key; aes.IV = iv; var encryptor = aes.CreateEncryptor(key, iv); using var ms = new MemoryStream(); using var encrypt = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); using var sw = new StreamWriter(encrypt); try { sw.Write(s); sw.Close(); ms.Close(); } catch (Exception e) { Console.WriteLine(e); throw; } finally { encrypt.Clear(); } encrypted = ms.ToArray(); return(encrypted); }
public static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] iv) { string result; using var aes = Aes.Create(); aes.Key = key; aes.IV = iv; var decryptor = aes.CreateDecryptor(key, iv); using var ms = new MemoryStream(cipherText); using var decrypt = new CryptoStream(ms, decryptor, CryptoStreamMode.Read); using var sr = new StreamReader(decrypt); try { result = sr.ReadToEnd(); sr.Close(); ms.Close(); } catch (Exception e) { Console.WriteLine(e); throw; } finally { decrypt.Clear(); } return(result); }
internal static string EncryptString(string InputText, string Password) { /*source: http://dotnet.org.za/deon/pages/2998.aspx * see also: http://www.codeproject.com/KB/cs/Data_Encryption.aspx, * http://stackoverflow.com/questions/1629828/how-to-encrypt-a-string-in-net/1629927, * http://www.obviex.com/samples/Encryption.aspx * http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx*/ RijndaelManaged rijndaelCipher = new RijndaelManaged(); //To byte array byte[] plainText = System.Text.Encoding.Unicode.GetBytes(InputText); // While the salt should be a cryptographically random number, we have no place to store that information // so are using password length to offer slightly greater security against a dictionary attack byte[] salt = Encoding.ASCII.GetBytes(Password.Length.ToString()); // The key will be generated from the specified // password and salt. PasswordDeriveBytes key = new PasswordDeriveBytes(Password, salt); // Create a encryptor from the existing key bytes. // 32 bytes for the key // (the default Rijndael key length is 256 bit = 32 bytes) and // then 16 bytes for the IV (initialization vector), // (the default Rijndael IV length is 128 bit = 16 bytes) ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(key.GetBytes(32), key.GetBytes(16)); // Create a MemoryStream for the encrypted bytes MemoryStream memoryStream = new MemoryStream(); // Create a CryptoStream through which we are going to be processing our data. // CryptoStreamMode.Write means that we are going to be writing data // to the stream and the output will be written in the MemoryStream // we have provided. (always use write mode for encryption) CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write); // Start the encryption process. cryptoStream.Write(plainText, 0, plainText.Length); // Finish encrypting. cryptoStream.FlushFinalBlock(); // Convert our encrypted data from a memoryStream into a byte array. byte[] CipherBytes = memoryStream.ToArray(); // Close both streams. memoryStream.Close(); cryptoStream.Close(); // Convert encrypted data into a base64-encoded string. string encryptedData = Convert.ToBase64String(CipherBytes); //Clear the CryptoStream cryptoStream.Clear(); // Return encrypted string. return(encryptedData); }
public static void Clear() { ICryptoTransform encryptor = new IdentityTransform(1, 1, true); using (MemoryStream output = new MemoryStream()) using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write)) { encryptStream.Clear(); Assert.Throws<NotSupportedException>(() => encryptStream.Write(new byte[] { 1, 2, 3, 4, 5 }, 0, 5)); } }