public void CreyptoStreamExample() { var algorithm = SymmetricAlgorithm.Create(); //algorithm.GenerateKey(); //algorithm.GenerateIV(); using(var file = File.Create(@".\key.txt")) { // file.Write(algorithm.Key, 0, algorithm.Key.Length); } using (var file = File.Create(@".\IV.txt")) { //file.Write(algorithm.IV, 0, algorithm.IV.Length); } algorithm.Key = KeyAndIV; algorithm.IV = KeyAndIV; var encryptor = algorithm.CreateEncryptor(); algorithm.Padding = PaddingMode.None; using(var inputStream = new FileStream(@".\EncryptedFile.txt", FileMode.OpenOrCreate)) using(var cryptoStream = new CryptoStream(inputStream, encryptor, CryptoStreamMode.Write)) { var input = Encoding.UTF8.GetBytes(SecretText); cryptoStream.Write(input, 0, input.Length); cryptoStream.Clear(); } }
private const String SALT_VALUE = "Abc1@#23!56GH"; //any character #endregion Fields #region Methods 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; }
public byte[] Encrypt(byte[] srcData, string strKey) { byte[] buffer = HashDigest.StringDigest(strKey, DigestType.MD5); SymmetricAlgorithm algorithm = SymmetricAlgorithm.Create("3DES"); algorithm.Key = buffer; algorithm.IV = Keys; new DESCryptoServiceProvider(); MemoryStream stream = new MemoryStream(); CryptoStream stream2 = new CryptoStream(stream, algorithm.CreateEncryptor(), CryptoStreamMode.Write); stream2.Write(srcData, 0, srcData.Length); stream2.FlushFinalBlock(); stream2.Clear(); return stream.ToArray(); }
// Internal helper function to do the encryption/decryption protected static byte[] Crypt(byte[] bValue, string sPassword, string sSalt, bool bEncrypt) { byte[] bReturnVal = null; AesManaged aesTransform = null; MemoryStream msStream = null; CryptoStream csCryptoStream = null; try { // Rfc2898DeriveBytes (PBKDF2) is similar to using PasswordDeriveBytes (PBKDF1) but the algorithm is stronger apparently Rfc2898DeriveBytes pwdGen = new Rfc2898DeriveBytes(sPassword, Encoding.Unicode.GetBytes(sSalt), 1000); // Create our AES Key and Initialization Vector (IV) values aesTransform = new AesManaged(); aesTransform.Key = pwdGen.GetBytes(aesTransform.KeySize / 8); aesTransform.IV = pwdGen.GetBytes(aesTransform.BlockSize / 8); aesTransform.Padding = PaddingMode.ISO10126;// Pad with random characters rather than zeros // Depending on if we're encrypting or decrypting create the proper transform object ICryptoTransform ctTransform = (bEncrypt ? aesTransform.CreateEncryptor() : aesTransform.CreateDecryptor()); // Create our memory stream and encryption/decryption stream object msStream = new MemoryStream(); csCryptoStream = new CryptoStream(msStream, ctTransform, CryptoStreamMode.Write); // Encrypt/Decrypt the value csCryptoStream.Write(bValue, 0, bValue.Length); csCryptoStream.FlushFinalBlock(); // Turn our encrypted/decrypted memory stream value into a byte array bReturnVal = msStream.ToArray(); } finally { if (csCryptoStream != null) { csCryptoStream.Clear(); csCryptoStream.Close(); } if (msStream != null) { msStream.Close(); } if (aesTransform != null) { aesTransform.Clear(); } } // Return the encrypted/decrypted value return bReturnVal; }
/// <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(); }
/// <summary> /// Encrypts or decrypts the refresh token. /// </summary> /// <param name="key">Key used for decryption</param> /// <param name="bytes">Refresh Token bytes</param> /// <param name="encryptor">AES object for encryption or decryption</param> /// <param name="isEncrypt">Checks for encryption/decryption</param> /// <returns>Returns the encrypted or decrypted refresh token depending on the AES object being passed</returns> private static string EncryptDecryptRefreshToken(string key, byte[] bytes, bool isEncrypt) { string refreshToken = string.Empty; if (!string.IsNullOrEmpty(ConstantStrings.EncryptionVector) && !string.IsNullOrEmpty(key) && null != bytes) { byte[] vector = new byte[ConstantStrings.EncryptionVector.Length * sizeof(char)]; System.Buffer.BlockCopy(key.ToCharArray(), 0, vector, 0, vector.Length); CryptoStream cryptoStream = null; using (Aes encryptor = Aes.Create()) { using (Rfc2898DeriveBytes encryptObject = new Rfc2898DeriveBytes(key, vector)) { encryptor.Key = encryptObject.GetBytes(32); // 32 bytes encryption key encryptor.IV = encryptObject.GetBytes(16); // 16 bytes initialization vector } using (MemoryStream memoryStream = new MemoryStream()) { if (isEncrypt) { // To encrypt the refresh token cryptoStream = new CryptoStream(memoryStream, encryptor.CreateEncryptor(), CryptoStreamMode.Write); // Creates an object to apply the cryptographic transformation to a memory stream cryptoStream.Write(bytes, 0, bytes.Length); // Applies the cryptographic transformation to refresh token cryptoStream.Clear(); refreshToken = Convert.ToBase64String(memoryStream.ToArray()); } else { // To decrypt the refresh token cryptoStream = new CryptoStream(memoryStream, encryptor.CreateDecryptor(), CryptoStreamMode.Write); cryptoStream.Write(bytes, 0, bytes.Length); cryptoStream.Clear(); refreshToken = Encoding.Unicode.GetString(memoryStream.ToArray()); } } } } return refreshToken; }
/// <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; }
// IDisposable methods protected override void Dispose(bool disposing) { if (disposing) { // dispose of our internal state if (des != null) { des.Clear(); } if (m_encryptor != null) { m_encryptor.Dispose(); } if (_cs != null) { _cs.Clear(); } if (_ts != null) { _ts.Clear(); } } base.Dispose(disposing); }
[ExpectedException (typeof (ArgumentNullException))] // to match exception throw by Read in a similar case #endif public void Write_Disposed () { // do no corrupt writeStream in further tests using (Stream s = new MemoryStream ()) { byte[] buffer = new byte [8]; cs = new CryptoStream (s, encryptor, CryptoStreamMode.Write); cs.Clear (); cs.Write (buffer, 0, 8); } }
[ExpectedException (typeof (ArgumentNullException))] // should fail like previous test case #endif public void Read_Disposed_Break () { // do no corrupt readStream in further tests using (Stream s = new MemoryStream ()) { byte[] buffer = new byte [8]; cs = new CryptoStream (s, encryptor, CryptoStreamMode.Read); int len = cs.Read (buffer, 0, 4); Assert.AreEqual (4, len, "Read 4"); cs.Clear (); len = cs.Read (buffer, 3, 4); } }
public void Read_Disposed () { // do no corrupt readStream in further tests using (Stream s = new MemoryStream ()) { byte[] buffer = new byte [8]; cs = new CryptoStream (s, encryptor, CryptoStreamMode.Read); cs.Clear (); Assert.AreEqual (0, cs.Read (buffer, 0, 8), "Read from disposed"); } }
public void FlushFinalBlock_Disposed () { // do no corrupt writeStream in further tests using (Stream s = new MemoryStream ()) { cs = new CryptoStream (s, encryptor, CryptoStreamMode.Write); cs.Clear (); cs.FlushFinalBlock (); } }
public void DecryptData(string inName, string outName) { FileStream fileStream1 = new FileStream(inName, FileMode.Open, FileAccess.Read); FileStream fileStream2 = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write); fileStream2.SetLength(0L); this.desKey[0] = (byte) 20; this.desKey[1] = (byte) 157; this.desKey[2] = (byte) 64; this.desKey[3] = (byte) 213; this.desKey[4] = (byte) 193; this.desKey[5] = (byte) 46; this.desKey[6] = (byte) 85; this.desKey[7] = (byte) 2; this.desIV[0] = (byte) 0; this.desIV[1] = (byte) 0; this.desIV[2] = (byte) 0; this.desIV[3] = (byte) 0; this.desIV[4] = (byte) 0; this.desIV[5] = (byte) 0; this.desIV[6] = (byte) 0; this.desIV[7] = (byte) 0; byte[] numArray = new byte[8]; long num = 8L; long length = fileStream1.Length; DESCryptoServiceProvider cryptoServiceProvider = new DESCryptoServiceProvider(); cryptoServiceProvider.Mode = CipherMode.CBC; cryptoServiceProvider.Padding = PaddingMode.None; CryptoStream cryptoStream = new CryptoStream((Stream) fileStream2, cryptoServiceProvider.CreateDecryptor(this.desKey, this.desIV), CryptoStreamMode.Write); for (; num <= length; { int count; num = (long) Convert.ToInt32((double) num + (double) count / (double) cryptoServiceProvider.BlockSize * (double) cryptoServiceProvider.BlockSize); } ) { count = fileStream1.Read(numArray, 0, 8); cryptoStream.Write(numArray, 0, count); } cryptoStream.Close(); fileStream1.Close(); fileStream2.Close(); cryptoStream.Clear(); cryptoServiceProvider.Clear(); }
/// <summary> /// 对字符串的加密处理 /// </summary> /// <param name="source">需要加密的字符串</param> /// <returns>加密后的字符串</returns> /// <remarks>对字符串的加密处理 /// <code source="..\Framework\TestProjects\DeluxeWorks.Library.Test\Core\CryptoHelperTest.cs" lang="cs" region="EncryptTest" title="DES算法字符串加密"/> /// </remarks> public static string Encrypt(string source) { byte[] buff = Encoding.Unicode.GetBytes(source); MemoryStream mem = new MemoryStream(); CryptoStream stream = new CryptoStream(mem, CryptoHelper.et, CryptoStreamMode.Write); stream.Write(buff, 0, buff.Length); stream.FlushFinalBlock(); stream.Clear(); return Convert.ToBase64String(mem.ToArray()); }
/// <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; }
//////////////////////////////////////////////////////////////////// // Encrypt byte array //////////////////////////////////////////////////////////////////// internal Byte[] EncryptByteArray( Int32 ObjectNumber, Byte[] PlainText ) { // create encryption key Byte[] EncryptionKey = CreateEncryptionKey(ObjectNumber); Byte[] CipherText; if(EncryptionType == EncryptionType.Aes128) { MemoryStream OutputStream = null; CryptoStream CryptoStream = null; // generate new initialization vector IV AES.GenerateIV(); // create cipher text buffer including initialization vector Int32 CipherTextLen = (PlainText.Length & 0x7ffffff0) + 16; CipherText = new Byte[CipherTextLen + 16]; Array.Copy(AES.IV, 0, CipherText, 0, 16); // set encryption key and key length AES.Key = EncryptionKey; // Create the streams used for encryption. OutputStream = new MemoryStream(); CryptoStream = new CryptoStream(OutputStream, AES.CreateEncryptor(), CryptoStreamMode.Write); // write plain text byte array CryptoStream.Write(PlainText, 0, PlainText.Length); // encrypt plain text to cipher text CryptoStream.FlushFinalBlock(); // get the result OutputStream.Seek(0, SeekOrigin.Begin); OutputStream.Read(CipherText, 16, CipherTextLen); // release resources CryptoStream.Clear(); OutputStream.Close(); } else { CipherText = (Byte[]) PlainText.Clone(); EncryptRC4(EncryptionKey, CipherText); } // return result return(CipherText); }
/// <summary> /// Decrypts a string using a given private key /// </summary> /// <param name="strCipherText">Text to be decrypted</param> /// <param name="privateKey">Private Key used to decrypt</param> /// <returns>Decrypted Text</returns> /// <remarks>The parameter must be 24 characters long</remarks> private static string TripleDESPrivateKeyDecryption(string strCipherText, string privateKey) { TripleDESCryptoServiceProvider crp = new TripleDESCryptoServiceProvider(); UnicodeEncoding uEncode = new UnicodeEncoding(); MemoryStream stmPlainText = new MemoryStream(); byte[] bytCipherText; byte[] slt = new byte[0]; byte[] bytDerivedKey; bytCipherText = Convert.FromBase64String(strCipherText); MemoryStream stmCipherText = new MemoryStream(bytCipherText); crp.KeySize = TRIPLE_DES_KEY_SIZE; PasswordDeriveBytes pdb = new PasswordDeriveBytes(privateKey, slt); 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> /// SimpleEncrypts the plaintext. /// </summary> /// <param name="plaintext">The plaintext to be encrypted.</param> /// <returns>The encrypted plaintext (-> ciphertext).</returns> private byte[] SimpleEncrypt(byte[] plaintext) { byte[] ciphertext = null; MemoryStream memoryStream = new MemoryStream(); byte[] IV = new byte[16]; //Creates the default implementation, which is RijndaelManaged. SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); //RNGCryptoServiceProvider is an implementation of a random number generator. RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); // The array is now filled with cryptographically strong random bytes, and none are zero. rng.GetNonZeroBytes(IV); // creates a symmetric encryptor object with the specified Key and initialization vector (IV). ICryptoTransform encryptor = rijn.CreateEncryptor(this.key, IV); // write the unencrypted initialization vector memoryStream.Write(IV, 0, IV.Length); // prepare the Crypto Stream CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write); // write plaintext into compressed and encrypted stream cryptoStream.Write(plaintext, 0, plaintext.Length); cryptoStream.Close(); cryptoStream.Clear(); // Umwandlung in einen Base64 String, damit die Daten auch serialisiert werden können (.xml) byte[] binaryData = memoryStream.ToArray(); string base64String = Convert.ToBase64String(binaryData); ciphertext = AnsiStringToByteArray(base64String); // Speicher frei geben memoryStream.Close(); encryptor.Dispose(); rijn.Clear(); return ciphertext; }
public static string SimpleDecrpyt(string crypt_text) { if (rijn == null) { SetupEncryption(); } byte[] crypt_buffer = Convert.FromBase64String(crypt_text); MemoryStream ms = new MemoryStream(crypt_buffer); CryptoStream crypt_stream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read); byte[] clear_buffer = new byte[crypt_buffer.Length]; crypt_stream.Read(clear_buffer, 0, clear_buffer.Length); crypt_stream.Clear(); crypt_stream.Close(); int end_index; for (end_index = clear_buffer.Length - 1; end_index > 0 && clear_buffer[end_index] == 0; end_index--) ; byte[] trunc_buffer = new byte[end_index + 1]; Array.Copy(clear_buffer, trunc_buffer, end_index + 1); return UTF8Encoding.UTF8.GetString(trunc_buffer); }
public static string SimpleEncrypt(string clear_text) { if (rijn == null) { SetupEncryption(); } MemoryStream ms = new MemoryStream(); CryptoStream crypt_stream = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); byte[] clear_buffer = UTF8Encoding.UTF8.GetBytes(clear_text); crypt_stream.Write(clear_buffer, 0, clear_buffer.Length); crypt_stream.FlushFinalBlock(); crypt_stream.Clear(); crypt_stream.Close(); return Convert.ToBase64String(ms.ToArray()); }
/// <summary> /// 解密为数据 /// </summary> /// <param name="s"></param> /// <returns></returns> public byte[] DecryptData(string s) { CheckUtil.ArgumentNotNullOrEmpty(s, "s"); byte[] inputData = Convert.FromBase64String(s); byte[] outputData = null; 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); outputData = new byte[inputData.Length]; cs.Read(outputData, 0, outputData.Length); cs.Clear(); cs.Close(); } return outputData; }
public void PartialRoundtripRead () { byte[] encrypted; using (DebugStream mem1 = new DebugStream ()) { byte[] toEncrypt = Encoding.Unicode.GetBytes ("Please encode me!"); using (CryptoStream crypt = new CryptoStream (mem1, aes.CreateEncryptor (), CryptoStreamMode.Write)) { crypt.Write (toEncrypt, 0, toEncrypt.Length); crypt.FlushFinalBlock (); } encrypted = mem1.ToArray (); } using (DebugStream mem2 = new DebugStream (encrypted)) { byte[] buffer = new byte [1024]; CryptoStream cr = new CryptoStream (mem2, aes.CreateDecryptor (), CryptoStreamMode.Read); int len = cr.Read (buffer, 0, 20); cr.Clear (); cr.Close (); Assert.AreEqual (20, len, "Partial Length Read"); Assert.AreEqual ("Please enc", Encoding.Unicode.GetString (buffer, 0, len), "Partial Block Read"); } }
/// <summary> /// 同上反推解密 /// </summary> /// <param name="inName">要解密的檔案路徑</param> /// <param name="outName">解密成原始資料後的檔案路徑</param> /// <param name="rijnKey">加密金鑰(規定要16 byte)</param> /// <param name="rijnIV">initial value初始值(加解密雙方都要一樣)</param> /// <returns></returns> static byte[] DecryptData(string inName, string outName, byte[] rijnKey, byte[] rijnIV) { //Create the file streams to handle the input and output files. FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read); FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write); byte[] decData = new byte[0x1000]; //用來裝解密後的資料 int decData_len = 0; //解密後資料的長度 fin.Position = 0; //設定資料流讀取的初始位置 //data_len = fin.Read(data_Buffer, 0, data_Buffer.Length);//(這是錯誤的)不能先讀,讀完資料流內就沒資料了 //使用rijn演算法 SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); //使用cryptoStream來讀取加密的資料流並設定解密的cryptor(Key,IV) CryptoStream decStream = new CryptoStream(fin, rijn.CreateDecryptor(rijnKey, rijnIV), CryptoStreamMode.Read); Console.WriteLine("Decrypting..."); //******************************************************* //StreamReader streamReader = new StreamReader(decStream); //string data = streamReader.ReadToEnd(); //Console.WriteLine("Decrypt data:{0}", data); //decData = Encoding.ASCII.GetBytes(data); //******************************************************* decData_len = decStream.Read(decData, 0, decData.Length);//將解密的資料讀到buffer if (!decStream.HasFlushedFinalBlock) decStream.FlushFinalBlock(); Array.Resize(ref decData,decData_len);//縮一下buffer大小 fout.Write(decData, 0, decData.Length);//從另一個資料流將解密後的資料寫入 fout.Flush(); decStream.Clear(); decStream.Close(); fin.Close(); fout.Close(); return decData; }
public void WriteOnBlockWithFinal () { byte[] desKey = {0, 1, 2, 3, 4, 5, 6, 7}; byte[] desIV = {0, 1, 2, 3, 4, 5, 6, 7}; DES des = DES.Create (); MemoryStream msin = new MemoryStream (); CryptoStream enc = new CryptoStream (msin, des.CreateEncryptor (desKey, desIV), CryptoStreamMode.Write); byte[] data = new byte [2200]; enc.Write (data, 0, 2200); enc.FlushFinalBlock (); msin.Position = 0; Assert.AreEqual (2208, msin.Length, "Encryped Write Length"); // 2200 + padding MemoryStream msout = new MemoryStream (); msout.SetLength (0); byte[] tmp = new byte [1024]; long readlen = 0; long totallen = msin.Length; CryptoStream dec = new CryptoStream (msout, des.CreateDecryptor (desKey, desIV), CryptoStreamMode.Write); int len = msin.Read (tmp, 0, 1024); while (len > 0) { dec.Write (tmp, 0, len); readlen += len; len = msin.Read (tmp, 0, 1024); } Assert.AreEqual (2200, msout.Length, "Decryped Write Length"); dec.Close (); dec.Clear (); msout.Close (); msin.Close (); Assert.AreEqual (2208, readlen, "Read Length"); // 2200 + padding }
// LAMESPEC or MS BUG [ExpectedException (typeof (ObjectDisposedException))] public void Read_Disposed () { // do no corrupt readStream in further tests using (Stream s = new MemoryStream ()) { byte[] buffer = new byte [8]; cs = new CryptoStream (s, encryptor, CryptoStreamMode.Read); cs.Clear (); try { cs.Read (buffer, 0, 8); Assert.Fail (); } catch (NotSupportedException) { } } }
/// <summary> /// ����� "�����������" /// </summary> private void Encrypt(byte[] data, int length, byte[] key, byte[] iv) { Rijndael rijndael = new RijndaelManaged(); rijndael.Mode = CipherMode.CBC; rijndael.BlockSize = rijndael.KeySize = 256; ICryptoTransform ict = rijndael.CreateEncryptor(key, iv); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, ict, CryptoStreamMode.Write); cs.Write(data, 0, length); cs.FlushFinalBlock(); Array.Copy(ms.GetBuffer(), data, ms.Length); cs.Close(); cs.Clear(); rijndael.Clear(); }
/// <summary> /// Decrypts an array of AES 256 encrypted bytes to a plain text string. /// </summary> /// <param name="cipherText">The bytes to decrypt.</param> /// <param name="key">The key used by the decryption algorithm.</param> /// <param name="iv">The initialization vector used by the decryption algorithm.</param> /// <returns>The decrypted string, or null if the byte array could not be decrypted.</returns> public static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] iv) { // Check arguments. if (cipherText == null || cipherText.Length <= 0) { throw new ArgumentNullException("cipherText"); } if (key == null || key.Length <= 0) { throw new ArgumentNullException("key"); } if (iv == null || iv.Length <= 0) { throw new ArgumentNullException("iv"); } // Declare the RijndaelManaged object used to decrypt the data. RijndaelManaged aesAlg = null; // Declare the string used to hold the decrypted text. string text = null; try { // Create a RijndaelManaged object with the specified key and IV. aesAlg = new RijndaelManaged(); try { aesAlg.Key = key; try { aesAlg.IV = iv; // Create a decryptor to perform the stream transform. ICryptoTransform decryptor = null; try { decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for decryption. using (MemoryStream msDecrypt = new MemoryStream(cipherText)) { CryptoStream csDecrypt = null; try { csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); StreamReader srDecrypt = null; try { srDecrypt = new StreamReader(csDecrypt); // Read the decrypted bytes from the decrypting stream // and place them in a string. try { text = srDecrypt.ReadToEnd(); } catch (OutOfMemoryException) { // There is insufficient memory to allocate a buffer for the returned string. return null; } catch (IOException) { // An I/O error occurred. return null; } finally { // Close the StreamReader. if (srDecrypt != null) { srDecrypt.Close(); } } } catch (ArgumentException) { // The StreamReader does not support reading. return null; } finally { // Close the StreamReader. if (srDecrypt != null) { srDecrypt.Close(); } } } catch (ArgumentException) { // The CryptoStream is not readable, or writeable, or is invalid. return null; } finally { // Clear the CryptoStream. if (csDecrypt != null) { csDecrypt.Clear(); } } } } catch (CryptographicException) { // The value of the ICryptoTransform's Mode parameter is not ECB, CBC, or CFB. return null; } finally { // Dispose of the ICryptoTransform. if (decryptor != null) { decryptor.Dispose(); } } } catch (CryptographicException) { // An attempt was made to set the initialization vector to an invalid size. return null; } } catch (CryptographicException) { // The key size is invalid. return null; } } catch (InvalidOperationException) { // The RijndaelManaged class is not compliant with the FIPS algorithm. return null; } finally { // Clear the RijndaelManaged object. if (aesAlg != null) aesAlg.Clear(); } return text; }
/// <summary> /// 解密文件 /// </summary> /// <param name="SourceFilePath">源文件路径(被解密的文件路径)</param> /// <param name="TargetFilePath">目标文件路径(解密后生成的文件路径)</param> /// <param name="DecryptKey">解密文件用的密钥</param> public static void DecryptFile(string SourceFilePath, string TargetFilePath, string DecryptKey) { if (string.IsNullOrEmpty(SourceFilePath)) { throw new SourceFilePathIsNullOrEmptyException(); } FileInfo fi = new FileInfo(SourceFilePath); if (!fi.Exists) { throw new SourceFileNotExistException(); } if (fi.Length > 2048000) { throw new FileSizeIsGreaterThan2MException(); } if (string.IsNullOrEmpty(TargetFilePath)) { throw new TargetFilePathIsNullOrEmptyException(); } if (string.IsNullOrEmpty(DecryptKey)) { throw new EncryptKeyIsNullOrEmptyException(); } byte[] IV = { 0x1E, 0xA2, 0x61, 0x5F, 0xD0, 0x3C, 0x99, 0xBB };//这里要与加密的相同,否则解密出来的结果会不相同。 if (DecryptKey.Length < 8) { DecryptKey = DecryptKey.PadRight(8, '0'); } else if (DecryptKey.Length > 8) { DecryptKey = DecryptKey.Remove(8); } byte[] byKey = null; byKey = Encoding.UTF8.GetBytes(DecryptKey.Substring(0, 8)); using (FileStream fsSource = new FileStream(SourceFilePath, FileMode.Open, FileAccess.Read)) { using (MemoryStream ms = new MemoryStream()) { byte[] bSource = new byte[100]; long readLength = 0; long writeLength = fsSource.Length; int iLength = 0; DES des = new DESCryptoServiceProvider(); try { using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)) { while (readLength < writeLength) { iLength = fsSource.Read(bSource, 0, bSource.Length); cs.Write(bSource, 0, iLength); readLength = readLength + iLength; } cs.FlushFinalBlock(); using (FileStream fsTarget = new FileStream(TargetFilePath, FileMode.OpenOrCreate, FileAccess.Write)) { ms.WriteTo(fsTarget); fsTarget.Close(); } cs.Clear(); cs.Close(); } } catch (CryptographicException) { throw new DecryptErrorException(); } des.Clear(); ms.Close(); } fsSource.Close(); } }
/// <summary> /// Encrypts a string of text to an array of AES 256 encrypted bytes. /// </summary> /// <param name="text">The text to encrypt.</param> /// <param name="key">The key used by the encryption algorithm.</param> /// <param name="iv">The initialization vector used by the encryption algorithm.</param> /// <returns>An encrypted array of bytes, or an empty array of bytes if the string could not /// be encrypted.</returns> public static byte[] EncryptStringToBytes(string text, byte[] key, byte[] iv) { // Check the arguments. if (string.IsNullOrWhiteSpace(text)) { throw new ArgumentNullException("text"); } if (key == null || key.Length <= 0) { throw new ArgumentNullException("key"); } if (iv == null || iv.Length <= 0) { throw new ArgumentNullException("iv"); } // Declare the stream used to encrypt to an in memory array of bytes. MemoryStream msEncrypt = null; // Declare the RijndaelManaged object used to encrypt the data. RijndaelManaged aesAlg = null; try { // Create a RijndaelManaged object with the specified key and IV. aesAlg = new RijndaelManaged(); try { aesAlg.Key = key; try { aesAlg.IV = iv; // Create an encryptor to perform the stream transform. ICryptoTransform encryptor = null; try { encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for encryption. msEncrypt = new MemoryStream(); CryptoStream csEncrypt = null; try { csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write); StreamWriter swEncrypt = null; try { swEncrypt = new StreamWriter(csEncrypt); //Write all data to the stream. try { swEncrypt.Write(text); } catch (ObjectDisposedException) { // AutoFlush is true of the StreamWriter buffer is full, and the current writer is closed. return new byte[0]; } catch (NotSupportedException) { // AutoFlush is true or the StreamWriter buffer is full, and the contents of the buffer // can not be written to the underlying fixed size stream because the StreamWriter is // at the end of the stream. return new byte[0]; } catch (IOException) { // An I/O error occurred. return new byte[0]; } } catch (ArgumentException) { // The StreamWriter is not writable. return new byte[0]; } finally { // Close the StreamWriter. if (swEncrypt != null) { swEncrypt.Close(); } } } catch (ArgumentException) { // The CryptoStream is not readable, or writeable, or is invalid. return new byte[0]; } finally { // Clear the CryptoStream. if (csEncrypt != null) { csEncrypt.Clear(); } } } catch (CryptographicException) { // The value of the ICryptoTransform's Mode parameter is not ECB, CBC, or CFB. return new byte[0]; } finally { // Dispose of the ICryptoTransform. if (encryptor != null) { encryptor.Dispose(); } } } catch (CryptographicException) { // An attempt was made to set the initialization vector to an invalid size. return new byte[0]; } } catch (CryptographicException) { // The key size is invalid. return new byte[0]; } } catch (InvalidOperationException) { // The RijndaelManaged class is not compliant with the FIPS algorithm. return new byte[0]; } finally { // Clear the RijndaelManaged object. if (aesAlg != null) { aesAlg.Clear(); } } // Return the encrypted bytes from the memory stream. return msEncrypt.ToArray(); }
/// <summary> /// ����� "������������" /// </summary> private bool Decrypt(byte[] data, int length, byte[] key, byte[] iv) { Rijndael rijndael = new RijndaelManaged(); rijndael.Mode = CipherMode.CBC; rijndael.BlockSize = rijndael.KeySize = 256; ICryptoTransform ict = rijndael.CreateDecryptor(key, iv); MemoryStream ms = new MemoryStream(); ms.Write(data, 0, length); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); CryptoStream cs = new CryptoStream(ms, ict, CryptoStreamMode.Read); try { cs.Read(data, 0, length); } catch(CryptographicException) { return false; } cs.Close(); cs.Clear(); rijndael.Clear(); return true; }
public void EncryptData(string inName, string outName) { FileStream fileStream = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write); fileStream.SetLength(0L); this.desKey[0] = (byte) 20; this.desKey[1] = (byte) 157; this.desKey[2] = (byte) 64; this.desKey[3] = (byte) 213; this.desKey[4] = (byte) 193; this.desKey[5] = (byte) 46; this.desKey[6] = (byte) 85; this.desKey[7] = (byte) 2; this.desIV[0] = (byte) 0; this.desIV[1] = (byte) 0; this.desIV[2] = (byte) 0; this.desIV[3] = (byte) 0; this.desIV[4] = (byte) 0; this.desIV[5] = (byte) 0; this.desIV[6] = (byte) 0; this.desIV[7] = (byte) 0; byte[] buffer = new byte[8]; long num1 = 8L; long num2 = (long) inName.Length; DESCryptoServiceProvider cryptoServiceProvider = new DESCryptoServiceProvider(); cryptoServiceProvider.Mode = CipherMode.CBC; cryptoServiceProvider.Padding = PaddingMode.None; CryptoStream cryptoStream = new CryptoStream((Stream) fileStream, cryptoServiceProvider.CreateEncryptor(this.desKey, this.desIV), CryptoStreamMode.Write); this.i = 0; do { buffer[this.i] = checked ((byte) Strings.Asc(Strings.Mid(inName, this.i + 1, 1))); checked { ++this.i; } } while (this.i <= 7); for (; num1 <= num2; { int count; num1 = (long) Convert.ToInt32((double) num1 + (double) count / (double) cryptoServiceProvider.BlockSize * (double) cryptoServiceProvider.BlockSize); } ) { count = 8; cryptoStream.Write(buffer, 0, count); } cryptoStream.Close(); fileStream.Close(); cryptoStream.Clear(); cryptoServiceProvider.Clear(); try { this.DES_file_name = FileSystem.CurDir() + "\\Password.dat"; FileInfo fileInfo = new FileInfo(this.DES_file_name); if (!fileInfo.Exists) { int num3 = (int) Interaction.MsgBox((object) ("DES output file : " + this.DES_file_name + " does not exist in the local directory"), MsgBoxStyle.OkOnly, (object) null); } this.DES_file_number = FileSystem.FreeFile(); this.DES_file_buffer_len = checked ((int) fileInfo.Length); FileSystem.FileOpen(this.DES_file_number, this.DES_file_name, OpenMode.Binary, OpenAccess.Read, OpenShare.Default, this.DES_file_buffer_len); } catch (Exception ex) { ProjectData.SetProjectError(ex); int num3 = (int) Interaction.MsgBox((object) ("Unable to open DES output file " + this.DES_file_name), MsgBoxStyle.OkOnly, (object) null); ProjectData.ClearProjectError(); } try { FileSystem.FileGet(this.DES_file_number, ref this.DES_file_string_bytes, -1L, false); this.DESBox.Text = ""; MainForm mainForm = this; int num3 = 0; int num4 = checked (this.DES_file_buffer_len - 2); mainForm.i = num3; while (this.i <= num4) { if (Strings.Len(Conversion.Hex(Strings.Asc(Strings.Mid(this.DES_file_string_bytes, checked (this.i + 1), 1)))) == 2) { TextBox desBox = this.DESBox; desBox.Text = desBox.Text + Conversion.Hex(Strings.Asc(Strings.Mid(this.DES_file_string_bytes, checked (this.i + 1), 1))) + "."; } else { TextBox desBox = this.DESBox; desBox.Text = desBox.Text + "0" + Conversion.Hex(Strings.Asc(Strings.Mid(this.DES_file_string_bytes, checked (this.i + 1), 1))) + "."; } checked { ++this.i; } } if (Strings.Len(Conversion.Hex(Strings.Asc(Strings.Mid(this.DES_file_string_bytes, this.DES_file_buffer_len, 1)))) == 2) { TextBox desBox = this.DESBox; desBox.Text = desBox.Text + Conversion.Hex(Strings.Asc(Strings.Mid(this.DES_file_string_bytes, this.DES_file_buffer_len, 1))); } else { TextBox desBox = this.DESBox; desBox.Text = desBox.Text + "0" + Conversion.Hex(Strings.Asc(Strings.Mid(this.DES_file_string_bytes, this.DES_file_buffer_len, 1))); } try { FileSystem.FileClose(new int[1] { this.DES_file_number }); } catch (Exception ex) { ProjectData.SetProjectError(ex); int num5 = (int) Interaction.MsgBox((object) ("Unable to close DES encoded output file " + this.DES_file_name), MsgBoxStyle.OkOnly, (object) null); ProjectData.ClearProjectError(); } } catch (Exception ex1) { ProjectData.SetProjectError(ex1); int num3 = (int) Interaction.MsgBox((object) ("Error reading password file " + this.DES_file_name), MsgBoxStyle.OkOnly, (object) null); try { FileSystem.FileClose(new int[1] { this.DES_file_number }); } catch (Exception ex2) { ProjectData.SetProjectError(ex2); int num4 = (int) Interaction.MsgBox((object) ("Unable to close DES encoded password file " + this.DES_file_name), MsgBoxStyle.OkOnly, (object) null); ProjectData.ClearProjectError(); } ProjectData.ClearProjectError(); } if (this.SaveSeedCheckBox.Checked) return; try { FileSystem.Kill(this.DES_file_name); } catch (Exception ex) { ProjectData.SetProjectError(ex); ProjectData.ClearProjectError(); } }