/// <summary> /// AES 加密 /// </summary> /// <param name="str">要加密的内容</param> /// <param name="key">两种方式</param> /// <returns></returns> public static string AesEncrypt(string str, string key) { if (string.IsNullOrEmpty(str)) { return(null); } Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str); //方法一:只使用key加密 //System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged //{ // Key = Encoding.UTF8.GetBytes(key), // Mode = System.Security.Cryptography.CipherMode.CBC,//Mode = System.Security.Cryptography.CipherMode.ECB, // Padding = System.Security.Cryptography.PaddingMode.PKCS7 //}; //System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor(); //Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); //return Convert.ToBase64String(resultArray, 0, resultArray.Length); //方法二:使用key和向量IV加密 using (RijndaelManaged rm = new RijndaelManaged()) { System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor(rgbKey, rgbIv); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return(Convert.ToBase64String(resultArray, 0, resultArray.Length)); } }
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", "")); }
internal System.IO.Stream Decrypt(System.IO.Stream inStream) { if (!IsCryptoReady) { throw new InvalidOperationException("Diffie Hellman Key Exchange not finished."); } System.IO.MemoryStream memStream = new System.IO.MemoryStream(); byte[] bytes = new byte[1024]; int bytesRead = 0; do { bytesRead = inStream.Read(bytes, 0, 1024); memStream.Write(bytes, 0, bytesRead); } while (bytesRead > 0); memStream.Seek(0, System.IO.SeekOrigin.Begin); System.IO.MemoryStream outStream = new System.IO.MemoryStream(); System.Security.Cryptography.ICryptoTransform xfrm = aes.CreateDecryptor(); System.Security.Cryptography.CryptoStream stream = new CryptoStream(outStream, xfrm, CryptoStreamMode.Write); int len = 0; while (len < memStream.Length) { int n = memStream.Read(bytes, 0, 1024); stream.Write(bytes, 0, n); len += n; } stream.Flush(); outStream.Seek(0, System.IO.SeekOrigin.Begin); return(outStream); }
/// <summary> /// AES解密,与JAVA通用 /// </summary> /// <param name="str"></param> /// <param name="key"></param> /// <returns></returns> public static string AesDecrypt(string str, string key) { if (string.IsNullOrEmpty(str)) { return(""); } try { Byte[] toEncryptArray = Convert.FromBase64String(str); System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged { Key = Encoding.UTF8.GetBytes(key), Mode = System.Security.Cryptography.CipherMode.ECB, Padding = System.Security.Cryptography.PaddingMode.PKCS7 }; System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return(Encoding.UTF8.GetString(resultArray)); } catch (Exception e) { Log.Error(e.Message); return(""); } }
/// <summary> /// AES 加密 /// </summary> /// <param name="encryptKey"></param> /// <param name="bizContent"></param> /// <param name="charset"></param> /// <returns></returns> public static string AesEncrypt(string encryptKey, string bizContent, string charset) { Byte[] keyArray = Convert.FromBase64String(encryptKey); Byte[] toEncryptArray = null; if (string.IsNullOrEmpty(charset)) { toEncryptArray = Encoding.UTF8.GetBytes(bizContent); } else { toEncryptArray = Encoding.GetEncoding(charset).GetBytes(bizContent); } System.Security.Cryptography.RijndaelManaged rDel = new System.Security.Cryptography.RijndaelManaged(); rDel.Key = keyArray; rDel.Mode = System.Security.Cryptography.CipherMode.CBC; rDel.Padding = System.Security.Cryptography.PaddingMode.PKCS7; rDel.IV = AES_IV; System.Security.Cryptography.ICryptoTransform cTransform = rDel.CreateEncryptor(rDel.Key, rDel.IV); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return(Convert.ToBase64String(resultArray)); }
public static string Decrypt(string cipherText) { //Get the plain text in a byte array System.Byte[] ByteText = System.Convert.FromBase64String(cipherText); System.IO.MemoryStream EncStream = new System.IO.MemoryStream(ByteText, 0, ByteText.Length); //Get the binary format of the hash key System.Byte[] HashKey = Crypter.FormatKey(Crypter.encrypKey); System.Byte[] IVector = Crypter.FormatInitializationVector(); Crypter.encryptionProvider.Key = HashKey; Crypter.encryptionProvider.IV = IVector; System.Security.Cryptography.ICryptoTransform Encrypter = Crypter.encryptionProvider.CreateDecryptor(); //Create a Stream for the transform System.Security.Cryptography.CryptoStream Stream = new System.Security.Cryptography.CryptoStream(EncStream, Encrypter, System.Security.Cryptography.CryptoStreamMode.Read); System.IO.StreamReader PlainText = null; try { PlainText = new System.IO.StreamReader(Stream); return(PlainText.ReadToEnd()); } finally { PlainText.Close(); Stream.Close(); } }
/// <summary> /// 解密 /// </summary> public static string AESDecrypt(string input) { byte[] encryptBytes = Convert.FromBase64String(input); byte[] salt = Encoding.UTF8.GetBytes(saltValue); System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged( ); System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(pwdValue, salt); aes.BlockSize = aes.LegalBlockSizes[0].MaxSize; aes.KeySize = aes.LegalKeySizes[0].MaxSize; aes.Key = rfc.GetBytes(aes.KeySize / 8); aes.IV = rfc.GetBytes(aes.BlockSize / 8); // 用当前的 Key 属性和初始化向量 IV 创建对称解密器对象 System.Security.Cryptography.ICryptoTransform decryptTransform = aes.CreateDecryptor( ); // 解密后的输出流 System.IO.MemoryStream decryptStream = new System.IO.MemoryStream( ); // 将解密后的目标流(decryptStream)与解密转换(decryptTransform)相连接 System.Security.Cryptography.CryptoStream decryptor = new System.Security.Cryptography.CryptoStream( decryptStream, decryptTransform, System.Security.Cryptography.CryptoStreamMode.Write); // 将一个字节序列写入当前 CryptoStream (完成解密的过程) decryptor.Write(encryptBytes, 0, encryptBytes.Length); decryptor.Close( ); // 将解密后所得到的流转换为字符串 byte[] decryptBytes = decryptStream.ToArray( ); string decryptedString = UTF8Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length); return(decryptedString); }
public string Encrypt(string Text) { string outText = string.Empty; System.Security.Cryptography.CryptoStream myCryptoStream = null; try { System.Byte[] bufferRead = System.Text.Encoding.ASCII.GetBytes(Text); System.IO.MemoryStream myOutMemStream = new System.IO.MemoryStream(1024); myrijManaged.Key = keyByte; myrijManaged.IV = IVByte; System.Security.Cryptography.ICryptoTransform myCryptoTransform = myrijManaged.CreateEncryptor(); myCryptoStream = new System.Security.Cryptography.CryptoStream(myOutMemStream, myCryptoTransform, System.Security.Cryptography.CryptoStreamMode.Write); myCryptoStream.Write(bufferRead, 0, bufferRead.Length); myCryptoStream.FlushFinalBlock(); System.Byte[] result = new byte[(int)myOutMemStream.Position]; myOutMemStream.Position = 0; myOutMemStream.Read(result, 0, result.Length); outText = System.Convert.ToBase64String(result); } catch (Exception exp) { throw exp; } finally { if (myCryptoStream != null) { myCryptoStream.Close(); } } return(outText); }
/// <summary> /// AES加密 /// </summary> /// <param name="encryptStr">明文</param> /// <param name="key">密钥</param> /// <returns></returns> public static string Encrypt() { //获取mac地址 string str = GetFirstMacAddress(); //获取下一天日期 string key = DateTime.Now.AddDays(1).ToString("yyyyMMdd"); //补全key为16个字符的字符串 for (int i = key.Length; i < 16; i++) { key += "0"; } if (string.IsNullOrEmpty(str)) { return(null); } Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str); //开始AES加密 System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged { Key = Encoding.UTF8.GetBytes(key), //密钥 Mode = System.Security.Cryptography.CipherMode.ECB, //加密模式 Padding = System.Security.Cryptography.PaddingMode.PKCS7 //填白模式,对于AES, C# 框架中的 PKCS #7等同与Java框架中 PKCS #5 }; //字节编码, 将有特等含义的字符串转化为字节流 System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor(); //加密 Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); //将加密后的字节流转化为字符串,以便网络传输与储存。 return(Convert.ToBase64String(resultArray, 0, resultArray.Length)); }
public static byte[] DecryptAES(byte[] input, string key) { System.Security.Cryptography.RijndaelManaged AES = new System.Security.Cryptography.RijndaelManaged(); System.Security.Cryptography.MD5CryptoServiceProvider Hash_AES = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] decrypted; try { byte[] hash = new byte[32]; byte[] temp = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(key)); Array.Copy(temp, 0, hash, 0, 16); Array.Copy(temp, 0, hash, 15, 16); AES.Key = hash; AES.Mode = System.Security.Cryptography.CipherMode.ECB; System.Security.Cryptography.ICryptoTransform DESDecrypter = AES.CreateDecryptor(); //byte[] Buffer = Convert.FromBase64String(input); //byte[] Buffer = Convert.for; //decrypted = System.Text.ASCIIEncoding.UTF8.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length)); decrypted = DESDecrypter.TransformFinalBlock(input, 0, input.Length); return(decrypted); } catch (Exception ex) { throw ex; } }
public static string AES_Encrypt(string input_text, string security_Code) { // ''' security_Code= [email protected] System.Security.Cryptography.RijndaelManaged AES = new System.Security.Cryptography.RijndaelManaged(); System.Security.Cryptography.MD5CryptoServiceProvider Hash_AES = new System.Security.Cryptography.MD5CryptoServiceProvider(); string encrypted = ""; try { byte[] hash = new byte[32]; byte[] temp = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(security_Code)); Array.Copy(temp, 0, hash, 0, 16); Array.Copy(temp, 0, hash, 15, 16); AES.Key = hash; AES.Mode = System.Security.Cryptography.CipherMode.ECB; //'Security.Cryptography.CipherMode.ECB System.Security.Cryptography.ICryptoTransform DESEncrypter = AES.CreateEncryptor(); byte[] Buffer = System.Text.ASCIIEncoding.ASCII.GetBytes(input_text); encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length)); } catch (Exception ex) { } return(encrypted); }
}//end method /// <summary> /// 3des解密字符6 /// </summary> /// <param name="a_strString">要解密的字符串</param> /// <param name="a_strKey">密钥</param> /// <returns>解密后的字符串</returns> /// <exception cref="">密钥错误</exception> /// <remarks>静态方法,采用默认utf8编码</remarks> public static string Decrypt3DES(this string a_strString, string a_strKey) { System.Security.Cryptography.TripleDESCryptoServiceProvider DES = new System.Security.Cryptography.TripleDESCryptoServiceProvider(); System.Security.Cryptography.MD5CryptoServiceProvider hashMD5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); DES.Key = hashMD5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(a_strKey)); DES.Mode = System.Security.Cryptography.CipherMode.ECB; System.Security.Cryptography.ICryptoTransform DESDecrypt = DES.CreateDecryptor(); string result = ""; try { byte[] Buffer = Convert.FromBase64String(a_strString); result = System.Text.Encoding.UTF8.GetString(DESDecrypt.TransformFinalBlock (Buffer, 0, Buffer.Length)); } catch (Exception e) { #if DEBUG Console.WriteLine("错误:{0}", e); #endif//DEBUG throw (new Exception("Invalid Key or input string is not a valid base64 string", e)); } return(result); }//end method
//Decryption Method public string DecryptTripleDES(string base64Text) { try { string Key = Convert.ToString(configuration.GetSection("appSettings").GetSection("EncryptKey").Value); byte[] Buffer = new byte[0]; System.Security.Cryptography.TripleDESCryptoServiceProvider DES = new System.Security.Cryptography.TripleDESCryptoServiceProvider(); System.Security.Cryptography.MD5CryptoServiceProvider hashMD5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); DES.Key = hashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(Key)); DES.Mode = System.Security.Cryptography.CipherMode.ECB; System.Security.Cryptography.ICryptoTransform DESDecrypt = DES.CreateDecryptor(); Buffer = Convert.FromBase64String(base64Text); string DecTripleDES = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length)); return(DecTripleDES); } catch (Exception) { return(string.Empty); } }
/// <summary> /// AES加密 /// </summary> /// <param name="text">加密字符</param> /// <param name="password">加密的密码</param> /// <param name="iv">密钥</param> /// <returns></returns> // 加密 /// <summary> /// AES 加密 /// </summary> /// <param name="str"></param> /// <param name="key"></param> /// <returns></returns> public static string AesEncrypt(string str, string key) { if (key == null) { return("Key為空null"); } // 判断Key是否为16位 if (key.Length != 16) { return("Key長度不是16位元"); } if (string.IsNullOrEmpty(str)) { return(null); } Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str); System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged { Key = Encoding.UTF8.GetBytes(key), Mode = System.Security.Cryptography.CipherMode.ECB, Padding = System.Security.Cryptography.PaddingMode.PKCS7 }; System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return(Convert.ToBase64String(resultArray, 0, resultArray.Length)); }
/// <summary> /// 加密 /// </summary> public static string AESEncrypt(string input) { byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(input); byte[] salt = System.Text.UTF8Encoding.UTF8.GetBytes(saltValue); // AesManaged - 高级加密标准(AES) 对称算法的管理类 System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged( ); // Rfc2898DeriveBytes - 通过使用基于 HMACSHA1 的伪随机数生成器,实现基于密码的密钥派生功能 (PBKDF2 - 一种基于密码的密钥派生函数) // 通过 密码 和 salt 派生密钥 System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(pwdValue, salt); aes.BlockSize = aes.LegalBlockSizes[0].MaxSize; aes.KeySize = aes.LegalKeySizes[0].MaxSize; aes.Key = rfc.GetBytes(aes.KeySize / 8); aes.IV = rfc.GetBytes(aes.BlockSize / 8); // 用当前的 Key 属性和初始化向量 IV 创建对称加密器对象 System.Security.Cryptography.ICryptoTransform encryptTransform = aes.CreateEncryptor( ); // 加密后的输出流 System.IO.MemoryStream encryptStream = new System.IO.MemoryStream( ); // 将加密后的目标流(encryptStream)与加密转换(encryptTransform)相连接 System.Security.Cryptography.CryptoStream encryptor = new System.Security.Cryptography.CryptoStream (encryptStream, encryptTransform, System.Security.Cryptography.CryptoStreamMode.Write); // 将一个字节序列写入当前 CryptoStream (完成加密的过程) encryptor.Write(data, 0, data.Length); encryptor.Close( ); // 将加密后所得到的流转换成字节数组,再用Base64编码将其转换为字符串 string encryptedString = Convert.ToBase64String(encryptStream.ToArray( )); return(encryptedString); }
public string Decrypt(string CypherText) { string outText = string.Empty; System.Security.Cryptography.CryptoStream myCryptoStream = null; try { System.Byte[] data = System.Convert.FromBase64String(CypherText); System.IO.MemoryStream memStream = new System.IO.MemoryStream(data.Length); myrijManaged.Key = keyByte; myrijManaged.IV = IVByte; System.Security.Cryptography.ICryptoTransform myCryptoTransform = myrijManaged.CreateDecryptor(); myCryptoStream = new System.Security.Cryptography.CryptoStream(memStream, myCryptoTransform, System.Security.Cryptography.CryptoStreamMode.Read); memStream.Write(data, 0, data.Length); memStream.Position = 0; outText = new System.IO.StreamReader(myCryptoStream).ReadToEnd(); } catch (Exception exp) { throw exp; } finally { if (myCryptoStream != null) { myCryptoStream.Close(); } } return(outText); }
private static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV) { byte[] encrypted; // Create an Aes object // with the specified key and IV. using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create()) { aesAlg.Key = Key; aesAlg.IV = IV; // Create a decrytor to perform the stream transform. System.Security.Cryptography.ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for encryption. using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream()) { using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream( msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write)) { using (System.IO.StreamWriter swEncrypt = new System.IO.StreamWriter(csEncrypt)) { //Write all data to the stream. swEncrypt.Write(plainText); } encrypted = msEncrypt.ToArray(); } } } // Return the encrypted bytes from the memory stream. return(encrypted); }
public byte[] Decrypte(byte[] inData) { if (!isCrypte) { //if (true) return(inData); } UInt32 len = 0; switch (pkgLen) { case 2: if (inData.Length < 2) { UnityEngine.Debug.LogError("indata len less then 2." + inData.Length); } len = (UInt32)((UInt16)System.Net.IPAddress.NetworkToHostOrder((short)BitConverter.ToUInt16(inData, 0))); break; case 4: len = (UInt32)System.Net.IPAddress.NetworkToHostOrder((int)BitConverter.ToUInt32(inData, 0)); break; } System.Security.Cryptography.ICryptoTransform trs = cryto.CreateDecryptor(key, iv); byte[] outData = new byte[len]; byte[] ddate = trs.TransformFinalBlock(inData, pkgLen, inData.Length - pkgLen); Array.Copy(ddate, outData, len); //UnityEngine.Debug.Log("decrypte inData:" + BitConverter.ToString(inData)); //UnityEngine.Debug.Log("decrypte outData:" + BitConverter.ToString(outData)); return(outData); }
private static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV) { // Declare the string used to hold // the decrypted text. string plaintext = null; // Create an Aes object // with the specified key and IV. using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create()) { aesAlg.Key = Key; aesAlg.IV = IV; // Create a decrytor to perform the stream transform. System.Security.Cryptography.ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for decryption. using (System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(cipherText)) { using (System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream( msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read)) { using (System.IO.StreamReader srDecrypt = new System.IO.StreamReader(csDecrypt)) { // Read the decrypted bytes from the decrypting stream // and place them in a string. plaintext = srDecrypt.ReadToEnd(); } } } } return(plaintext); }
/// <summary> /// AES 解密 /// </summary> /// <param name="str">需解密字符串</param> /// <param name="key">密钥</param> /// <param name="isDecodeUrl">是否需要URL解码</param> /// <returns></returns> public static string AesDecrypt(string str, string key, bool isDecodeUrl = true) { if (string.IsNullOrEmpty(str)) { return(null); } if (isDecodeUrl) { str = System.Web.HttpUtility.UrlDecode(str); } Byte[] toEncryptArray = Convert.FromBase64String(str); System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged { Key = Encoding.UTF8.GetBytes(key), Mode = System.Security.Cryptography.CipherMode.ECB, Padding = System.Security.Cryptography.PaddingMode.PKCS7 }; System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return(Encoding.UTF8.GetString(resultArray)); }
public static string EncryptText(string _In) { try { string sKey = ""; if (_In == "") { return(_In); } sKey = CreateKey("PASSWORD"); System.Security.Cryptography.TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider(); System.Security.Cryptography.MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider(); DES.Key = hashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(sKey)); DES.Mode = System.Security.Cryptography.CipherMode.ECB; System.Security.Cryptography.ICryptoTransform DESEncrypt = DES.CreateEncryptor(); byte[] Buffer = System.Text.ASCIIEncoding.ASCII.GetBytes(_In); return(Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length))); } catch (Exception ex) { clsMessages.ShowErrorException(ex); return(""); } }
/// <summary> /// Método para encriptar em AES /// </summary> /// <param name="plaintext"></param> /// <param name="text"></param> /// <returns></returns> public static byte[] Encrypt(byte[] plaintext, string text) { /* * Block Length: 128bit * Block Mode: ECB * Data Padding: Padded by bytes which Asc() equal for number of padded bytes (done automagically) * Key Padding: 0x00 padded to multiple of 16 bytes * IV: None */ byte[] key = System.Text.ASCIIEncoding.ASCII.GetBytes(text); System.Security.Cryptography.RijndaelManaged AES = new System.Security.Cryptography.RijndaelManaged(); AES.BlockSize = 128; AES.Mode = System.Security.Cryptography.CipherMode.ECB; AES.Key = key; System.Security.Cryptography.ICryptoTransform encryptor = AES.CreateEncryptor(); MemoryStream mem = new MemoryStream(); System.Security.Cryptography.CryptoStream cryptStream = new System.Security.Cryptography.CryptoStream(mem, encryptor, System.Security.Cryptography.CryptoStreamMode.Write); cryptStream.Write(plaintext, 0, plaintext.Length); cryptStream.FlushFinalBlock(); byte[] cypher = mem.ToArray(); cryptStream.Close(); cryptStream = null; encryptor.Dispose(); AES = null; return(cypher); }
private void EncryptUsingDotNet(Stream istream, Stream ostream, byte[] iv, bool forEncryption) { var engine = BlockCipherModel.Engine.Instance <SysSecurity.SymmetricAlgorithm>(); var mode = (SysSecurity.CipherMode)Enum.Parse(typeof(SysSecurity.CipherMode), BlockCipherModel.Mode.ToString()); var padding = (SysSecurity.PaddingMode) Enum.Parse(typeof(SysSecurity.PaddingMode), BlockCipherModel.Padding.ToString()); engine.Mode = mode; engine.Padding = padding; SysSecurity.ICryptoTransform cryptoTranform = forEncryption ? engine.CreateEncryptor(PbkdfModel.Key, iv) : engine.CreateDecryptor(PbkdfModel.Key, iv); SysSecurity.CryptoStreamMode csMode = forEncryption ? SysSecurity.CryptoStreamMode.Write : SysSecurity.CryptoStreamMode.Read; using ( var encStream = new SysSecurity.CryptoStream(forEncryption ? ostream : istream, cryptoTranform, csMode)) { if (forEncryption) { CopyStream(istream, encStream); } else { CopyStream(encStream, ostream); } } }
/// <summary> /// Transforms an input block. /// </summary> /// <param name="transformField">Either the <see cref="encryptor"/> or <see cref="decryptor"/> field.</param> /// <param name="transformCreator">The function to create a new transformer.</param> /// <param name="data">The input data.</param> /// <param name="iv">The initialization vector.</param> /// <returns>The result of the transform.</returns> private byte[] CipherOperation(ref Platform.ICryptoTransform transformField, Func <SymmetricCryptographicKey, byte[], Platform.ICryptoTransform> transformCreator, byte[] data, byte[] iv) { Requires.NotNull(transformCreator, nameof(transformCreator)); Requires.NotNull(data, nameof(data)); if (this.Padding == SymmetricAlgorithmPadding.None && data.Length == 0) { return(data); } if (iv != null || !this.CanStreamAcrossTopLevelCipherOperations || transformField == null) { transformField?.Dispose(); transformField = transformCreator(this, iv); } if (this.CanStreamAcrossTopLevelCipherOperations) { byte[] outputBlock = new byte[data.Length]; int bytesOutput = transformField.TransformBlock(data, 0, data.Length, outputBlock, 0); Array.Resize(ref outputBlock, bytesOutput); return(outputBlock); } else { return(transformField.TransformFinalBlock(data, 0, data.Length)); } }
private byte[] RijndealDecryption(byte[] data) { byte[] result = null; if (RIJNDEALPRIVATEKEY == null) { throw (new InvalidOperationException("Encryption key has not been defined")); } if (data != null && data.Length > 0) { try { Rijndael obj = System.Security.Cryptography.Rijndael.Create(); try { using (System.Security.Cryptography.ICryptoTransform encrypt = obj.CreateDecryptor(RIJNDEALPRIVATEKEY, RIJNDEALVECTORKEY)) { result = encrypt.TransformFinalBlock(data, 0, data.Length); } } catch { } } catch { } } return(result); }
/// <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); }
public static void Main() { //chave secreta byte[] Key = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; //vetor de inicialização byte[] IV = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; //Stream de memória IO.MemoryStream memstream = new IO.MemoryStream(15); //Stream de criptografia CP.RC2CryptoServiceProvider provider = new CP.RC2CryptoServiceProvider(); CP.ICryptoTransform transform = provider.CreateEncryptor(Key, IV); CP.CryptoStreamMode mode = CP.CryptoStreamMode.Write; CP.CryptoStream stream = new CP.CryptoStream(memstream, transform, mode); //Lê cada caracter da string foreach (char ch in "Isto é um teste") { stream.WriteByte((Convert.ToByte(ch))); } int c; //Reposiciona o ponteiro para leitura memstream.Position = c = 0; //técnica não trivial, mas válida while ((c = memstream.ReadByte()) != -1) { Console.Write((char)c); } stream.Close(); //Libera a stream (crypto) memstream.Close(); //Libera a stream (mem) }
public string mEncryptUTF(string text) { byte[] plainBytes = System.Text.UTF8Encoding.UTF8.GetBytes(text); byte[] cipherBytes; using (System.Security.Cryptography.ICryptoTransform sse = rc2.CreateEncryptor()) { using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, sse, CryptoStreamMode.Write)) { cs.Write(plainBytes, 0, plainBytes.Length); cs.FlushFinalBlock(); cs.Close(); cs.Dispose(); } cipherBytes = ms.ToArray(); ms.Close(); ms.Dispose(); } sse.Dispose(); } return(Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length)); }
public static string AES_Decrypt(string input_text) { //Please dont change or EDIT ANY PART of THIS CODE // ''' security_Code= [email protected] string securitycode = "[email protected]"; System.Security.Cryptography.RijndaelManaged AES = new System.Security.Cryptography.RijndaelManaged(); System.Security.Cryptography.MD5CryptoServiceProvider Hash_AES = new System.Security.Cryptography.MD5CryptoServiceProvider(); string decrypted = ""; try { byte[] hash = new byte[32]; byte[] temp = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(securitycode)); Array.Copy(temp, 0, hash, 0, 16); Array.Copy(temp, 0, hash, 15, 16); AES.Key = hash; AES.Mode = CipherMode.ECB; // Security.Cryptography.CipherMode.ECB System.Security.Cryptography.ICryptoTransform DESDecrypter = AES.CreateDecryptor(); byte[] Buffer = Convert.FromBase64String(input_text); decrypted = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length)); } catch (Exception ex) { throw ex; } return(decrypted); }
/// <summary> /// AES解密/ECB/NoPadding /// </summary> /// <param name="str"></param> /// <param name="key"></param> /// <returns></returns> public static string AesDecrypt(string str, string key) { if (string.IsNullOrEmpty(str)) { return(null); } Byte[] toEncryptArray = Convert.FromBase64String(str); //key不足16位时用1补齐 if (key.Length % 16 != 0) { int keyLen = 16 - (key.Length % 16); for (int i = 0; i < keyLen; i++) { key += "1"; } } System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged { Key = Encoding.UTF8.GetBytes(key), Mode = System.Security.Cryptography.CipherMode.ECB, Padding = System.Security.Cryptography.PaddingMode.None }; System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return(Encoding.UTF8.GetString(resultArray).Replace("\0", "")); }
/// <summary> /// Initializes a new instance of the <see cref="CryptoTransformAdaptor"/> class. /// </summary> /// <param name="transform">The transform.</param> internal CryptoTransformAdaptor(Platform.ICryptoTransform transform) { Requires.NotNull(transform, "transform"); this.transform = transform; }