/// <summary> /// AES加密算法 /// </summary> /// <param name="plainText">明文字符串</param> /// <param name="key">密钥</param> /// <returns>返回加密后的密文</returns> internal static string Encrypt(string plainText, string key) { //分组加密算法 SymmetricAlgorithm des = Rijndael.Create(); byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字节数组 //设置密钥及密钥向量 des.Key = ConvertKey(key); des.IV = DefaultKey; using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); byte[] cipherBytes = ms.ToArray();//得到加密后的字节数组 var output = Convert.ToBase64String(cipherBytes); cipherBytes = null; return(output); } } }
public SimpleAES(string password) { _rijndael = Rijndael.Create(); _rijndael.Padding = PaddingMode.Zeros; Rfc2898DeriveBytes pdb = null; try { pdb = new Rfc2898DeriveBytes(password, SALT); _rijndael.Key = pdb.GetBytes(32); _rijndael.IV = pdb.GetBytes(16); } finally { IDisposable disp = pdb as IDisposable; if (disp != null) { disp.Dispose(); } } }
// Encrypt a byte array into a byte array using a key and an IV public static byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV) { // Create a MemoryStream that is going to accept the encrypted bytes MemoryStream ms = new MemoryStream(); // Create a symmetric algorithm. // We are going to use Rijndael because it is strong and available on all platforms. // You can use other algorithms, to do so substitute the next line with something like // TripleDES alg = TripleDES.Create(); Rijndael alg = Rijndael.Create(); // Now set the key and the IV. // We need the IV (Initialization Vector) because the algorithm is operating in its default // mode called CBC (Cipher Block Chaining). The IV is XORed with the first block (8 byte) // of the data before it is encrypted, and then each encrypted block is XORed with the // following block of plaintext. This is done to make encryption more secure. // There is also a mode called ECB which does not need an IV, but it is much less secure. alg.Key = Key; alg.IV = IV; // Create a CryptoStream through which we are going to be pumping 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. CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write); // Write the data and make it do the encryption cs.Write(clearData, 0, clearData.Length); // Close the crypto stream (or do FlushFinalBlock). // This will tell it that we have done our encryption and there is no more data coming in, // and it is now a good time to apply the padding and finalize the encryption process. cs.Close(); // Now get the encrypted data from the MemoryStream. // Some people make a mistake of using GetBuffer() here, which is not the right way. byte[] encryptedData = ms.ToArray(); return(encryptedData); }
// Decrypt a file into another file using a password public static void Decrypt(string fileIn, string fileOut, string Password) { // First we are going to open the file streams FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read); FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write); // Then we are going to derive a Key and an IV from the Password and create an algorithm PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); Rijndael alg = Rijndael.Create(); alg.Key = pdb.GetBytes(32); alg.IV = pdb.GetBytes(16); // Now create a crypto stream through which we are going to be pumping data. // Our fileOut is going to be receiving the Decrypted bytes. CryptoStream cs = new CryptoStream(fsOut, alg.CreateDecryptor(), CryptoStreamMode.Write); // Now will will initialize a buffer and will be processing the input file in chunks. // This is done to avoid reading the whole file (which can be huge) into memory. int bufferLen = 4096; byte[] buffer = new byte[bufferLen]; int bytesRead; do { // read a chunk of data from the input file bytesRead = fsIn.Read(buffer, 0, bufferLen); // Decrypt it cs.Write(buffer, 0, bytesRead); } while (bytesRead != 0); // close everything cs.Close(); // this will also close the unrelying fsOut stream fsIn.Close(); }
/// <summary> /// AES解密 /// </summary> /// <param name="cipherText">密文字节数组</param> /// <param name="strKey">密钥:16位</param> /// <returns>返回解密后的字符串</returns> public static byte[] AESDecryptToBytes(byte[] cipherText, string strKey) { //默认密钥向量 byte[] _key1 = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; try { SymmetricAlgorithm des = Rijndael.Create(); des.Key = Encoding.UTF8.GetBytes(strKey); des.IV = _key1; byte[] decryptBytes = new byte[cipherText.Length]; MemoryStream ms = new MemoryStream(cipherText); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read); cs.Read(decryptBytes, 0, decryptBytes.Length); cs.Close(); ms.Close(); return(decryptBytes); } catch { return(null); } }
/// <summary> /// AES算法解密 /// </summary> /// <param name="cipherText">需要解密的Base64字符串</param> /// <param name="key">密匙</param> /// <param name="iv">向量</param> /// <returns>解密后的字符串</returns> /// <remarks>如果解密的字符串不是Base64编码格式,会报错.</remarks> /// <exception cref="System.ArgumentNullException">参数为空时,导致异常.</exception> public static string AesDecrypt(this string cipherText, string key, string iv) { // Check arguments. if (cipherText == null || cipherText.Length == 0) { throw new ArgumentNullException("cipherText"); } if (key == null || key.Length < 1) { throw new ArgumentNullException("Key"); } if (iv == null || iv.Length < 1) { throw new ArgumentNullException("iv"); } // Create an Rijndael object with the specified key and IV. using (Rijndael rijAlg = Rijndael.Create()) { rijAlg.Key = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(key)); rijAlg.IV = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(iv)); // Create expression decrytor to perform the stream transform. ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); // Create the streams used for decryption. using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText))) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt, Encoding.UTF8)) { // Read the decrypted bytes from the decrypting stream and place them in expression string. return(srDecrypt.ReadToEnd()); } } } } }
public static string EncryptText(string plainText) { var iv = Encoding.UTF8.GetBytes(AES_IV); var key = Encoding.UTF8.GetBytes(AES_KEY); var plainBytes = Encoding.UTF8.GetBytes(plainText); var rijndael = Rijndael.Create(); var encryptor = rijndael.CreateEncryptor(key, iv); var memoryStream = new MemoryStream(plainBytes.Length); var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write); cryptoStream.Write(plainBytes, 0, plainBytes.Length); cryptoStream.FlushFinalBlock(); var cipherBytes = memoryStream.ToArray(); memoryStream.Close(); cryptoStream.Close(); return(Convert.ToBase64String(cipherBytes)); }
/// <summary> /// Encrypt a given string using the given key. The cipherText is Base64 /// encoded and returned. The algorithjm currently used is "Rijndael" /// </summary> /// <param name="clearString">The string to encrypt.</param> /// <param name="keyBytes">The key for the encryption algorithm</param> /// <returns>The Base64 encoded cipher text</returns> public static String EncryptString(String clearString, byte[] keyBytes) { MemoryStream ms = new MemoryStream(); //DES alg = DES.Create(); //RC2 alg = RC2.Create(); Rijndael alg = Rijndael.Create(); alg.Key = keyBytes; alg.IV = GetSalt(); byte[] clearBytes = Encoding.Unicode.GetBytes(clearString); CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(clearBytes, 0, clearBytes.Length); cs.Close(); byte[] cipherText = ms.ToArray(); return(Convert.ToBase64String(cipherText)); }
/// <summary> /// AES解密 /// </summary> /// <param name="encryptStr">密文字符串</param> /// <param name="key"></param> /// <param name="iv"></param> /// <returns>明文</returns> public static string AESDecrypt(string encryptStr, string key, string iv) { byte[] rgbKey = Encoding.UTF8.GetBytes(key); byte[] rgbIv = Encoding.UTF8.GetBytes(iv); encryptStr = encryptStr.Replace(" ", "+"); byte[] byteArray = Convert.FromBase64String(encryptStr); string decrypt = null; using (Rijndael aes = Rijndael.Create()) { using (MemoryStream mStream = new MemoryStream()) { using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(rgbKey, rgbIv), CryptoStreamMode.Write)) { cStream.Write(byteArray, 0, byteArray.Length); cStream.FlushFinalBlock(); decrypt = Encoding.UTF8.GetString(mStream.ToArray()); } } aes.Clear(); } return(decrypt); }
private byte[] AES_Encode(string EncodeStr) { //AES string strKey = "imnateimhandsome"; byte[] _key1 = { 0x22, 0x35, 0x59, 0x78, 0x70, 0xAC, 0xC0, 0xFF, 0x22, 0x35, 0x59, 0x78, 0x70, 0xAB, 0xC0, 0xFF }; SymmetricAlgorithm des = Rijndael.Create(); byte[] inputByteArray = Encoding.UTF8.GetBytes(EncodeStr);//得到需加密字串byte型態 des.Key = Encoding.UTF8.GetBytes(strKey); des.IV = _key1; MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); byte[] result = ms.ToArray();//加密完 cs.Close(); ms.Close(); return(result); }
/// <summary> /// AES解密 /// </summary> /// <param name="value">待加密字段</param> /// <param name="keyVal">密钥值</param> /// <param name="ivVal">加密辅助向量</param> /// <returns></returns> public static string UnAesStr(this string value, string keyVal, string ivVal) { var encoding = Encoding.UTF8; byte[] btKey = keyVal.FormatByte(encoding); byte[] btIv = ivVal.FormatByte(encoding); byte[] byteArray = Convert.FromBase64String(value); string decrypt; Rijndael aes = Rijndael.Create(); using (MemoryStream mStream = new MemoryStream()) { using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(btKey, btIv), CryptoStreamMode.Write)) { cStream.Write(byteArray, 0, byteArray.Length); cStream.FlushFinalBlock(); decrypt = encoding.GetString(mStream.ToArray()); } } aes.Clear(); return(decrypt); }
public string Decrypt(string key, string data) { Rijndael r = Rijndael.Create(); byte[] keyBytes = Encoding.ASCII.GetBytes(key); byte[] dataBytes = Convert.FromBase64String(data); r.Key = keyBytes; r.IV = keyBytes; byte[] decryptedData; using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream( ms, r.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(dataBytes, 0, dataBytes.Length); } decryptedData = ms.ToArray(); } return(Encoding.ASCII.GetString(decryptedData)); }
/// AES加密 /// </summary> /// <param name="inputdata">输入的数据</param> /// <param name="iv">向量128位</param> /// <param name="strKey">加密密钥</param> /// <returns></returns> public static byte[] AESEncrypt(byte[] inputdata, byte[] iv, byte[] key) { //分组加密算法 SymmetricAlgorithm des = Rijndael.Create(); byte[] inputByteArray = inputdata; //得到需要加密的字节数组 //设置密钥及密钥向量 des.Key = key; //Encoding.UTF8.GetBytes(strKey.Substring(0, 32)); des.IV = iv; using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); byte[] cipherBytes = ms.ToArray();//得到加密后的字节数组 cs.Close(); ms.Close(); return(cipherBytes); } } }
/// <summary> /// 加密 参数:byte[] /// </summary> /// <param name="palinData">明文</param> /// <param name="key">密钥</param> /// <param name="iv">向量</param> /// <returns>byte[]:密文</returns> public static byte[] Encrypt(byte[] palinData, string key, string iv = "") { if (palinData == null) { return(null); } if (!(CheckKey(key) && CheckIv(iv))) { return(palinData); } byte[] bKey = new byte[32]; Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(bKey.Length)), bKey, bKey.Length); byte[] bVector = new byte[16]; if (!string.IsNullOrWhiteSpace(iv)) { Array.Copy(Encoding.UTF8.GetBytes(iv.PadRight(bVector.Length)), bVector, bVector.Length); } else { Array.Copy(Encoding.UTF8.GetBytes(key.Substring(0, 16).PadRight(bVector.Length)), bVector, bVector.Length); } byte[] cryptograph = null; // 加密后的密文 Rijndael Aes = Rijndael.Create(); // 开辟一块内存流 using (MemoryStream Memory = new MemoryStream()) { // 把内存流对象包装成加密流对象 using (CryptoStream Encryptor = new CryptoStream(Memory, Aes.CreateEncryptor(bKey, bVector), CryptoStreamMode.Write)) { // 明文数据写入加密流 Encryptor.Write(palinData, 0, palinData.Length); Encryptor.FlushFinalBlock(); cryptograph = Memory.ToArray(); } } return(cryptograph); }
public static string GetV(string data, int keyno, bool reverse) { var hasher = Rijndael.Create(); hasher.Key = keyno == 1 ? GetSK1(false) : GetSK2(false); hasher.IV = new byte[hasher.BlockSize >> 3]; string result; if (reverse) { using (var ms = new MemoryStream()) using (var ss = new CryptoStream(ms, hasher.CreateEncryptor(), CryptoStreamMode.Write)) { var buffer = Encoding.Unicode.GetBytes(data); ss.Write(buffer, 0, buffer.Length); ss.FlushFinalBlock(); hasher.Clear(); result = Convert.ToBase64String(ms.ToArray()); } } else { var bytes = Convert.FromBase64String(data); using (var ms = new MemoryStream(bytes)) using (var ss = new CryptoStream(ms, hasher.CreateDecryptor(), CryptoStreamMode.Read)) { var buffer = new byte[bytes.Length]; var size = ss.Read(buffer, 0, buffer.Length); hasher.Clear(); var newBuffer = new byte[size]; Array.Copy(buffer, newBuffer, size); result = Encoding.Unicode.GetString(newBuffer); } } return(result); }
public static SymmetricAlgorithm CreateSymAlgorithm(SymAlgorithms saAlgo) { SymmetricAlgorithm saReturn; switch (saAlgo) { case SymAlgorithms.AES128: saReturn = Rijndael.Create(); saReturn.BlockSize = 128; saReturn.KeySize = 128; break; case SymAlgorithms.AES192: saReturn = Rijndael.Create(); saReturn.BlockSize = 128; saReturn.KeySize = 192; break; case SymAlgorithms.AES256: saReturn = Rijndael.Create(); saReturn.BlockSize = 128; saReturn.KeySize = 256; break; case SymAlgorithms.CAST5: saReturn = CAST5.Create(); break; case SymAlgorithms.Triple_DES: saReturn = TripleDES.Create(); break; default: throw new System.Security.Cryptography.CryptographicException("The algorithm is not supported!"); } return(saReturn); }
/// <summary> /// AES 解密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法) /// </summary> /// <param name="DecryptString">待解密密文</param> /// <param name="DecryptKey">解密密钥</param> /// <returns></returns> public static byte[] AESDecrypt(byte[] DecryptedData, string DecryptKey) { if (DecryptedData == null || DecryptedData.Length <= 0) { throw (new Exception("密文不得为空")); } if (string.IsNullOrEmpty(DecryptKey)) { throw (new Exception("密钥不得为空")); } byte[] plainBytes = Encoding.Default.GetBytes(DecryptKey); Byte[] bKey = new Byte[16]; Array.Copy(Encoding.Default.GetBytes(DecryptKey.PadRight(bKey.Length)), bKey, bKey.Length); string m_strDecrypt = string.Empty; byte[] m_btIV = Convert.FromBase64String(strIv); Rijndael m_AESProvider = Rijndael.Create(); try { byte[] m_btDecryptString = Convert.FromBase64String(Convert.ToBase64String(DecryptedData)); MemoryStream m_stream = new MemoryStream(); CryptoStream m_csstream = new CryptoStream(m_stream, m_AESProvider.CreateDecryptor(bKey, m_btIV), CryptoStreamMode.Write); m_csstream.Write(m_btDecryptString, 0, m_btDecryptString.Length); m_csstream.FlushFinalBlock(); m_strDecrypt = Encoding.Default.GetString(m_stream.ToArray()); m_stream.Close(); m_stream.Dispose(); m_csstream.Close(); m_csstream.Dispose(); } catch (IOException ex) { throw ex; } catch (CryptographicException ex) { throw ex; } catch (ArgumentException ex) { throw ex; } catch (Exception ex) { throw ex; } finally { m_AESProvider.Clear(); } return(Convert.FromBase64String(m_strDecrypt)); }
/// <summary> /// 将一个流解密为内存流。 /// </summary> /// <param name="stream">一个可读取的流。</param> /// <param name="key">key。</param> /// <param name="vector">vector。</param> /// <returns>返回解密后的数据。</returns> public static System.IO.MemoryStream Decrypt(System.IO.Stream stream, string key, string vector) { byte[] bKey = new byte[32]; Array.Copy(System.Text.Encoding.UTF8.GetBytes(key.PadRight(bKey.Length)), bKey, bKey.Length); byte[] bVector = new byte[16]; Array.Copy(System.Text.Encoding.UTF8.GetBytes(vector.PadRight(bVector.Length)), bVector, bVector.Length); CryptoStream cryptoStream = null; System.IO.MemoryStream memoryResult = null; Rijndael rijndaelAES = Rijndael.Create(); try { cryptoStream = new CryptoStream(stream, rijndaelAES.CreateDecryptor(bKey, bVector), CryptoStreamMode.Read); memoryResult = new System.IO.MemoryStream(); byte[] buffer = new byte[1024]; int readBytes = 0; while ((readBytes = cryptoStream.Read(buffer, 0, buffer.Length)) > 0) { memoryResult.Write(buffer, 0, readBytes); } memoryResult.Position = 0; } catch { throw; } finally { if (cryptoStream != null) { cryptoStream.Close(); cryptoStream.Dispose(); cryptoStream = null; } } return(memoryResult); }
/// <summary> /// AES解密 /// </summary> /// <param name="str">密文</param> /// <returns>返回解密后的字符串</returns> public static string AESDecrypt(string str) { if (string.IsNullOrWhiteSpace(str)) { return(string.Empty); } string strResult = string.Empty; try { byte[] data = new byte[(str.Length) / 2]; for (int i = 0; i < data.Length; i++) { data[i] = (byte)( "0123456789abcdef".IndexOf(str[i * 2]) * 16 + "0123456789abcdef".IndexOf(str[i * 2 + 1]) ); } SymmetricAlgorithm des = Rijndael.Create(); des.Key = Encoding.UTF8.GetBytes(keys); des.IV = _key1; byte[] decryptBytes = new byte[data.Length]; MemoryStream ms = new MemoryStream(data); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read); StreamReader streamReader = new StreamReader(cs); strResult = streamReader.ReadToEnd(); //cs.Read(decryptBytes, 0, decryptBytes.Length); cs.Close(); ms.Close(); } catch { return(string.Empty); } return(strResult); }
public void DecryptIfNeeded(X509Certificate2 spCert) { if (spCert == null) { throw new ArgumentNullException(nameof(spCert)); } var responseNode = SelectSingleNode("/samlp:Response"); var encryptedAssertionNode = SelectSingleNode("/samlp:Response/saml:EncryptedAssertion"); if (encryptedAssertionNode != null) { var encryptedDataNode = SelectSingleNode("/samlp:Response/saml:EncryptedAssertion/xenc:EncryptedData"); var encryptionMethodAlgorithm = SelectSingleNode("/samlp:Response/saml:EncryptedAssertion/xenc:EncryptedData/xenc:EncryptionMethod")?.Attributes["Algorithm"]?.Value; var encryptionMethodKeyAlgorithm = SelectSingleNode("/samlp:Response/saml:EncryptedAssertion/xenc:EncryptedData/ds:KeyInfo/e:EncryptedKey/e:EncryptionMethod")?.Attributes["Algorithm"]?.Value; var cypherText = SelectSingleNode("/samlp:Response/saml:EncryptedAssertion/xenc:EncryptedData/ds:KeyInfo/e:EncryptedKey/e:CipherData/e:CipherValue")?.InnerText; var key = Rijndael.Create(encryptionMethodAlgorithm); key.Key = EncryptedXml.DecryptKey( Convert.FromBase64String(cypherText), (RSA)spCert.PrivateKey, useOAEP: encryptionMethodKeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl ); var encryptedXml = new EncryptedXml(); var encryptedData = new EncryptedData(); encryptedData.LoadXml((XmlElement)encryptedDataNode); var plaintext = encryptedXml.DecryptData(encryptedData, key); var xmlString = Encoding.UTF8.GetString(plaintext); var tempDoc = new XmlDocument(); tempDoc.LoadXml(xmlString); var importNode = responseNode.OwnerDocument.ImportNode(tempDoc.DocumentElement, true); responseNode.ReplaceChild(importNode, encryptedAssertionNode); } }
public CryptedMoggStream(Stream stream) { Base = stream; EndianReader reader = new EndianReader(Base, Endianness.LittleEndian); ReadBuffer = new byte[Util.AesKeySize]; KeyBuffer = new byte[Util.AesKeySize]; Buffer = new byte[Util.AesKeySize]; Crypt = Rijndael.Create(); Crypt.Padding = PaddingMode.None; Crypt.Mode = CipherMode.ECB; // MOGG Key: Crypt.Key = new byte[] { 0x37, 0xB2, 0xE2, 0xB9, 0x1C, 0x74, 0xFA, 0x9E, 0x38, 0x81, 0x08, 0xEA, 0x36, 0x23, 0xDB, 0xE4 }; Decryptor = Crypt.CreateEncryptor(); Offset = 1; if (Base.Length >= 8) { int magic = reader.ReadInt32(); if (magic == 0x0B || magic == 0x0A) { HeaderSize = reader.ReadUInt32(); // HeaderSize Size = Base.Length - HeaderSize; Encrypted = magic == 0x0B; Position = 0; } else { throw new FormatException(); } } else { HeaderSize = 0; Size = Base.Length; } }
public void Save(Stream stream) { var writer = new BinaryWriter(stream); // Write the file magic and version. writer.Write(referenceFileMagic); // The encryption system doesn't handle short passwords gracefully, so extend them to 16 characters with spaces. password = password.PadRight(16, ' '); // Hash the password and save the hash to the file unencrypted. byte[] passwordASCII = ASCIIEncoding.ASCII.GetBytes(password); byte[] passwordHash = (new SHA512Managed()).ComputeHash(passwordASCII); writer.Write(passwordHash); // Choose a random initialization vector. byte[] initializationVector = new byte[16]; RandomNumberGenerator.Create().GetBytes(initializationVector); // Write the initialization vector. writer.Write(initializationVector); // Create an encrypting stream to write the un-encrypted data to the file. writer = new BinaryWriter( new CryptoStream( stream, Rijndael.Create().CreateEncryptor( passwordASCII, initializationVector), CryptoStreamMode.Write)); // Write the SNP IDs and values to the file. foreach (var pair in snpToGenotypeMap) { writer.Write(pair.Key); pair.Value.Write(writer); } }
//encrypt public static void Encrypt() { try { var path = AppDomain.CurrentDomain.BaseDirectory; //Create a new instance of the RijndaelManaged class // and encrypt the stream. RijndaelManaged RMCrypto = new RijndaelManaged(); byte[] Key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 }; byte[] IV = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 }; byte[] encrypted; byte[] raw; raw = ReadFromFile(@"" + path + "highscores.sav"); string edited = Encoding.ASCII.GetString(raw); using (Rijndael rijAlg = Rijndael.Create()) { // Create an encryptor to perform the stream transform. ICryptoTransform encryptor = rijAlg.CreateEncryptor(Key, IV); // Create the streams used for encryption. using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { //Write to the stream. swEncrypt.Write(edited); } encrypted = msEncrypt.ToArray(); } } } WriteToFile(@"" + path + "highscores.sav", encrypted); } catch (Exception) { } }
/// <summary> /// AES解密(默认为CBC模式) /// </summary> /// <param name="inputdata">输入的数据</param> /// <param name="iv">向量</param> /// <param name="strKey">key</param> /// <returns></returns> public static byte[] AESDecrypt(byte[] inputdata, byte[] iv, string strKey) { #if NET35 || NET40 || NET45 SymmetricAlgorithm des = Rijndael.Create(); #else SymmetricAlgorithm des = Aes.Create(); #endif des.Key = Encoding.UTF8.GetBytes(strKey.PadRight(32)); des.IV = iv; byte[] decryptBytes = null;// new byte[inputdata.Length]; using (MemoryStream ms = new MemoryStream(inputdata)) { using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read)) { using (MemoryStream originalMemory = new MemoryStream()) { Byte[] Buffer = new Byte[1024]; Int32 readBytes = 0; while ((readBytes = cs.Read(Buffer, 0, Buffer.Length)) > 0) { originalMemory.Write(Buffer, 0, readBytes); } decryptBytes = originalMemory.ToArray(); #region 废弃的方法 //cs.Read(decryptBytes, 0, decryptBytes.Length); ////cs.Close(); ////ms.Close(); #endregion } } } return(decryptBytes); }
/// <summary> /// ���� ������byte[] /// </summary> /// <param name="encryptedData">�����ܵ�����</param> /// <param name="key">��Կ</param> /// <param name="iv">����</param> /// <returns>����</returns> public static byte[] Decrypt(byte[] encryptedData, string key, string iv) { if (encryptedData == null) { return(null); } if (!(CheckKey(key) && CheckIv(iv))) { return(encryptedData); } byte[] bKey = new byte[32]; System.Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(bKey.Length)), bKey, bKey.Length); byte[] bVector = new byte[16]; System.Array.Copy(Encoding.UTF8.GetBytes(iv.PadRight(bVector.Length)), bVector, bVector.Length); byte[] original = null; // ���ܺ������ Rijndael Aes = Rijndael.Create(); // ����һ���ڴ������洢���� using (MemoryStream Memory = new MemoryStream(encryptedData)) { // ���ڴ��������װ�ɼ��������� using (CryptoStream Decryptor = new CryptoStream(Memory, Aes.CreateDecryptor(bKey, bVector), CryptoStreamMode.Read)) { // ���Ĵ洢�� using (MemoryStream originalMemory = new MemoryStream()) { byte[] Buffer = new byte[1024]; int readBytes = 0; while ((readBytes = Decryptor.Read(Buffer, 0, Buffer.Length)) > 0) { originalMemory.Write(Buffer, 0, readBytes); } original = originalMemory.ToArray(); } } } return(original); }
///<summary>Encrypts signature text and returns a base 64 string so that it can go directly into the database.</summary> public string GetSigString() { if (pointList.Count == 0) { return(""); } string rawString = ""; for (int i = 0; i < pointList.Count; i++) { if (i > 0) { rawString += ";"; } rawString += pointList[i].X.ToString() + "," + pointList[i].Y.ToString(); } byte[] sigBytes = Encoding.UTF8.GetBytes(rawString); MemoryStream ms = new MemoryStream(); //Compression could have been done here, using DeflateStream //A decision was made not to use compression because it would have taken more time and not saved much space. //DeflateStream compressedzipStream = new DeflateStream(ms , CompressionMode.Compress, true); //Now, we have the compressed bytes. Need to encrypt them. Rijndael crypt = Rijndael.Create(); crypt.KeySize = 128; //16 bytes; Because this is 128 bits, it is the same as AES. crypt.Key = hash; crypt.IV = new byte[16]; CryptoStream cs = new CryptoStream(ms, crypt.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(sigBytes, 0, sigBytes.Length); cs.FlushFinalBlock(); byte[] encryptedBytes = new byte[ms.Length]; ms.Position = 0; ms.Read(encryptedBytes, 0, (int)ms.Length); cs.Dispose(); ms.Dispose(); return(Convert.ToBase64String(encryptedBytes)); }
/// <summary> /// Encrypts the value <paramref name="toEncrypt"/> using the <paramref name="password"/>. /// </summary> /// <param name="password">The password.</param> /// <param name="toEncrypt">The value to encrypt.</param> /// <returns>Encrypted value</returns> public static string Encrypt(string password, string toEncrypt) { Rijndael rinedal = null; byte[] toEncBytes = null; try { toEncBytes = Encoding.Default.GetBytes(toEncrypt); Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(password, GenerateSalt(password)); rinedal = Rijndael.Create(); rinedal.Padding = PaddingMode.ISO10126; // our key ICryptoTransform tx = rinedal.CreateEncryptor(pdb.GetBytes(32), pdb.GetBytes(16)); // our IV byte[] encrypted = tx.TransformFinalBlock(toEncBytes, 0, toEncBytes.Length); return(Convert.ToBase64String(encrypted)); } finally { // this clears out any secret data if (rinedal != null) { rinedal.Clear(); } // zeroes out our array if (toEncBytes != null) { for (int i = 0; i <= toEncBytes.Length - 1; i++) { toEncBytes[i] = 0; } } } }
/// <summary> /// Unscrabbles the specified a byte array. /// </summary> /// <param name="aByteArray">A byte array.</param> /// <param name="aKey">A key.</param> /// <param name="aIV">A IV.</param> /// <returns></returns> public static string Fixit(byte[] aByteArray, byte[] aKey, byte[] aIV) { if (aByteArray == null || aByteArray.Length <= 0) { throw new ArgumentNullException("aByteArray"); } if (aKey == null || aKey.Length <= 0) { throw new ArgumentNullException("aKey"); } if (aIV == null || aIV.Length <= 0) { throw new ArgumentNullException("aIV"); } string _fixed = null; using (var vRijndael = Rijndael.Create()) { vRijndael.Key = aKey; vRijndael.IV = aIV; using (var vICryptoTransform = vRijndael.CreateDecryptor(vRijndael.Key, vRijndael.IV)) { using (var vMemoryStream = new MemoryStream(aByteArray)) { using (var vCryptoStream = new CryptoStream(vMemoryStream, vICryptoTransform, CryptoStreamMode.Read)) { using (var vStreamReader = new StreamReader(vCryptoStream)) { _fixed = vStreamReader.ReadToEnd(); } } } } } return(_fixed); }
/// <summary> /// AES加密 /// </summary> /// <param name="Data">被加密的明文</param> /// <param name="Key">密钥</param> /// <param name="Vector">向量</param> /// <returns>密文</returns> public static String AESEncrypt(String Data, String Key, String Vector) { Byte[] plainBytes = Encoding.UTF8.GetBytes(Data); Byte[] bKey = new Byte[32]; Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length); Byte[] bVector = new Byte[16]; Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length); Byte[] Cryptograph = null; // 加密后的密文 Rijndael Aes = Rijndael.Create(); try { // 开辟一块内存流 using (MemoryStream Memory = new MemoryStream()) { // 把内存流对象包装成加密流对象 using (CryptoStream Encryptor = new CryptoStream(Memory, Aes.CreateEncryptor(bKey, bVector), CryptoStreamMode.Write)) { // 明文数据写入加密流 Encryptor.Write(plainBytes, 0, plainBytes.Length); Encryptor.FlushFinalBlock(); Cryptograph = Memory.ToArray(); } } } catch { Cryptograph = null; } return(Convert.ToBase64String(Cryptograph)); }
public static void Encrypt(string fileIn, string fileOut, string Password) { FileStream fileStream1 = new FileStream(fileIn, FileMode.Open, FileAccess.Read); FileStream fileStream2 = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write); PasswordDeriveBytes passwordDeriveBytes = new PasswordDeriveBytes(Password, new byte[13] { (byte)73, (byte)118, (byte)97, (byte)110, (byte)32, (byte)77, (byte)101, (byte)100, (byte)118, (byte)101, (byte)100, (byte)101, (byte)118 }); Rijndael rijndael = Rijndael.Create(); rijndael.Key = passwordDeriveBytes.GetBytes(32); rijndael.IV = passwordDeriveBytes.GetBytes(16); CryptoStream cryptoStream = new CryptoStream((Stream)fileStream2, rijndael.CreateEncryptor(), CryptoStreamMode.Write); int count1 = 4096; byte[] buffer = new byte[count1]; int count2; do { count2 = fileStream1.Read(buffer, 0, count1); cryptoStream.Write(buffer, 0, count2); }while (count2 != 0); cryptoStream.Close(); fileStream1.Close(); }