/// <summary> /// Инициализирует новый экземпляр CryptoTransformingBufferedSource получающий данные из указанного источника /// и применяющий к ним указанное криптографическое преобразование. /// </summary> /// <param name="source">Источник данных, к которому будет применяться криптографическое преобразование.</param> /// <param name="cryptoTransform">Криптографическое преобразование, которое будет применяться к данным источника.</param> /// <param name="buffer"> /// Байтовый буфер, в котором будут содержаться преобразованные данные. /// Должен быть достаточен по размеру, /// чтобы вмещать выходной блок криптографического преобразования (cryptoTransform.OutputBlockSize). /// </param> public CryptoTransformingBufferedSource(IBufferedSource source, ICryptographicTransform cryptoTransform, byte[] buffer) { if (source == null) { throw new ArgumentNullException ("source"); } if (cryptoTransform == null) { throw new ArgumentNullException ("cryptoTransform"); } if (buffer == null) { throw new ArgumentNullException ("cryptoTransform"); } if (buffer.Length < 1) { throw new ArgumentOutOfRangeException ("buffer"); } if (buffer.Length < cryptoTransform.OutputBlockSize) { throw new ArgumentOutOfRangeException ("buffer", string.Format (System.Globalization.CultureInfo.InvariantCulture, "buffer.Length ({0}) less than cryptoTransform.OutputBlockSize ({1}).", buffer.Length, cryptoTransform.OutputBlockSize)); } Contract.EndContractBlock (); _source = source; _cryptoTransform = cryptoTransform; _inputMaxBlocks = _source.Buffer.Length / _cryptoTransform.InputBlockSize; _buffer = buffer; }
public override void init(int mode, byte[] key, byte[] iv) { triDes = new System.Security.Cryptography.TripleDESCryptoServiceProvider(); triDes.Mode=System.Security.Cryptography.CipherMode.CBC; triDes.Padding=System.Security.Cryptography.PaddingMode.None; //String pad="NoPadding"; //if(padding) pad="PKCS5Padding"; byte[] tmp; if(iv.Length>ivsize) { tmp=new byte[ivsize]; Array.Copy(iv, 0, tmp, 0, tmp.Length); iv=tmp; } if(key.Length>bsize) { tmp=new byte[bsize]; Array.Copy(key, 0, tmp, 0, tmp.Length); key=tmp; } try { // cipher=javax.crypto.Cipher.getInstance("DESede/CBC/"+pad); /* // The following code does not work on IBM's JDK 1.4.1 SecretKeySpec skeySpec = new SecretKeySpec(key, "DESede"); cipher.init((mode==ENCRYPT_MODE? javax.crypto.Cipher.ENCRYPT_MODE: javax.crypto.Cipher.DECRYPT_MODE), skeySpec, new IvParameterSpec(iv)); */ // DESedeKeySpec keyspec=new DESedeKeySpec(key); // SecretKeyFactory keyfactory=SecretKeyFactory.getInstance("DESede"); // SecretKey _key=keyfactory.generateSecret(keyspec); // cipher.init((mode==ENCRYPT_MODE? // javax.crypto.Cipher.ENCRYPT_MODE: // javax.crypto.Cipher.DECRYPT_MODE), // _key, new IvParameterSpec(iv)); cipher = (mode==ENCRYPT_MODE? triDes.CreateEncryptor(key, iv): triDes.CreateDecryptor(key, iv)); } catch(Exception e) { Console.WriteLine(e); cipher=null; } }
/// <summary> /// AES 解密 /// </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); 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 SystemDecryptByKey(string toDecrypt, string key) { while (16 > key.Length) { key += "_"; } byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); byte[] toEncryptArray = Convert.FromBase64String(toDecrypt); System.Security.Cryptography.RijndaelManaged rDel = new System.Security.Cryptography.RijndaelManaged(); rDel.Key = keyArray; rDel.Mode = System.Security.Cryptography.CipherMode.ECB; rDel.Padding = System.Security.Cryptography.PaddingMode.PKCS7; System.Security.Cryptography.ICryptoTransform cTransform = rDel.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return(UTF8Encoding.UTF8.GetString(resultArray)); }
/// <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 = null) { if (string.IsNullOrWhiteSpace(encryptKey)) { encryptKey = SystemKey.AesKey; } byte[] keyArray = Convert.FromBase64String(encryptKey); byte[] toEncryptArray = null; string result = null; if (string.IsNullOrWhiteSpace(charset)) { toEncryptArray = Encoding.UTF8.GetBytes(bizContent); } else { toEncryptArray = Encoding.GetEncoding(charset).GetBytes(bizContent); } try { using (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); result = Convert.ToBase64String(resultArray); } } catch (Exception ex) { LogHelper.Error(ex); } return(result); }
private static readonly byte[] IV = { 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10 }; // 默认密钥向量 #endregion #region DES加密 public static string Encrypt(string text) { if (string.IsNullOrWhiteSpace(text)) { return(""); } byte[] byteArray = Encoding.UTF8.GetBytes(text); using (System.Security.Cryptography.DESCryptoServiceProvider desCSP = new System.Security.Cryptography.DESCryptoServiceProvider()) { using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) { System.Security.Cryptography.ICryptoTransform iCryptoTransform = desCSP.CreateEncryptor(KEY, IV); using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, iCryptoTransform, System.Security.Cryptography.CryptoStreamMode.Write)) { cryptoStream.Write(byteArray, 0, byteArray.Length); cryptoStream.FlushFinalBlock(); } return(BitConverter.ToString(memoryStream.ToArray()).Replace("-", "")); } } }
/// <summary> /// Decrypts a Base64 wrapped encrypted data from the provided key. /// </summary> /// <param name="Source">The encrypted base64 string.</param> /// <param name="Key">The key to use for decryption.</param> /// <returns>The original binary stream of data.</returns> public System.IO.Stream DecryptToStream(string Source, string Key) { // convert from Base64 to binary byte[] bytIn = System.Convert.FromBase64String(Source); // create a MemoryStream with the input System.IO.MemoryStream ms = new System.IO.MemoryStream(bytIn, 0, bytIn.Length); byte[] bytKey = GetLegalKey(Key); // set the private key _cryptoservice.Key = bytKey; _cryptoservice.IV = bytKey; // create a Decryptor from the Provider Service instance System.Security.Cryptography.ICryptoTransform decrypto = _cryptoservice.CreateDecryptor(); // create Crypto Stream that transforms a stream using the decryption System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, decrypto, System.Security.Cryptography.CryptoStreamMode.Read); return(cs); }
/// <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); Byte[] iv = Encoding.UTF8.GetBytes("SiChuanBingosoft"); System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged { Key = Encoding.UTF8.GetBytes(key), Mode = System.Security.Cryptography.CipherMode.CBC, Padding = System.Security.Cryptography.PaddingMode.PKCS7, IV = iv }; 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[] InternalDecrypt(byte[] data, byte[] key, byte[] IV) { System.IO.MemoryStream loc0 = new System.IO.MemoryStream(); System.Security.Cryptography.ICryptoTransform loc1 = GetDecServiceProvier(key, IV); System.Security.Cryptography.CryptoStream loc2 = new System.Security.Cryptography.CryptoStream(loc0, loc1, System.Security.Cryptography.CryptoStreamMode.Write); loc2.Write(data, 0, data.Length); if (loc2 != null) { loc2.FlushFinalBlock(); loc2.Close(); } byte[] loc3 = loc0.ToArray(); if (loc0 != null) { loc0.Close(); } return(loc3); }
public static byte[] AES_Encrypt(string input, string pass) { System.Security.Cryptography.RijndaelManaged AES = new System.Security.Cryptography.RijndaelManaged(); System.Security.Cryptography.MD5CryptoServiceProvider Hash_AES = new System.Security.Cryptography.MD5CryptoServiceProvider(); try { byte[] hash = new byte[32]; byte[] temp = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass)); 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 AESEncrypter = AES.CreateEncryptor(); byte[] Buffer = System.Text.ASCIIEncoding.ASCII.GetBytes(input); return(AESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length)); } catch (Exception ex) { return(null); } }
public static string EncryptTripleDES(string Plaintext) { 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 DESEncrypt = DES.CreateEncryptor(); var Buffer = System.Text.ASCIIEncoding.ASCII.GetBytes(Plaintext); string TripleDES = Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length)); return(TripleDES); }
static int ReadBitStreamSize(IO.EndianReader s, System.Security.Cryptography.ICryptoTransform hasher, int maxBitStreamSize, bool isProbablyFromMcc) { byte[] bitstream_size_bytes = new byte[sizeof(int)]; s.Read(bitstream_size_bytes); hasher.TransformBlock(bitstream_size_bytes, 0, bitstream_size_bytes.Length, null, 0); if (!s.ByteOrder.IsSameAsRuntime()) { Bitwise.ByteSwap.SwapData(Bitwise.ByteSwap.kInt32Definition, bitstream_size_bytes); } int assumed_size = BitConverter.ToInt32(bitstream_size_bytes, 0); int size = assumed_size; bool size_was_in_range_after_forced_byte_swap = false; if (isProbablyFromMcc) { size = Bitwise.ByteSwap.SwapInt32(size); } else if (assumed_size < 0 || assumed_size > maxBitStreamSize) { size = Bitwise.ByteSwap.SwapInt32(size); if (size <= maxBitStreamSize) { size_was_in_range_after_forced_byte_swap = true; } else { throw new System.IO.InvalidDataException(string.Format( "Invalid bitstream size {0}, data is probably corrupt. Max size is {1}", assumed_size.ToString("X8"), maxBitStreamSize.ToString("X8"))); } } Util.MarkUnusedVariable(ref size_was_in_range_after_forced_byte_swap); return(size); }
/// <summary> /// AES解密 /// </summary> /// <param name="encryptKey"></param> /// <param name="bizContent"></param> /// <param name="charset"></param> /// <returns></returns> public static string AesDencrypt(string encryptKey, string bizContent, string charset = null) { if (string.IsNullOrWhiteSpace(encryptKey)) { encryptKey = SystemKey.AesKey; } var arr_key = Convert.FromBase64String(encryptKey); var arr_content = Convert.FromBase64String(bizContent); var reslut = default(string); try { using (System.Security.Cryptography.RijndaelManaged rDel = new System.Security.Cryptography.RijndaelManaged()) { rDel.Key = arr_key; rDel.Mode = System.Security.Cryptography.CipherMode.CBC; rDel.Padding = System.Security.Cryptography.PaddingMode.PKCS7; rDel.IV = AES_IV; System.Security.Cryptography.ICryptoTransform cTransform = rDel.CreateDecryptor(rDel.Key, rDel.IV); var arr_result = cTransform.TransformFinalBlock(arr_content, 0, arr_content.Length); if (string.IsNullOrWhiteSpace(charset)) { reslut = Encoding.UTF8.GetString(arr_result); } else { reslut = Encoding.GetEncoding(charset).GetString(arr_result); } } } catch (Exception ex) { LogHelper.Error(ex); } return(reslut); }
private static string Decrypt(string cipherString) { try { byte[] keyArray; byte[] toEncryptArray = Convert.FromBase64String(cipherString); //Di default disabilito l'hashing bool useHashing = false; //La chiave deve essere di 24 caratteri string key = "ValueTeamDocsPa3Services"; if (useHashing) { System.Security.Cryptography.MD5CryptoServiceProvider hashmd5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); hashmd5.Clear(); } else { keyArray = UTF8Encoding.UTF8.GetBytes(key); } System.Security.Cryptography.TripleDESCryptoServiceProvider tdes = new System.Security.Cryptography.TripleDESCryptoServiceProvider(); tdes.Key = keyArray; tdes.Mode = System.Security.Cryptography.CipherMode.ECB; tdes.Padding = System.Security.Cryptography.PaddingMode.PKCS7; System.Security.Cryptography.ICryptoTransform cTransform = tdes.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); tdes.Clear(); return(UTF8Encoding.UTF8.GetString(resultArray)); } catch (Exception) { throw; } }
public static bool _CreateEncryptor_System_Security_Cryptography_Rijndael( ) { //Parameters //ReturnType/Value System.Security.Cryptography.ICryptoTransform returnVal_Real = null; System.Security.Cryptography.ICryptoTransform returnVal_Intercepted = null; //Exception Exception exception_Real = null; Exception exception_Intercepted = null; InterceptionMaintenance.disableInterception( ); try { returnValue_Real = System.Security.Cryptography.Rijndael.CreateEncryptor(); } catch (Exception e) { exception_Real = e; } InterceptionMaintenance.enableInterception( ); try { returnValue_Intercepted = System.Security.Cryptography.Rijndael.CreateEncryptor(); } catch (Exception e) { exception_Intercepted = e; } Return((exception_Real.Messsage == exception_Intercepted.Message) && (returnValue_Real == returnValue_Intercepted)); }
public string DecryptFile(string FileName) { System.IO.FileStream fs = null; string s = string.Empty; try { string sKey = GenerateKey(); System.Security.Cryptography.DESCryptoServiceProvider DES = new System.Security.Cryptography.DESCryptoServiceProvider(); DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey); DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey); System.IO.FileInfo dirFile = new System.IO.FileInfo(FileName); if (!dirFile.Exists) { return(string.Empty); } fs = new System.IO.FileStream(FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.Security.Cryptography.ICryptoTransform desdecrypt = DES.CreateDecryptor(); System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(fs, desdecrypt, System.Security.Cryptography.CryptoStreamMode.Read); s = new System.IO.StreamReader(cs).ReadToEnd(); //Return fs.Close(); } catch (Exception ex) { throw ex; } finally { if ((fs != null)) { fs.Close(); } } return(s); }
} // End Constructor // http://www.codeproject.com/KB/aspnet/ASPNET_20_Webconfig.aspx // http://www.codeproject.com/KB/database/Connection_Strings.aspx public string DeCrypt(string strSourceText) { string result = null; try { using (System.Security.Cryptography.TripleDES des3 = System.Security.Cryptography.TripleDES.Create()) { using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create()) { des3.Key = md5.ComputeHash(this.m_encoding.GetBytes(this.m_symmetricKey)); des3.Mode = System.Security.Cryptography.CipherMode.ECB; } // End Using md5 if (Microsoft.VisualBasic.CompilerServices.Operators.CompareString(strSourceText, "", false) != 0) { using (System.Security.Cryptography.ICryptoTransform cryptoTransform = des3.CreateDecryptor()) { byte[] array = System.Convert.FromBase64String(strSourceText); des3.Clear(); result = this.m_encoding.GetString(cryptoTransform.TransformFinalBlock(array, 0, array.Length)); System.Array.Clear(array, 0, array.Length); array = null; } // End Using cryptoTransform } else { result = ""; } } // End Using des3 return(result); } // End Try catch (System.Exception ex) { System.Console.WriteLine(ex.Message); // TODO: Log throw; } }
internal static string ToDescrypt(string chave, string criptografia) { System.Security.Cryptography.RijndaelManaged rijndael = new System.Security.Cryptography.RijndaelManaged(); rijndael.Mode = System.Security.Cryptography.CipherMode.CBC; rijndael.KeySize = 128; byte[] chaveBytes; byte[] criptografiaBytes; byte[] mensagemBytes; string mensagem; chaveBytes = Encoding.UTF8.GetBytes(chave); mensagemBytes = Convert.FromBase64String(criptografia); System.Security.Cryptography.ICryptoTransform cryptor = rijndael.CreateDecryptor(chaveBytes, chaveBytes); criptografiaBytes = cryptor.TransformFinalBlock(mensagemBytes, 0, mensagemBytes.Length); cryptor.Dispose(); mensagem = Encoding.UTF8.GetString(criptografiaBytes); return(mensagem); }
/// <summary> /// 解密 /// </summary> /// <param name="value">值</param> /// <returns>when exception will return empty string</returns> public static string Decrypt(string value) { try { Byte[] keyArray = System.Text.UTF8Encoding.UTF8.GetBytes(_key); Byte[] toEncryptArray = Convert.FromBase64String(value); System.Security.Cryptography.RijndaelManaged rDel = new System.Security.Cryptography.RijndaelManaged(); rDel.Key = keyArray; rDel.Mode = System.Security.Cryptography.CipherMode.ECB; rDel.Padding = System.Security.Cryptography.PaddingMode.PKCS7; System.Security.Cryptography.ICryptoTransform cTransform = rDel.CreateDecryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return(System.Text.UTF8Encoding.UTF8.GetString(resultArray)); } catch { return(string.Empty); } }
public static string Decrypt(string text) { string inputText = text; if (string.IsNullOrWhiteSpace(text)) { return(""); } if (inputText.Contains("-")) { inputText = inputText.Replace("-", ""); } if (inputText.Contains(" ")) { inputText = inputText.Replace(" ", ""); } if (inputText.Length % 2 != 0) { throw new ArgumentException("要解密的字符串长度无效。"); } byte[] byteArray = new byte[inputText.Length / 2]; for (int i = 0; i < byteArray.Length; i++) { byteArray[i] = byte.Parse(inputText.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber); } using (System.Security.Cryptography.DESCryptoServiceProvider desCSP = new System.Security.Cryptography.DESCryptoServiceProvider()) { using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) { System.Security.Cryptography.ICryptoTransform iCryptoTransform = desCSP.CreateDecryptor(KEY, IV); using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, iCryptoTransform, System.Security.Cryptography.CryptoStreamMode.Write)) { cryptoStream.Write(byteArray, 0, byteArray.Length); cryptoStream.FlushFinalBlock(); } return(Encoding.UTF8.GetString(memoryStream.ToArray())); } } }
/// <summary> /// AES加密 /// </summary> /// <param name="str">需要加密的字符串</param> /// <param name="key">32位密钥</param> /// <returns>加密后的字符串</returns> public static string EncryptToString(string str, string key) { Byte[] keyArray = System.Text.Encoding.UTF8.GetBytes(key); Byte[] toEncryptArray = System.Text.Encoding.UTF8.GetBytes(str); var rijndael = new System.Security.Cryptography.RijndaelManaged(); rijndael.Key = keyArray; rijndael.Mode = System.Security.Cryptography.CipherMode.ECB; rijndael.Padding = System.Security.Cryptography.PaddingMode.PKCS7; rijndael.IV = System.Text.Encoding.UTF8.GetBytes(Iv); System.Security.Cryptography.ICryptoTransform cTransform = rijndael.CreateEncryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); StringBuilder builder = new StringBuilder(); int num2 = resultArray.Length - 1; for (int i = 0; i <= num2; i++) { builder.AppendFormat("{0:X2}", resultArray[i]); } return(builder.ToString()); // return Convert.ToBase64String(resultArray, 0, resultArray.Length); }
public string DecryptString(string value, string keyString) { try { byte[] resultBA = new byte[value.Length / 2], valueBA = new byte[value.Length / 2]; byte[] iv = new byte[] { 0x14, 0xD7, 0x5B, 0xA2, 0x47, 0x83, 0x0F, 0xC4 }; System.Text.ASCIIEncoding ascEncoding = new System.Text.ASCIIEncoding(); byte[] key = new byte[24]; ascEncoding.GetBytes(keyString, 0, keyString.Length < 24?keyString.Length:24, key, 0); MemoryStream memStream = new MemoryStream(); byte[] tempBA = InternalMethods.HexStringToBytes(value); memStream.Write(tempBA, 0, tempBA.Length); memStream.Position = 0; System.Security.Cryptography.TripleDES cryptoServiceProvider = System.Security.Cryptography.TripleDESCryptoServiceProvider.Create(); System.Security.Cryptography.ICryptoTransform decryptor = cryptoServiceProvider.CreateDecryptor(key, iv); System.Security.Cryptography.CryptoStream cStream = new System.Security.Cryptography.CryptoStream( memStream, decryptor, System.Security.Cryptography.CryptoStreamMode.Read); cStream.Read(resultBA, 0, resultBA.Length); cStream.Close(); return(ascEncoding.GetString(resultBA)); } catch (Exception exc) { LogEvent("Decryption failure. Returning original value" + Environment.NewLine + exc.Source, "DecryptString()", exc.ToString(), 3); return(value); } }
static public byte[] Encode(byte[] Data, System.Security.Cryptography.ICryptoTransform Encoder) { byte[] Outer; int rdlen = 0; using (System.IO.MemoryStream memStream = new System.IO.MemoryStream()) { byte[] bin = new byte[128]; int len; System.IO.MemoryStream InputStr = new System.IO.MemoryStream(); InputStr.Write(Data, 0, Data.Length); InputStr.Position = 0; System.Security.Cryptography.CryptoStream CryptStream = new System.Security.Cryptography.CryptoStream(memStream, Encoder, System.Security.Cryptography.CryptoStreamMode.Write); while (rdlen < Data.Length) { len = InputStr.Read(bin, 0, 128); CryptStream.Write(bin, 0, len); rdlen = rdlen + len; } CryptStream.FlushFinalBlock(); Outer = memStream.ToArray(); CryptStream.Close(); } return(Outer); }
public bool Encrypt(byte[] src, out byte[] dst) { dst = new byte[src.Length]; if (key == null) { key = GetAssemblyHash(); } System.Security.Cryptography.RSA rsa = System.Security.Cryptography.RSA.Create(); System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create(); aes.Key = key; System.Security.Cryptography.ICryptoTransform ict = aes.CreateEncryptor(); for (int l = 0; l < src.Length;) { l += ict.TransformBlock(src, l, l + bufferSize < src.Length? bufferSize: src.Length - l, dst, l); } return(true); }
public string Descriptografar(string chave, string criptografia) { System.Security.Cryptography.TripleDES des = System.Security.Cryptography.TripleDES.Create(); des.Mode = System.Security.Cryptography.CipherMode.CBC; des.KeySize = 192; byte[] chaveBytes; byte[] criptografiaBytes; byte[] mensagemBytes; string mensagem; chaveBytes = Encoding.UTF8.GetBytes(chave); mensagemBytes = Convert.FromBase64String(criptografia); System.Security.Cryptography.ICryptoTransform cryptor = des.CreateDecryptor(chaveBytes, chaveBytes); criptografiaBytes = cryptor.TransformFinalBlock(mensagemBytes, 0, mensagemBytes.Length); cryptor.Dispose(); mensagem = Encoding.UTF8.GetString(criptografiaBytes); return(mensagem); }
public string AesEncrypt(string input) { System.Security.Cryptography.RijndaelManaged aes = new System.Security.Cryptography.RijndaelManaged(); System.Security.Cryptography.MD5CryptoServiceProvider hashAes = new System.Security.Cryptography.MD5CryptoServiceProvider(); try { byte[] hash = new byte[32]; byte[] temp = hashAes.ComputeHash(System.Text.Encoding.UTF8.GetBytes(_hashKey)); 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 DESEncrypter = aes.CreateEncryptor(); byte[] Buffer = System.Text.Encoding.UTF8.GetBytes(input); var encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length)); return(encrypted); } catch (Exception) { return(""); } }
/// <summary> /// AES解密 /// </summary> /// <param name="str">需要解密的字符串</param> /// <param name="key">32位密钥</param> /// <returns>解密后的字符串</returns> public static string Decrypt(string str, string key) { try { byte[] keyArray = Encoding.UTF8.GetBytes(key); byte[] toEncryptArray = Convert.FromBase64String(str); var rijndael = new System.Security.Cryptography.RijndaelManaged { Key = keyArray, Mode = System.Security.Cryptography.CipherMode.ECB, Padding = System.Security.Cryptography.PaddingMode.PKCS7 }; //rijndael.IV = System.Text.Encoding.UTF8.GetBytes(Iv); System.Security.Cryptography.ICryptoTransform cTransform = rijndael.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return(Encoding.UTF8.GetString(resultArray)); } catch (Exception ex) { return(str); } }
internal static string ToCrypt(string chave, string mensagem) { System.Security.Cryptography.DES des = System.Security.Cryptography.DES.Create(); des.Mode = System.Security.Cryptography.CipherMode.CBC; des.KeySize = 64; byte[] chaveBytes; byte[] criptografiaBytes; byte[] mensagemBytes; string criptografia; chaveBytes = Encoding.UTF8.GetBytes(chave); mensagemBytes = Encoding.UTF8.GetBytes(mensagem); System.Security.Cryptography.ICryptoTransform cryptor = des.CreateEncryptor(chaveBytes, chaveBytes); criptografiaBytes = cryptor.TransformFinalBlock(mensagemBytes, 0, mensagemBytes.Length); cryptor.Dispose(); criptografia = Convert.ToBase64String(criptografiaBytes); return(criptografia); }
private byte[] AESEncrypt(byte[] data, byte[] key) { byte[] cipherTextBytes = null; // Create uninitialized Rijndael encryption object. System.Security.Cryptography.RijndaelManaged symmetricKey = new System.Security.Cryptography.RijndaelManaged(); // It is required that the encryption mode is Electronic Codebook (ECB) // see MS-OFFCRYPTO v1.0 2.3.4.7 pp 39. symmetricKey.Mode = System.Security.Cryptography.CipherMode.ECB; symmetricKey.Padding = System.Security.Cryptography.PaddingMode.None; // System.Security.Cryptography.PaddingMode.None; symmetricKey.KeySize = this.keySize; // symmetricKey.Key = key; // symmetricKey.IV = new byte[16]; // Generate encryptor from the existing key bytes and initialization vector. // Key size will be defined based on the number of the key bytes. System.Security.Cryptography.ICryptoTransform encryptor = symmetricKey.CreateEncryptor(key, null); // Define memory stream which will be used to hold encrypted data. using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) { // Define cryptographic stream (always use Write mode for encryption). using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, encryptor, System.Security.Cryptography.CryptoStreamMode.Write)) { // Start encrypting. cryptoStream.Write(data, 0, data.Length); // Finish encrypting. cryptoStream.FlushFinalBlock(); } // Convert our encrypted data from a memory stream into a byte array. cipherTextBytes = memoryStream.ToArray(); return(cipherTextBytes); } }
//public enum Symmetric //{ // AES //} //public void Get(Symmetric alg) //{ //} //public enum Asymmetric //{ // RSA //} //public void Get(Asymmetric alg) //{ //} //public enum Hash //{ // SHA256, // SHA512 //} //public void Get(Hash alg) //{ //} //public enum HMAC //{ // HMACSHA256, // HMACSHA512 //} //public void Get(HMAC alg) //{ //} //public void GetRng() //{ //} //public void GetPBKDF() //{ //} public byte[] Encrypt(string plainText, byte[] keyBytes, byte[] ivBytes) { if (plainText == null || plainText.Length <= 0) { throw new ArgumentNullException("plainText"); } if (keyBytes == null || keyBytes.Length <= 0) { throw new ArgumentNullException("Key"); } if (ivBytes == null || ivBytes.Length <= 0) { throw new ArgumentNullException("IV"); } System.IO.MemoryStream memoryStream; using (System.Security.Cryptography.AesCryptoServiceProvider csp = new System.Security.Cryptography.AesCryptoServiceProvider()) { csp.Key = keyBytes; csp.IV = ivBytes; //csp.CreateEncryptor // Create an encryptor to perform the stream transform. System.Security.Cryptography.ICryptoTransform cryptoTransformer = csp.CreateEncryptor(csp.Key, csp.IV); // Create the streams used for encryption. using (memoryStream = new System.IO.MemoryStream()) using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, cryptoTransformer, System.Security.Cryptography.CryptoStreamMode.Write)) using (System.IO.StreamWriter sw = new System.IO.StreamWriter(cryptoStream)) { sw.AutoFlush = true; sw.Write(plainText); } } return(memoryStream.ToArray()); }
/// <summary> /// 解密数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Button2_Click(object sender, EventArgs e) { //写新解密文 using (System.IO.FileStream writeFile = System.IO.File.Create(Server.MapPath("./temp可删除/") + System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName) + ".Dencode")) { //读取加密码key using (System.IO.Stream sr = FileUpload2.PostedFile.InputStream) { System.Security.Cryptography.AesManaged Aes = new System.Security.Cryptography.AesManaged(); byte[] ByteKey = new byte[32]; sr.Read(ByteKey, 0, ByteKey.Length); //读取KEY using (System.Security.Cryptography.ICryptoTransform dencode = Aes.CreateDecryptor(ByteKey, ByteKey.Take(16).ToArray())) { //开始解密一次性 //byte[] result = dencode.TransformFinalBlock(reads, 0, len); //使用DES流解密 using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(writeFile, dencode, System.Security.Cryptography.CryptoStreamMode.Write)) { while (sr.CanRead) { byte[] reads = new byte[2048]; //读取的有效长度 int len = sr.Read(reads, 0, reads.Length); if (len == 0) { break; } cs.Write(reads, 0, len); } cs.Close(); } } sr.Close(); } writeFile.Close(); } }
// 復号化された文字列を返す public string CreateDecryptorString(string baseString) { string output = ""; System.Security.Cryptography.RijndaelManaged rijndael = new System.Security.Cryptography.RijndaelManaged(); //パスワードから共有キーと初期化ベクタを作成 byte[] key; byte[] iv; GenerateKeyFromPassword( GeneratePassward,//password rijndael.KeySize, out key, rijndael.BlockSize, out iv ); rijndael.Key = key; rijndael.IV = iv; //文字列をバイト型配列に戻す byte[] strBytes = System.Convert.FromBase64String(baseString); //対称暗号化オブジェクトの作成 System.Security.Cryptography.ICryptoTransform decryptor = rijndael.CreateDecryptor(); //バイト型配列を復号化する //復号化に失敗すると例外CryptographicExceptionが発生 byte[] decBytes = decryptor.TransformFinalBlock(strBytes, 0, strBytes.Length); //閉じる decryptor.Dispose(); //バイト型配列を文字列に戻して返す output = System.Text.Encoding.UTF8.GetString(decBytes); return(output); }
private static long MapTransformIndexBackToOriginal(long resultIndex, ICryptographicTransform transform) { var blockNumber = resultIndex / (long)transform.OutputBlockSize; var blockOffset = ((resultIndex % (long)transform.OutputBlockSize) % (long)transform.InputBlockSize); return blockNumber * transform.InputBlockSize + blockOffset; }
internal EncryptedStream(System.Security.Cryptography.ICryptoTransform encoder) { mEncoder = encoder; }
public EncryptionStream(AesEncoderNode node, System.Security.Cryptography.ICryptoTransform encoder) { mNode = node; mEncoder = encoder; mBuffer1 = new byte[16]; mBuffer2 = new byte[16]; }
/// <summary> /// Initializa os objetos necessários para realizar criptografia e descriptografia. /// </summary> private void Initialize() { System.Security.Cryptography.RijndaelManaged v_rijndael; System.Security.Cryptography.Rfc2898DeriveBytes v_passwordbytes; byte[] v_initvectorbytes; byte[] v_keybytes; v_rijndael = new System.Security.Cryptography.RijndaelManaged(); v_rijndael.Mode = System.Security.Cryptography.CipherMode.CBC; v_initvectorbytes = System.Text.Encoding.ASCII.GetBytes(this.v_initvector); v_passwordbytes = new System.Security.Cryptography.Rfc2898DeriveBytes(this.v_password, v_initvectorbytes, 1); v_keybytes = v_passwordbytes.GetBytes(this.v_keysize / 8); this.v_encryptor = v_rijndael.CreateEncryptor(v_keybytes, v_initvectorbytes); this.v_decryptor = v_rijndael.CreateDecryptor(v_keybytes, v_initvectorbytes); }