public string Decrypt(string strEncryptedText) { if (strEncryptedText == null || strEncryptedText.Equals("")) return strEncryptedText; string strDecryptedText = null; RijndaelManaged rijndael = new RijndaelManaged(); ICryptoTransform decryptor = rijndael.CreateDecryptor(Key, IV); byte[] byteEncryptedText = Convert.FromBase64String(strEncryptedText); MemoryStream memStream = new MemoryStream(byteEncryptedText); CryptoStream decryptStream = null; try { decryptStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read); byte[] byteDecryptedText = new byte[byteEncryptedText.Length]; int decryptedByteCount = decryptStream.Read(byteDecryptedText, 0, byteDecryptedText.Length); strDecryptedText = Encoding.UTF8.GetString(byteDecryptedText, 0, decryptedByteCount); } finally { if (rijndael != null) rijndael.Clear(); if (decryptor != null) decryptor.Dispose(); if (memStream != null) memStream.Close(); if (decryptStream != null) decryptStream.Close(); } if (UseSalt) strDecryptedText = strDecryptedText.Substring(8); return strDecryptedText; }
public static string DecryptString(String cipherText, string Key) { byte[] tmpCipherText = Convert.FromBase64String(cipherText); byte[] tmpKey = GenerateAlgotihmInputs(Key); using (RijndaelManaged alg = new RijndaelManaged()) { alg.Key = tmpKey; alg.IV = tmpKey; // Create a decrytor to perform the stream transform. ICryptoTransform decryptor = alg.CreateDecryptor(alg.Key, alg.IV); // Create the streams used for decryption. using (MemoryStream msDecrypt = new MemoryStream(tmpCipherText)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { // Place les données déchiffrées dans un tableau d'octet byte[] plainTextData = new byte[tmpCipherText.Length]; int decryptedByteCount = csDecrypt.Read(plainTextData, 0, plainTextData.Length); return Encoding.UTF8.GetString(plainTextData, 0, decryptedByteCount); } } } }
public static string Decrypt(string cipherText, string passPhrase) { // Get the complete stream of bytes that represent: // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText] var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText); // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes. var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray(); // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes. var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray(); // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string. var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray(); var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations); var keyBytes = password.GetBytes(Keysize / 8); using (var symmetricKey = new RijndaelManaged()) { symmetricKey.BlockSize = 256; symmetricKey.Mode = CipherMode.CBC; symmetricKey.Padding = PaddingMode.PKCS7; using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes)) { using (var memoryStream = new MemoryStream(cipherTextBytes)) { using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) { var plainTextBytes = new byte[cipherTextBytes.Length]; var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); memoryStream.Close(); cryptoStream.Close(); return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount); } } } } }
/// <summary> /// AES解密(无向量) /// </summary> /// <param name="encryptedBytes">被加密的明文</param> /// <param name="key">密钥</param> /// <returns>明文</returns> public static string AESDecryptWithoutVector(String Data, String Key) { Byte[] encryptedBytes = Convert.FromBase64String(Data); Byte[] bKey = new Byte[32]; Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length); MemoryStream mStream = new MemoryStream(encryptedBytes); //mStream.Write( encryptedBytes, 0, encryptedBytes.Length ); //mStream.Seek( 0, SeekOrigin.Begin ); RijndaelManaged aes = new RijndaelManaged(); aes.Mode = CipherMode.ECB; aes.Padding = PaddingMode.PKCS7; aes.KeySize = 128; aes.Key = bKey; //aes.IV = _iV; CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read); try { byte[] tmp = new byte[encryptedBytes.Length + 32]; int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32); byte[] ret = new byte[len]; Array.Copy(tmp, 0, ret, 0, len); return Encoding.UTF8.GetString(ret); } finally { cryptoStream.Close(); mStream.Close(); aes.Clear(); } }
/// <summary> /// Decrypts the specified data using a 128-bit cipher. The key can be any length. /// </summary> /// <param name="Data">The data to be decrypted.</param> /// <param name="Key">The key used to decrypt the data.</param> /// <returns>A string containing the decoded data.</returns> public static byte[] Decrypt128Byte(byte[] Data, byte[] Key) { RijndaelManaged AES = null; var MS = new MemoryStream(Data); CryptoStream CS = null; StreamReader DS = null; try { //Get the IV and length corrected Key. KeyData KeyData = GenerateKeyIV128(Key); //Create the AES crytpograhy object. AES = new RijndaelManaged { BlockSize = 128, KeySize = 128, Key = KeyData.Key, IV = KeyData.IV, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }; CS = new CryptoStream(MS, AES.CreateDecryptor(), CryptoStreamMode.Read); DS = new StreamReader(CS); var D = new byte[CS.Length]; CS.Read(D, 0, (int)CS.Length - 1); return D; } finally { if (AES != null) AES.Clear(); MS.Dispose(); if (CS != null) CS.Dispose(); if (DS != null) DS.Dispose(); } }
protected static string DecryptString(string InputText, string Password) { try { RijndaelManaged RijndaelCipher = new RijndaelManaged(); byte[] EncryptedData = Convert.FromBase64String(InputText); byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString()); PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt); // Create a decryptor from the existing SecretKey bytes. ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(16), SecretKey.GetBytes(16)); MemoryStream memoryStream = new MemoryStream(EncryptedData); // Create a CryptoStream. (always use Read mode for decryption). CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read); // Since at this point we don't know what the size of decrypted data // will be, allocate the buffer long enough to hold EncryptedData; // DecryptedData is never longer than EncryptedData. byte[] PlainText = new byte[EncryptedData.Length]; // Start decrypting. int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length); memoryStream.Close(); cryptoStream.Close(); // Convert decrypted data into a string. string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount); // Return decrypted string. return DecryptedData; } catch (Exception exception) { return (exception.Message); } }
private byte[] DecryptManaged(byte[] Key, byte[] Vector, byte[] Data, PaddingMode Padding = PaddingMode.Zeros) { byte[] decryptedBytes; int count = 0; using (MemoryStream stream = new MemoryStream(Data)) { using (RijndaelManaged cipher = new RijndaelManaged()) { cipher.Mode = CipherMode.CBC; cipher.Padding = Padding; cipher.KeySize = Key.Length * 8; cipher.BlockSize = Vector.Length * 8; using (ICryptoTransform decryptor = cipher.CreateDecryptor(Key, Vector)) { using (CryptoStream reader = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) { decryptedBytes = new byte[stream.Length]; count = reader.Read(decryptedBytes, 0, decryptedBytes.Length); } } cipher.Clear(); } } return decryptedBytes; }
public static string DecryptFromByteArray(byte[] data) { System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(data); string @string; try { System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, new System.Security.Cryptography.TripleDESCryptoServiceProvider().CreateDecryptor(StringUtils.Key(), StringUtils.Iv()), System.Security.Cryptography.CryptoStreamMode.Read); try { byte[] array = new byte[data.Length]; int count = cryptoStream.Read(array, 0, array.Length); @string = new System.Text.UTF8Encoding().GetString(array, 0, count); } finally { cryptoStream.Dispose(); } } finally { memoryStream.Dispose(); } return(@string); }
/// <summary> /// Decrypts a string /// </summary> /// <param name="CipherText">Text to be decrypted</param> /// <param name="Password">Password to decrypt with</param> /// <param name="Salt">Salt to decrypt with</param> /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param> /// <param name="PasswordIterations">Number of iterations to do</param> /// <param name="InitialVector">Needs to be 16 ASCII characters long</param> /// <param name="KeySize">Can be 128, 192, or 256</param> /// <returns>A decrypted byte array in UTF-8 format</returns> public static byte[] Decrypt(byte[] CipherText, byte[] Password, byte[] InitialVector, byte[] Salt) { PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, Salt, HASH_ALGORITHM, PASSWORDITERATIONS); byte[] KeyBytes = DerivedPassword.GetBytes(KEY_SIZE / 8); RijndaelManaged SymmetricKey = new RijndaelManaged(); SymmetricKey.Mode = CipherMode.CBC; byte[] PlainTextBytes = new byte[CipherText.Length]; int ByteCount = 0; using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVector)) { using (MemoryStream MemStream = new MemoryStream(CipherText)) { using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read)) { ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length); MemStream.Close(); CryptoStream.Close(); } } } SymmetricKey.Clear(); byte[] decrypted = new byte[ByteCount]; Array.Copy(PlainTextBytes, decrypted, ByteCount); return decrypted; }
public static string Decrypt(byte[] cipherTextBytes, string password, string salt = null, string initialVector = null) { const int keySize = 256; byte[] initialVectorBytes = string.IsNullOrEmpty(initialVector) ? InitVectorBytes : Encoding.UTF8.GetBytes(initialVector); byte[] saltValueBytes = string.IsNullOrEmpty(salt) ? SaltBytes : Encoding.UTF8.GetBytes(salt); byte[] keyBytes = new Rfc2898DeriveBytes(password, saltValueBytes).GetBytes(keySize/8); byte[] plainTextBytes = new byte[cipherTextBytes.Length]; using (RijndaelManaged symmetricKey = new RijndaelManaged()) { symmetricKey.Mode = CipherMode.CBC; using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initialVectorBytes)) { using (MemoryStream memStream = new MemoryStream(cipherTextBytes)) { using (CryptoStream cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read) ) { int byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); return Encoding.UTF8.GetString(plainTextBytes, 0, byteCount); } } } } }
public static byte[] Desencriptar(byte[] mensajeEncriptado, SymmetricAlgorithm algoritmo) { int numeroBytesDesencriptados = 0; // La clase SymmetricAlgorithm delega el proceso de desencriptación de datos // Una instancia de ICryptoTransform transforma texto plano en texto cifrado o vice versa. // Las siguiente sentencia demuestra como crear transformaciones usando CreateDecryptor. byte[] mensajeDesencriptado = new byte[mensajeEncriptado.Length]; // Crear una ICryptoTransform que puede ser usada para desencriptar datos ICryptoTransform desencriptador = algoritmo.CreateDecryptor(); // Procedemos a descifrar el mensaje MemoryStream memoryStream = new MemoryStream(mensajeEncriptado); // Creamos el CryptoStream CryptoStream cryptoStream = new CryptoStream(memoryStream, desencriptador, CryptoStreamMode.Read); // Decrypting data and get the count of plain text bytes. numeroBytesDesencriptados = cryptoStream.Read(mensajeDesencriptado, 0, mensajeDesencriptado.Length); // Liberamos recursos. memoryStream.Close(); cryptoStream.Close(); return mensajeDesencriptado; }
public string mDecryptURLEncode(string EncryptedText) { string DecryptedText = ""; System.Security.Cryptography.ICryptoTransform ssd = rc2.CreateDecryptor(); string sEncrypt = HttpUtility.UrlDecode(EncryptedText); byte[] cipherBytes = Convert.FromBase64String(sEncrypt); byte[] initialText = null; using (System.IO.MemoryStream ms = new System.IO.MemoryStream(cipherBytes)) { using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, ssd, System.Security.Cryptography.CryptoStreamMode.Read)) { int iCount = opGetArrLength(cipherBytes); initialText = new Byte[cipherBytes.Length]; cs.Read(initialText, 0, initialText.Length); cs.Close(); cs.Dispose(); } ms.Close(); ms.Dispose(); } DecryptedText = System.Text.UTF8Encoding.UTF8.GetString(initialText); return(DecryptedText = DecryptedText.Replace("\0", "")); }
public string Decrypt(string encryptedValue) { if (String.IsNullOrEmpty(encryptedValue)) { throw new ArgumentNullException("encryptedValue"); } if (m_key == null) { throw new InvalidOperationException(Resources.Global.InvalidHashKey); } byte[] cipher = Convert.FromBase64String(encryptedValue); using (var crypto = new RijndaelManaged()) using (ICryptoTransform encryptor = crypto.CreateDecryptor(m_key, m_vector)) using (var memoryStream = new MemoryStream(cipher)) { var crptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Read); var data = new byte[cipher.Length]; int dataLength = crptoStream.Read(data, 0, data.Length); return Encoding.UTF8.GetString(data, 0, dataLength); } }
public IAsyncResult BeginPersist(CacheRequest request, CacheResponse response, AsyncCallback callback, object state) { if (!request.CanonicalUri.ToString().Contains("FragmentInfo") && !request.CanonicalUri.ToString().Contains("Manifest")) { try { using (CryptoStream stream = new CryptoStream(response.Response, this._decryptionInfo.Decryptor, CryptoStreamMode.Read)) { MemoryStream stream2 = new MemoryStream(); int count = 0x1000; byte[] buffer = new byte[count]; while (stream.CanRead) { int num = stream.Read(buffer, 0, count); if (num == 0) { break; } stream2.Write(buffer, 0, num); } stream2.Position = 0L; response.Response = stream2; } } catch { response.Response = null; } } return null; }
/// <summary> /// Decrypts specified ciphertext using Rijndael symmetric key algorithm. /// </summary> /// <param name="cipherText"> /// Base64-formatted ciphertext value. /// </param> /// <param name="passPhrase"> /// Passphrase from which a pseudo-random password will be derived. The /// derived password will be used to generate the encryption key. /// Passphrase can be any string. In this example we assume that this /// passphrase is an ASCII string. /// </param> /// <param name="saltValue"> /// Salt value used along with passphrase to generate password. Salt can /// be any string. In this example we assume that salt is an ASCII string. /// </param> /// <param name="passwordIterations"> /// Number of iterations used to generate password. One or two iterations /// should be enough. /// </param> /// <param name="initVector"> /// Initialization vector (or IV). This value is required to encrypt the /// first block of plaintext data. For RijndaelManaged class IV must be /// exactly 16 ASCII characters long. /// </param> /// <param name="keySize"> /// Size of encryption key in bits. Allowed values are: 128, 192, and 256. /// Longer keys are more secure than shorter keys. /// </param> /// <returns> /// Decrypted string value. /// </returns> /// <remarks> /// Most of the logic in this function is similar to the Encrypt /// logic. In order for decryption to work, all parameters of this function /// - except cipherText value - must match the corresponding parameters of /// the Encrypt function which was called to generate the /// ciphertext. /// </remarks> public static string Decrypt( string cipherText, string passPhrase, string saltValue, int passwordIterations, string initVector, int keySize) { byte[] initVectorBytes = System.Text.Encoding.ASCII.GetBytes(initVector); byte[] saltValueBytes = System.Text.Encoding.ASCII.GetBytes(saltValue); byte[] cipherTextBytes = Convert.FromBase64String(cipherText); var password = new Rfc2898DeriveBytes(passPhrase, saltValueBytes, passwordIterations); byte[] keyBytes = password.GetBytes(keySize / 8); var symmetricKey = new RijndaelManaged(); symmetricKey.Mode = CipherMode.CBC; ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes); using (var memoryStream = new MemoryStream(cipherTextBytes)) using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) { byte[] plainTextBytes = new byte[cipherTextBytes.Length]; int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); return System.Text.Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount); } }
public static byte[] decrypt(byte[] encrypted, byte[] Key, byte[] IV) { try { byte[] plain; int count; using (MemoryStream mStream = new MemoryStream(encrypted)) { using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider()) { aesProvider.Mode = CipherMode.CBC; using (CryptoStream cryptoStream = new CryptoStream(mStream, aesProvider.CreateDecryptor(Key, IV), CryptoStreamMode.Read)) { plain = new byte[encrypted.Length]; count = cryptoStream.Read(plain, 0, plain.Length); } } } byte[] returnValue = new byte[count]; Array.Copy(plain, returnValue, count); return returnValue; } catch (Exception e) { Logger.log(e.StackTrace); throw e; } }
/// <summary> /// 複合化スクリプト /// </summary> /// <returns>byte[] 複合化したbyte列</returns> public byte[] Decrypt(byte[] binData) { RijndaelManaged myRijndael = new RijndaelManaged(); myRijndael.Padding = PaddingMode.Zeros; myRijndael.Mode = CipherMode.CBC; myRijndael.KeySize = KeySize; myRijndael.BlockSize = BlockSize; byte[] key = new byte[0]; byte[] InitVector = new byte[0]; key = System.Text.Encoding.UTF8.GetBytes(AesKey); InitVector = System.Text.Encoding.UTF8.GetBytes(AesInitVector); ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, InitVector); byte[] src = binData; byte[] dest = new byte[src.Length]; MemoryStream msDecrypt = new MemoryStream(src); CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); // 複号化する try { csDecrypt.Read(dest, 0, dest.Length); } catch { return null; } return dest; }
/// <summary> /// Desencripta dado el Cifrado Rijndael /// </summary> /// <param name="data">Información a Desencriptar</param> /// <param name="cypher">Clave a Utilizar para descifrar</param> /// <returns>Información Desencriptada</returns> public static string Decrypt(string data, string cypher, Boolean webSafe) { if (webSafe) { data = Gale.Serialization.FromBase64(data); } string ciphertext = data; try { RijndaelManaged rijndaelCipher = new RijndaelManaged(); byte[] ciphertextByte = Convert.FromBase64String(ciphertext); byte[] saltByte = Encoding.ASCII.GetBytes(cypher.Length.ToString()); PasswordDeriveBytes secretKey = new PasswordDeriveBytes(cypher, saltByte); ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)); System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(ciphertextByte); CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read); byte[] plainText = new byte[ciphertextByte.Length + 1]; int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length); memoryStream.Close(); cryptoStream.Close(); return Encoding.UTF8.GetString(plainText, 0, decryptedCount); } catch (System.Exception ex) { throw ex; } }
private bool AESDecrypt(byte[] IV, byte[] encrypted, out byte[] resBytes) { byte[] decryptedTempMessageBytes = new byte[encrypted.Length]; using (Aes aesAlg = Aes.Create()) { aesAlg.Key = key; aesAlg.IV = IV; ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msDecrypt = new MemoryStream(encrypted)) { try { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { csDecrypt.Read(decryptedTempMessageBytes, 0, decryptedTempMessageBytes.Length); } } catch (CryptographicException ex) { resBytes = null; return false; } } } resBytes = decryptedTempMessageBytes; return true; }
/// <summary> /// Decrypts a string /// </summary> /// <param name="cipherText">Text to be decrypted</param> /// <param name="password">Password to decrypt with</param> /// <param name="salt">Salt to decrypt with</param> /// <param name="hashAlgorithm">Can be either SHA1 or MD5</param> /// <param name="passwordIterations">Number of iterations to do. The number of times the algorithm is run on the text. </param> /// <param name="initialVector">Needs to be 16 ASCII characters long</param> /// <param name="keySize">Can be 128, 192, or 256</param> /// <returns>A decrypted string</returns> public static string Decrypt(string cipherText, string password, string salt = "69ad1bfbd6605f3f6a3011460cdfb9db7757e0f9", string hashAlgorithm = "SHA1", int passwordIterations = 2, string initialVector = "OFRna73m*aze01xY", int keySize = 256) { if (string.IsNullOrEmpty(cipherText)) return ""; byte[] initialVectorBytes = Encoding.ASCII.GetBytes(initialVector); byte[] saltValueBytes = Encoding.ASCII.GetBytes(salt); byte[] cipherTextBytes = Convert.FromBase64String(cipherText); var derivedPassword = new PasswordDeriveBytes(password, saltValueBytes, hashAlgorithm, passwordIterations); byte[] keyBytes = derivedPassword.GetBytes(keySize / 8); var symmetricKey = new RijndaelManaged {Mode = CipherMode.CBC}; byte[] plainTextBytes = new byte[cipherTextBytes.Length]; int byteCount; using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initialVectorBytes)) { using (MemoryStream memStream = new MemoryStream(cipherTextBytes)) { using (CryptoStream cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read)) { byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); memStream.Close(); cryptoStream.Close(); } } } symmetricKey.Clear(); return Encoding.UTF8.GetString(plainTextBytes, 0, byteCount); }
public static byte[] Decrypt(byte[] input) { if (_key == null || _key.Length == 0) throw new Exception("Key can not be empty."); if (input == null || input.Length == 0) throw new ArgumentException("Input can not be empty."); byte[] data = new byte[0]; try { using (var ms = new MemoryStream(input)) { using (var rd = new RijndaelManaged { Key = _key }) { byte[] iv = new byte[IVLENGTH]; ms.Read(iv, 0, IVLENGTH); // read first 16 bytes for IV, followed by encrypted message rd.IV = iv; using (var cs = new CryptoStream(ms, rd.CreateDecryptor(), CryptoStreamMode.Read)) { byte[] temp = new byte[ms.Length - IVLENGTH + 1]; data = new byte[cs.Read(temp, 0, temp.Length)]; Buffer.BlockCopy(temp, 0, data, 0, data.Length); } } } } catch { } return data; }
public static void DecryptFile(string inputFile, string outputFile, string keyIV) { byte[] array = new byte[0x20]; byte[] buffer2 = new byte[0x10]; HexStringToByteArray(keyIV, array, 0); HexStringToByteArray(keyIV, buffer2, 0x40); FileStream stream = File.Open(inputFile, System.IO.FileMode.Open); FileStream stream2 = File.Open(outputFile, System.IO.FileMode.CreateNew); AesManaged managed = new AesManaged { Key = array, IV = buffer2 }; CryptoStream stream3 = new CryptoStream(stream, managed.CreateDecryptor(managed.Key, managed.IV), CryptoStreamMode.Read); try { int num; byte[] buffer = new byte[0xa000]; while ((num = stream3.Read(buffer, 0, buffer.Length)) > 0) { stream2.Write(buffer, 0, num); } } finally { stream3.Close(); stream.Close(); stream2.Close(); } }
/// <summary> /// Decrypts a byte array with a password /// </summary> /// <param name="data">Data to decrypt</param> /// <param name="password">Password to use</param> /// <param name="paddingMode">Padding mode to use</param> /// <returns>Decrypted byte array</returns> /// <exception cref="System.ArgumentNullException"> /// data /// or /// password /// </exception> /// <exception cref="ArgumentNullException"></exception> public static byte[] DecryptData(byte[] data, string password, PaddingMode paddingMode) { if (data == null || data.Length == 0) throw new ArgumentNullException("data"); if (password == null) throw new ArgumentNullException("password"); var pdb = new PasswordDeriveBytes(password, Encoding.UTF8.GetBytes("Salt")); var rm = new RijndaelManaged { Padding = paddingMode }; ICryptoTransform decryptor = rm.CreateDecryptor(pdb.GetBytes(16), pdb.GetBytes(16)); pdb.Dispose(); using (var msDecrypt = new MemoryStream(data)) using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { // Decrypted bytes will always be less then encrypted bytes, so length of encrypted data will be big enough for buffer. byte[] fromEncrypt = new byte[data.Length]; // Read as many bytes as possible. int read = csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length); if (read < fromEncrypt.Length) { // Return a byte array of proper size. byte[] clearBytes = new byte[read]; Buffer.BlockCopy(fromEncrypt, 0, clearBytes, 0, read); return clearBytes; } return fromEncrypt; } }
public byte[] Unprotect(byte[] protectedData) { byte[] output = null; using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = _key; aesAlg.IV = _IV; ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msDecrypt = new MemoryStream(protectedData)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { byte[] buffer = new byte[8]; using (MemoryStream msOutput = new MemoryStream()) { int read; while ((read = csDecrypt.Read(buffer, 0, buffer.Length)) > 0) { msOutput.Write(buffer, 0, read); } output = msOutput.ToArray(); } } } } return output; }
/// <summary> /// Encrypt/Decrypt with Read method. Recommended for decrypting only. /// </summary> /// <param name="cryptor"></param> /// <param name="input"></param> /// <returns></returns> private byte[] CipherStreamRead(System.Security.Cryptography.ICryptoTransform cryptor, byte[] input) { WriteLog("--- Cipher Stream:"); WriteLog("InputBlockSize: " + cryptor.InputBlockSize.ToString()); WriteLog("OutputBlockSize: " + cryptor.OutputBlockSize.ToString()); byte[] inputBuffer = new byte[input.Length]; byte[] outputBuffer = new byte[input.Length]; // Copy data bytes to input buffer. System.Buffer.BlockCopy(input, 0, inputBuffer, 0, inputBuffer.Length); // Create a MemoryStream to hold the input bytes. var stream = new System.IO.MemoryStream(inputBuffer); // Create a CryptoStream through which we are going to be processing our data. var cryptoStream = new System.Security.Cryptography.CryptoStream(stream, cryptor, System.Security.Cryptography.CryptoStreamMode.Read); // Start the crypting process. int length = cryptoStream.Read(outputBuffer, 0, outputBuffer.Length); // Finish crypting. cryptoStream.FlushFinalBlock(); // Convert data from a memoryStream into a byte array. System.Array.Resize(ref outputBuffer, length); // Close both streams. stream.Close(); // cryptoStream.Close(); WriteEnc(inputBuffer, outputBuffer); return(outputBuffer); }
/// <summary> /// 对流进行加密或解密 /// </summary> /// <param name="inS">输入流</param> /// <param name="outS">输出流</param> /// <param name="desKey">密钥</param> /// <param name="desIV">向量</param> /// <param name="isEncrypt">是否加密</param> /// <returns>成功返回true,失败返回false</returns> private static bool cryptIt(Stream inS, Stream outS, byte[] desKey, byte[] desIV, bool isEncrypt) { try { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); ICryptoTransform mode = null; if (isEncrypt) mode = des.CreateEncryptor(desKey, desIV); else mode = des.CreateDecryptor(desKey, desIV); CryptoStream cs = new CryptoStream(inS, mode, CryptoStreamMode.Read); byte[] bin = new byte[100]; int len; while ((len = cs.Read(bin, 0, bin.Length)) != 0) { outS.Write(bin, 0, len); } //流位置重置 inS.Position = 0; outS.Position = 0; return true; } catch (Exception exc) { MessageBox.Show(exc.Message, "错误"); return false; } }
internal static byte[] DecryptToBytes(byte[] cipher) { if ((cipher == null) || (cipher.Length <= 0)) throw new ArgumentException("Cipher Text"); try { byte[] plainBytes = null; using (MemoryStream msDecrypt = new MemoryStream(cipher)) { byte[] buffer = new byte[1024]; int readBytes = 0; using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (MemoryStream utf8Memory = new MemoryStream()) { while ((readBytes = csDecrypt.Read(buffer, 0, buffer.Length)) > 0) { utf8Memory.Write(buffer, 0, readBytes); } plainBytes = utf8Memory.ToArray(); } } } return plainBytes; } catch (Exception ex) { throw new CryptoException(ex.Message); } }
public static string Decrypt(string cipherText, string passPhrase) { if (cipherText != null && cipherText != "") { byte[] cipherTextBytes = Convert.FromBase64String(cipherText); using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null)) { byte[] keyBytes = password.GetBytes(keysize / 8); using (RijndaelManaged symmetricKey = new RijndaelManaged()) { symmetricKey.Mode = CipherMode.CBC; using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)) { using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes)) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) { byte[] plainTextBytes = new byte[cipherTextBytes.Length]; int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount); } } } } } } return ""; }
/// <summary> /// Decrypts an AES-encrypted string. /// </summary> /// <param name="cipherText">Text to be decrypted</param> /// <returns>A decrypted string</returns> public string Decrypt(byte[] cipherTextBytes) { string content = string.Empty; try { byte[] keyBytes = new Rfc2898DeriveBytes(Pass, Salt).GetBytes(KEY_LENGTH / 8); byte[] plainTextBytes = new byte[cipherTextBytes.Length]; using (RijndaelManaged symmetricKey = new RijndaelManaged()) { symmetricKey.Mode = CipherMode.CBC; using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, IV)) { using (MemoryStream memStream = new MemoryStream(cipherTextBytes)) { using (CryptoStream cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read)) { int byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); content = Encoding.UTF8.GetString(plainTextBytes, 0, byteCount); } } } } } catch(Exception ex) { Debug.LogException(ex); } return content; }
public static string DecryptTextFromMemory(byte[] Data, byte[] Key, byte[] IV) { try { // Create a new MemoryStream using the passed // array of encrypted data. MemoryStream msDecrypt = new MemoryStream(Data); // Create a CryptoStream using the MemoryStream // and the passed key and initialization vector (IV). CryptoStream csDecrypt = new CryptoStream(msDecrypt, new TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV), CryptoStreamMode.Read); // Create buffer to hold the decrypted data. byte[] fromEncrypt = new byte[Data.Length]; // Read the decrypted data out of the crypto stream // and place it into the temporary buffer. csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length); //Convert the buffer into a string and return it. return new ASCIIEncoding().GetString(fromEncrypt); } catch (CryptographicException e) { Console.WriteLine("A Cryptographic error occurred: {0}", e.Message); return null; } }
public static string AESDecrypt(string decryptStr, string decryptKey) { string result; if (string.IsNullOrWhiteSpace(decryptStr)) { result = string.Empty; } else { decryptKey = StringHelper.SubString(decryptKey, 32); decryptKey = decryptKey.PadRight(32, ' '); byte[] array = System.Convert.FromBase64String(decryptStr); System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm = System.Security.Cryptography.Rijndael.Create(); symmetricAlgorithm.Key = System.Text.Encoding.UTF8.GetBytes(decryptKey); symmetricAlgorithm.IV = SecureHelper._aeskeys; byte[] array2 = new byte[array.Length]; using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(array)) { using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, symmetricAlgorithm.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read)) { cryptoStream.Read(array2, 0, array2.Length); cryptoStream.Close(); memoryStream.Close(); } } result = System.Text.Encoding.UTF8.GetString(array2).Replace("\0", ""); } return(result); }
///<summary> /// Steve Lydford - 12/05/2008. /// /// Decrypts a file using Rijndael algorithm. ///</summary> ///<param name="inputFile"></param> ///<param name="outputFile"></param> private void decryptFile(string inputFile, string outputFile) { FileStream fsCrypt = null; FileStream fsOut = null; CryptoStream cryptStream = null; try { UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(TPW); fsCrypt = new FileStream(inputFile, FileMode.Open); RijndaelManaged RMCrypto = new RijndaelManaged(); cryptStream = new CryptoStream(fsCrypt, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read); byte[] inBytes = File.ReadAllBytes(inputFile); cryptStream.Read(inBytes, 0, inBytes.Length); fsOut = new FileStream(outputFile, FileMode.Create); fsOut.Write(inBytes, 0, inBytes.Length); } finally { if ( fsOut != null ) fsOut.Close(); if ( cryptStream != null ) cryptStream.Close(); } }
public static string Decrypt(string TextToBeDecrypted) { RijndaelManaged RijndaelCipher = new RijndaelManaged(); string Password = "******"; string DecryptedData; try { byte[] EncryptedData = Convert.FromBase64String(TextToBeDecrypted); byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString()); //Making of the key for decryption PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt); //Creates a symmetric Rijndael decryptor object. ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16)); MemoryStream 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); memoryStream.Close(); cryptoStream.Close(); //Converting to string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount); } catch { DecryptedData = TextToBeDecrypted; } return DecryptedData; }
/// <summary> /// Decrypts a string /// </summary> /// <param name="CipherText">Text to be decrypted</param> /// <param name="Password">Password to decrypt with</param> /// <param name="Salt">Salt to decrypt with</param> /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param> /// <param name="PasswordIterations">Number of iterations to do</param> /// <param name="InitialVector">Needs to be 16 ASCII characters long</param> /// <param name="KeySize">Can be 128, 192, or 256</param> /// <returns>A decrypted string</returns> public static string Decrypt(string CipherText, string Password, string Salt = "Kosher", string HashAlgorithm = "SHA1", int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY", int KeySize = 256) { if (string.IsNullOrEmpty(CipherText)) return ""; byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector); byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt); byte[] CipherTextBytes = Convert.FromBase64String(CipherText); PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations); byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8); RijndaelManaged SymmetricKey = new RijndaelManaged(); SymmetricKey.Mode = CipherMode.CBC; byte[] PlainTextBytes = new byte[CipherTextBytes.Length]; int ByteCount = 0; using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes)) { using (MemoryStream MemStream = new MemoryStream(CipherTextBytes)) { using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read)) { ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length); MemStream.Close(); CryptoStream.Close(); } } } SymmetricKey.Clear(); return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount); }
public static string Decrypt(string cipherText) { string functionReturnValue = null; try { if ((string.IsNullOrEmpty(cipherText))) { return(string.Empty); } // Convert strings defining encryption key characteristics into byte // arrays. Let us assume that strings only contain ASCII codes. // If strings include Unicode characters, use Unicode, UTF7, or UTF8 // encoding. byte[] initVectorBytes = null; initVectorBytes = Encoding.ASCII.GetBytes(initVector); byte[] saltValueBytes = null; saltValueBytes = Encoding.ASCII.GetBytes(saltValue); // Convert our ciphertext into a byte array. byte[] cipherTextBytes = null; cipherTextBytes = Convert.FromBase64String(cipherText); // First, we must create a password, from which the key will be // derived. This password will be generated from the specified // passphrase and salt value. The password will be created using // the specified hash algorithm. Password creation can be done in // several iterations. //Dim password As PasswordDeriveBytes //password = New PasswordDeriveBytes(passPhrase, _ // saltValueBytes, _ // hashAlgorithm, _ // passwordIterations) //' Use the password to generate pseudo-random bytes for the encryption //' key. Specify the size of the key in bytes (instead of bits). byte[] keyBytes = null; Rfc2898DeriveBytes password = default(Rfc2898DeriveBytes); password = new Rfc2898DeriveBytes(passPhrase, saltValueBytes, passwordIterations); keyBytes = password.GetBytes(keySize / 8); // Create uninitialized Rijndael encryption object. RijndaelManaged symmetricKey = default(RijndaelManaged); symmetricKey = new RijndaelManaged(); // It is reasonable to set encryption mode to Cipher Block Chaining // (CBC). Use default options for other symmetric key parameters. symmetricKey.Mode = CipherMode.CBC; // Generate decryptor from the existing key bytes and initialization // vector. Key size will be defined based on the number of the key // bytes. ICryptoTransform decryptor = default(ICryptoTransform); decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes); // Define memory stream which will be used to hold encrypted data. MemoryStream memoryStream = default(MemoryStream); memoryStream = new MemoryStream(cipherTextBytes); // Define memory stream which will be used to hold encrypted data. System.Security.Cryptography.CryptoStream cryptoStream = default(System.Security.Cryptography.CryptoStream); cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read); // Since at this point we don't know what the size of decrypted data // will be, allocate the buffer long enough to hold ciphertext; // plaintext is never longer than ciphertext. byte[] plainTextBytes = null; plainTextBytes = new byte[cipherTextBytes.Length + 1]; // Start decrypting. int decryptedByteCount = 0; decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); // Close both streams. memoryStream.Close(); cryptoStream.Close(); // Convert decrypted data into a string. // Let us assume that the original plaintext string was UTF8-encoded. string plainText = null; plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount); // Return decrypted string. functionReturnValue = plainText; } catch (Exception ex) { return(string.Empty); } return(functionReturnValue); }
public static string DesencriptarMD5(string cipherText) { string strReturn = string.Empty; string p_strSaltValue = "P@SSW@RD@09"; // Convert strings defining encryption key characteristics into byte // arrays. Let us assume that strings only contain ASCII codes. // If strings include Unicode characters, use Unicode, UTF7, or UTF8 // encoding. try { byte[] initVectorBytes; initVectorBytes = System.Text.Encoding.ASCII.GetBytes(m_strInitVector); byte[] saltValueBytes; saltValueBytes = System.Text.Encoding.ASCII.GetBytes(p_strSaltValue); // Convert our ciphertext into a byte array. byte[] cipherTextBytes; cipherTextBytes = Convert.FromBase64String(cipherText); // First, we must create a password, from which the key will be // derived. This password will be generated from the specified // passphrase and salt value. The password will be created using // the specified hash algorithm. Password creation can be done in // several iterations. Rfc2898DeriveBytes password; password = new Rfc2898DeriveBytes(m_strPassPhrase, saltValueBytes, m_strPasswordIterations); // Use the password to generate pseudo-random bytes for the encryption // key. Specify the size of the key in bytes (instead of bits). byte[] keyBytes; int intKeySize; intKeySize = System.Convert.ToInt32((m_intKeySize / (double)8)); keyBytes = password.GetBytes(intKeySize); // Create uninitialized Rijndael encryption object. System.Security.Cryptography.RijndaelManaged symmetricKey; symmetricKey = new System.Security.Cryptography.RijndaelManaged(); // It is reasonable to set encryption mode to Cipher Block Chaining // (CBC). Use default options for other symmetric key parameters. symmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC; // symmetricKey.Padding = PaddingMode.Zeros // Generate decryptor from the existing key bytes and initialization // vector. Key size will be defined based on the number of the key // bytes. System.Security.Cryptography.ICryptoTransform decryptor; decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes); // Define memory stream which will be used to hold encrypted data. System.IO.MemoryStream memoryStream; memoryStream = new System.IO.MemoryStream(cipherTextBytes); // Define memory stream which will be used to hold encrypted data. System.Security.Cryptography.CryptoStream cryptoStream; cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, decryptor, System.Security.Cryptography.CryptoStreamMode.Read); // Since at this point we don't know what the size of decrypted data // will be, allocate the buffer long enough to hold ciphertext; // plaintext is never longer than ciphertext. byte[] plainTextBytes; plainTextBytes = new byte[cipherTextBytes.Length + 1]; // Start decrypting. int decryptedByteCount; decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); // Close both streams. memoryStream.Close(); cryptoStream.Close(); // Convert decrypted data into a string. // Let us assume that the original plaintext string was UTF8-encoded. string plainText; plainText = System.Text.Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount); // Return decrypted string. strReturn = plainText; } catch (Exception ex) { strReturn = null; } return(strReturn); }