public AuthenticationHelper() { var rm = new RijndaelManaged(); encryptor = rm.CreateEncryptor(key, vector); decryptor = rm.CreateDecryptor(key, vector); encoder = new UTF8Encoding(); }
// Methods public EncryptionHelper() { RijndaelManaged managed = new RijndaelManaged(); this.EncryptorTransform = managed.CreateEncryptor(this.Key, this.Vector); this.DecryptorTransform = managed.CreateDecryptor(this.Key, this.Vector); this.UTFEncoder = new UTF8Encoding(); }
byte[] EncryptKeyForArchival(byte[] keyToExport, string passphrase, byte[] salt) { RijndaelManaged archivalEncryptionAlgorithm = new RijndaelManaged(); byte[] rgbKey = this.GenerateArchivalKey(archivalEncryptionAlgorithm, passphrase, salt); byte[] rgbIV = new byte[archivalEncryptionAlgorithm.BlockSize / 8]; return CryptographyUtility.Transform(archivalEncryptionAlgorithm.CreateEncryptor(rgbKey, rgbIV), keyToExport); }
private static String encrypt (Dictionary<String, String> data, String api_key) { JavaScriptSerializer serializer = new JavaScriptSerializer(); String json_data = serializer.Serialize(data); String iv = api_key.Substring(16, 16); api_key = api_key.Substring(0, 16); byte[] data_bytes = Encoding.UTF8.GetBytes(json_data); byte[] api_bytes = Encoding.ASCII.GetBytes(api_key); byte[] iv_bytes = Encoding.ASCII.GetBytes(iv); RijndaelManaged AES = new RijndaelManaged(); AES.Padding = PaddingMode.PKCS7; AES.Mode = CipherMode.CBC; AES.BlockSize = 128; AES.KeySize = 128; MemoryStream memStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memStream, AES.CreateEncryptor(api_bytes, iv_bytes), CryptoStreamMode.Write); cryptoStream.Write(data_bytes, 0, data_bytes.Length); cryptoStream.FlushFinalBlock(); byte[] encryptedMessageBytes = new byte[memStream.Length]; memStream.Position = 0; memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length); string encryptedMessage = System.Convert.ToBase64String(encryptedMessageBytes); return HttpUtility.UrlEncode(encryptedMessage); }
public static string EncryptString( string plainText, string passPhrase, string saltValue, int passwordIterations, string initVector, int keySize) { byte[] initVectorBytes = initVector == null ? new byte[16] : Encoding.ASCII.GetBytes(initVector); byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); byte[] keyBytes = GetKeyBytes(passPhrase, saltValue, passwordIterations, keySize); RijndaelManaged symmetricKey = new RijndaelManaged(); symmetricKey.Mode = CipherMode.CBC; ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes); byte[] cipherTextBytes; using (MemoryStream memoryStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); cipherTextBytes = memoryStream.ToArray(); } } string cipherText = Convert.ToBase64String(cipherTextBytes); return cipherText; }
public AesEncryption(byte[] Key, byte[] Vector) { RijndaelManaged rijndaelManaged = new RijndaelManaged(); this.EncryptorTransform = rijndaelManaged.CreateEncryptor(Key, Vector); this.DecryptorTransform = rijndaelManaged.CreateDecryptor(Key, Vector); this.UTFEncoder = new UTF8Encoding(); }
public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes) { byte[] encryptedBytes = null; // Set your salt here, change it to meet your flavor: // The salt bytes must be at least 8 bytes. byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; using (MemoryStream ms = new MemoryStream()) { using (RijndaelManaged AES = new RijndaelManaged()) { AES.KeySize = 256; AES.BlockSize = 128; var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); AES.Key = key.GetBytes(AES.KeySize / 8); AES.IV = key.GetBytes(AES.BlockSize / 8); AES.Mode = CipherMode.CBC; using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length); cs.Close(); } encryptedBytes = ms.ToArray(); } } return encryptedBytes; }
public static string Encrypt(string plainText, string passPhrase) { // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text // so that the same Salt and IV values can be used when decrypting. var saltStringBytes = Generate256BitsOfRandomEntropy(); var ivStringBytes = Generate256BitsOfRandomEntropy(); var plainTextBytes = Encoding.UTF8.GetBytes(plainText); var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations); var keyBytes = password.GetBytes(Keysize / 8); using (var symmetricKey = new RijndaelManaged()) { symmetricKey.BlockSize = 256; symmetricKey.Mode = CipherMode.CBC; symmetricKey.Padding = PaddingMode.PKCS7; using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes)) { using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes. var cipherTextBytes = saltStringBytes; cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray(); cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray(); memoryStream.Close(); cryptoStream.Close(); return Convert.ToBase64String(cipherTextBytes); } } } } }
public static string Criptografar(string texto) { if(string.IsNullOrEmpty(texto)) return String.Empty; string outStr; RijndaelManaged aesAlg = null; try { var key = new Rfc2898DeriveBytes(Segredo, Complemento); aesAlg = new RijndaelManaged(); aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8); aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8); var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); using (var msEncrypt = new MemoryStream()) { using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (var swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(texto); } } outStr = Convert.ToBase64String(msEncrypt.ToArray()); } } finally { if (aesAlg != null) aesAlg.Clear(); } return outStr; }
public static string Encrypt(string plainText, string passPhrase) { byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null)) { byte[] keyBytes = password.GetBytes(keysize / 8); using (RijndaelManaged symmetricKey = new RijndaelManaged()) { symmetricKey.Mode = CipherMode.CBC; using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)) { using (MemoryStream memoryStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); byte[] cipherTextBytes = memoryStream.ToArray(); return Convert.ToBase64String(cipherTextBytes); } } } } } }
public static IVCryptoStream Save(string path, byte[] key, byte[] iv) { FileStream file = new FileStream(path, FileMode.Create); RijndaelManaged crypt = new RijndaelManaged(); crypt.Key = key; if (iv == null) crypt.GenerateIV(); else { Debug.Assert(iv.Length == crypt.IV.Length); crypt.IV = iv; } try { file.Write(crypt.IV, 0, crypt.IV.Length); } catch { file.Dispose(); } return new IVCryptoStream(file, crypt.CreateEncryptor(), CryptoStreamMode.Write); }
/// <summary> /// Encrypts a string /// </summary> /// <param name="PlainText">Text to be encrypted</param> /// <param name="Password">Password to encrypt with</param> /// <param name="Salt">Salt to encrypt with</param> /// <param name="InitialVector">Needs to be 16 ASCII characters long</param> /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param> /// <param name="PasswordIterations">Number of iterations to do</param> /// <param name="KeySize">Can be 128, 192, or 256</param> /// <returns>An encrypted bytes</returns> public static byte[] Encrypt(byte[] PlainText, byte[] Password, byte[] InitialVector, byte[] Salt) { PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, Salt, HASH_ALGORITHM, PASSWORDITERATIONS); byte[] KeyBytes = DerivedPassword.GetBytes(KEY_SIZE / 8); RijndaelManaged SymmetricKey = new RijndaelManaged(); SymmetricKey.Mode = CipherMode.CBC; byte[] CipherTextBytes = null; using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVector)) { using (MemoryStream MemStream = new MemoryStream()) { using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write)) { CryptoStream.Write(PlainText, 0, PlainText.Length); CryptoStream.FlushFinalBlock(); CipherTextBytes = MemStream.ToArray(); MemStream.Close(); CryptoStream.Close(); } } } SymmetricKey.Clear(); return CipherTextBytes; //return Encoding.UTF8.GetBytes(Convert.ToBase64String(CipherTextBytes)); }
/// <summary> /// AES加密 /// </summary> /// <param name="plainText">要加密的字串</param> /// <returns>加密后的字串</returns> public static string EncryptStringAES(string plainText) { if (string.IsNullOrEmpty(plainText)) throw new ArgumentNullException("plainText"); string outStr = null; RijndaelManaged aesAlg = null; try { Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(_secret, _salt); aesAlg = new RijndaelManaged(); aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8); ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msEncrypt = new MemoryStream()) { msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int)); msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length); using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(plainText); } } outStr = Convert.ToBase64String(msEncrypt.ToArray()); } } finally { if (aesAlg != null) aesAlg.Clear(); } return outStr; }
internal static String Encrypt_AES(String data, String key, String iv) { byte[] encryptedBytes = null; byte[] bytesToBeEncrypted = Encoding.UTF8.GetBytes(data); using (MemoryStream ms = new MemoryStream()) { using (RijndaelManaged AES = new RijndaelManaged()) { AES.KeySize = 256; AES.BlockSize = 256; AES.Padding = PaddingMode.Zeros; AES.Key = Encoding.UTF8.GetBytes(key); AES.IV = Encoding.UTF8.GetBytes(iv); AES.Mode = CipherMode.CBC; using (var cs = new CryptoStream(ms, AES.CreateEncryptor(AES.Key, AES.IV), CryptoStreamMode.Write)) { cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length); cs.Close(); } encryptedBytes = ms.ToArray(); } } return Convert.ToBase64String(encryptedBytes, 0, encryptedBytes.Length); }
public SimplerAES() { RijndaelManaged rm = new RijndaelManaged(); encryptor = rm.CreateEncryptor(key, vector); decryptor = rm.CreateDecryptor(key, vector); encoder = new UTF8Encoding(); }
private const int IterateDecoding = 1000; //Try to think of a less terrible name for this. public static string EncryptPassword(string plainText, string passPhrase) { var rand1StringBytes = Generate256BitsOfStuff(); //256 bits of random ****. var rand2StringBytes = Generate256BitsOfStuff(); //Two * 256 bits of random ****. You'll see why! var unencryptedTextBytes = Encoding.UTF8.GetBytes(plainText); //unencrypted plain text. I hope we're not getting marked on the conciseness of our variable declerations... using (var password = new Rfc2898DeriveBytes(passPhrase, rand1StringBytes, IterateDecoding)) { var keyBytes = password.GetBytes(KeySize / 8); using (var symmetricKey = new RijndaelManaged()) { symmetricKey.BlockSize = KeySize; //There's no need to use more RAM than we need now is there? symmetricKey.Mode = CipherMode.CBC; symmetricKey.Padding = PaddingMode.PKCS7; using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, rand2StringBytes)) { using (var memoryStream = new MemoryStream()) //Using memory stream is a great way of keeping information volitile/difficult to intercept. { using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(unencryptedTextBytes, 0, unencryptedTextBytes.Length); //There's no point in encrypting characters that aren't there. cryptoStream.FlushFinalBlock(); // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes. var cipherTextBytes = rand1StringBytes; cipherTextBytes = cipherTextBytes.Concat(rand2StringBytes).ToArray(); //Stores how we've encrypted everything in an array so we can decrypt it when needed. cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray(); memoryStream.Close(); cryptoStream.Close(); return Convert.ToBase64String(cipherTextBytes); } } } } } } //End of encrypt method.
/// <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 string Encrypt(string value) { if (value == null) { throw new ArgumentNullException("value"); } if (m_key == null) { throw new InvalidOperationException(Resources.Global.InvalidHashKey); } byte[] data = Encoding.UTF8.GetBytes(value); using (var crypto = new RijndaelManaged()) using (var encryptor = crypto.CreateEncryptor(m_key, m_vector)) using (var memoryStream = new MemoryStream()) { var crptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write); crptoStream.Write(data, 0, data.Length); crptoStream.FlushFinalBlock(); return Convert.ToBase64String(memoryStream.ToArray()); } }
public static string AesEncrypt(string str) { if (string.IsNullOrEmpty(str)) { return(null); } Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str); Byte[] tmpArray = { }; //加密数据不足16位时用0补齐 if (toEncryptArray.Length % 16 != 0) { int len = 16 - (toEncryptArray.Length % 16); tmpArray = Enumerable.Repeat((byte)0, len).ToArray(); } toEncryptArray = toEncryptArray.Concat(tmpArray).ToArray(); 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.CreateEncryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return(Convert.ToBase64String(resultArray, 0, resultArray.Length)); }
public string somaSaldo(string text) { try { if (!string.IsNullOrEmpty(text)) { byte[] bKey = Convert.FromBase64String(cryptoKey); byte[] bText = new UTF8Encoding().GetBytes(text); Rijndael rijndael = new RijndaelManaged(); rijndael.KeySize = 256; MemoryStream mStream = new MemoryStream(); CryptoStream encryptor = new CryptoStream(mStream, rijndael.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write); encryptor.Write(bText, 0, bText.Length); encryptor.FlushFinalBlock(); return Convert.ToBase64String(mStream.ToArray()); } else { return null; } } catch (Exception ex) { throw new ApplicationException("Erro ao criptografar" + ex.Message, ex); } }
/// <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> /// <param name="sourceString">暗号化する文字列</param> /// <returns>暗号化された文字列</returns> public static byte[] Encrypt(string sourceString) { //RijndaelManagedオブジェクトを作成 RijndaelManaged rijndael = new RijndaelManaged(); string password = null; object[] guids = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), false); if (guids == null || guids.Length == 0 || !( guids[0] is System.Runtime.InteropServices.GuidAttribute )) { throw new ApplicationException(); } password = ( (System.Runtime.InteropServices.GuidAttribute)guids[0] ).Value; //パスワードから共有キーと初期化ベクタを作成 byte[] key, iv; GenerateKeyFromPassword(password, rijndael.KeySize, out key, rijndael.BlockSize, out iv); rijndael.Key = key; rijndael.IV = iv; //文字列をバイト型配列に変換する byte[] strBytes = Encoding.UTF8.GetBytes(sourceString); byte[] encBytes = new byte[0]; //対称暗号化オブジェクトの作成 using (ICryptoTransform encryptor = rijndael.CreateEncryptor()) { //バイト型配列を暗号化する encBytes = encryptor.TransformFinalBlock(strBytes, 0, strBytes.Length); //閉じる } //バイト型配列を文字列に変換して返す return encBytes; }
public static string AES_Encrypt(string input_text) { //Please dont change or EDIT ANY PART of THIS CODE // ''' security_Code= [email protected] string 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) { throw ex; } return(encrypted); }
public static byte[] Encrypt(byte[] input) { if (_key == null || _key.Length == 0) throw new Exception("Key can not be empty."); if (input == null || input.Length == 0) throw new ArgumentException("Input can not be empty."); byte[] data = input, encdata = new byte[0]; try { using (var ms = new MemoryStream()) { using (var rd = new RijndaelManaged { Key = _key }) { rd.GenerateIV(); using (var cs = new CryptoStream(ms, rd.CreateEncryptor(), CryptoStreamMode.Write)) { ms.Write(rd.IV, 0, rd.IV.Length); // write first 16 bytes IV, followed by encrypted message cs.Write(data, 0, data.Length); } } encdata = ms.ToArray(); } } catch { } return encdata; }
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); }
private byte[] aesEncodeInternal(byte[] plainData, byte[] cKey, byte[] cIV) { if (plainData == null || plainData.Length <= 0) throw new ArgumentNullException("plainData"); if (cKey == null || cKey.Length <= 0) throw new ArgumentNullException("cKey"); if (cIV == null || cIV.Length <= 0) throw new ArgumentNullException("cIV"); MemoryStream msEncrypt = null; RijndaelManaged aesAlg = null; try { aesAlg = new RijndaelManaged(); aesAlg.KeySize = 256; aesAlg.Key = _sha256.ComputeHash(cKey); aesAlg.IV = cIV; ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); msEncrypt = new MemoryStream(); using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { csEncrypt.Write(plainData, 0, plainData.Length); } } finally { if (aesAlg != null) aesAlg.Clear(); } return msEncrypt.ToArray(); }
/// <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 void CBC_0() { byte[] plaintext = new byte[32]; for (int i=0; i < plaintext.Length; i++) plaintext[i] = 0; byte[] iv = new byte[16]; for (byte i=0; i < iv.Length; i++) { iv[i] = 0; } RijndaelManaged r = new RijndaelManaged(); byte[] key = new byte[16]; for (int i=0; i < 16; i++) r.Key[i] = 0; r.BlockSize = 128; r.Mode = CipherMode.CBC; r.Padding = PaddingMode.Zeros; r.Key = key; byte[] expected = { 0x66, 0xe9, 0x4b, 0xd4, 0xef, 0x8a, 0x2c, 0x3b, 0x88, 0x4c, 0xfa, 0x59, 0xca, 0x34, 0x2b, 0x2e, 0xf7, 0x95, 0xbd, 0x4a, 0x52, 0xe2, 0x9e, 0xd7, 0x13, 0xd3, 0x13, 0xfa, 0x20, 0xe9, 0x8d, 0xbc }; CheckCBC(r.CreateEncryptor(key, iv), r.CreateDecryptor(key, iv), plaintext, expected); }
/// <summary> /// Encrypts a string /// </summary> /// <param name="plainText">Text to be encrypted</param> /// <param name="password">Password to encrypt with</param> /// <param name="salt">Salt to encrypt with</param> /// <param name="hashAlgorithm">Can be either SHA1 or MD5</param> /// <param name="passwordIterations">Number of iterations to do. The number of times the algorithm is run on the text. </param> /// <param name="initialVector">Needs to be 16 ASCII characters long</param> /// <param name="keySize">Can be 128, 192, or 256</param> /// <returns>An encrypted string</returns> public static string Encrypt(string plainText, string password, string salt = "69ad1bfbd6605f3f6a3011460cdfb9db7757e0f9", string hashAlgorithm = "SHA1", int passwordIterations = 2, string initialVector = "OFRna73m*aze01xY", int keySize = 256) { if (string.IsNullOrEmpty(plainText)) return ""; byte[] initialVectorBytes = Encoding.ASCII.GetBytes(initialVector); byte[] saltValueBytes = Encoding.ASCII.GetBytes(salt); byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); var derivedPassword = new PasswordDeriveBytes(password, saltValueBytes, hashAlgorithm, passwordIterations); byte[] keyBytes = derivedPassword.GetBytes(keySize / 8); var symmetricKey = new RijndaelManaged {Mode = CipherMode.CBC}; byte[] cipherTextBytes; using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initialVectorBytes)) { using (MemoryStream memStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); cipherTextBytes = memStream.ToArray(); memStream.Close(); cryptoStream.Close(); } } } symmetricKey.Clear(); return Convert.ToBase64String(cipherTextBytes); }
/// <summary> /// Encrypts a string /// </summary> /// <param name="PlainText">Text to be encrypted</param> /// <param name="Password">Password to encrypt with</param> /// <param name="Salt">Salt to encrypt with</param> /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param> /// <param name="PasswordIterations">Number of iterations to do</param> /// <param name="InitialVector">Needs to be 16 ASCII characters long</param> /// <param name="KeySize">Can be 128, 192, or 256</param> /// <returns>An encrypted string</returns> public static string Encrypt(string PlainText, string Password, string Salt = "Kosher", string HashAlgorithm = "SHA1", int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY", int KeySize = 256) { if (string.IsNullOrEmpty(PlainText)) return ""; byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector); byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt); byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText); PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations); byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8); RijndaelManaged SymmetricKey = new RijndaelManaged(); SymmetricKey.Mode = CipherMode.CBC; byte[] CipherTextBytes = null; using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes)) { using (MemoryStream MemStream = new MemoryStream()) { using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write)) { CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length); CryptoStream.FlushFinalBlock(); CipherTextBytes = MemStream.ToArray(); MemStream.Close(); CryptoStream.Close(); } } } SymmetricKey.Clear(); return Convert.ToBase64String(CipherTextBytes); }
public void encryption() { byte[] file = new byte[FileUpload1.PostedFile.ContentLength]; FileUpload1.PostedFile.InputStream.Read(file, 0, FileUpload1.PostedFile.ContentLength); string fileName = txtfilename.Text; byte[] Key = Encoding.UTF8.GetBytes(LTRPRIKEY.Text); ASCIIEncoding.ASCII.GetString(Key); try { string outputFile = Path.Combine(Server.MapPath("~/uploadfiles/advance"), fileName); FileStream fs = new FileStream(outputFile, FileMode.Create); RijndaelManaged rmCryp = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fs, rmCryp.CreateEncryptor(Key, Key), CryptoStreamMode.Write); foreach (var data in file) { cs.WriteByte((byte)data); } cs.Close(); fs.Close(); insert(); } catch (Exception ex) { ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert(" + ex + ");", true); } }
protected static byte[] encoded(byte[] bytesToBeEncrypted, byte[] passwordBytes) { byte[] encryptedBytes = null; byte[] saltBytes = new byte[] { 2, 15, 240, 232, 39, 204, 190, 33, 226, 206, 110, 107, 61, 25, 87, 196 }; using (MemoryStream ms = new MemoryStream()) { using (RijndaelManaged AES = new RijndaelManaged()) { AES.KeySize = 256; AES.BlockSize = 128; AES.Padding = PaddingMode.Zeros; var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); AES.Key = key.GetBytes(AES.KeySize / 8); AES.IV = key.GetBytes(AES.BlockSize / 8); AES.Mode = CipherMode.CBC; using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length); } encryptedBytes = ms.ToArray(); } } return encryptedBytes; }
/// <summary> /// AES 加密 /// </summary> /// <param name="str"></param> /// <param name="key"></param> /// <returns></returns> public static byte[] AesEncrypt(byte[] str, int count_, int index_ = 0, string key = _key) { // *remark*: ignore //if (string.IsNullOrEmpty(Encoding.UTF8.GetString(str, index_, count_))) return null; //Byte[] toEncryptArray = str; byte[] toEncryptArray = new byte[count_]; Array.Copy(str, index_, toEncryptArray, 0, count_); System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged { Key = Encoding.ASCII.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 resultArray; string ret = Convert.ToBase64String(resultArray, 0, resultArray.Length); //UnityEngine.Debug.Log("<b>encrypted</b>:" + ret); //return Encoding.Default.GetBytes(ret); return(Encoding.ASCII.GetBytes(ret)); }
private static ICryptoTransform GetAesTransform(byte[] key, byte[] iv, bool decrypt) { using (SymmetricAlgorithm algorithm = new RijndaelManaged()) { return (decrypt ? algorithm.CreateDecryptor(key, iv) : algorithm.CreateEncryptor(key, iv)); } }
public void init(int mode, byte[] key, byte[] iv) { this.mode = mode; rijndael = new RijndaelManaged(); rijndael.Mode = CipherMode.ECB; rijndael.Padding = PaddingMode.None; 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; } counter = new byte[iv.Length]; Array.Copy(iv, counter, iv.Length); try { cipher = rijndael.CreateEncryptor(key, null); } catch (Exception e) { Console.WriteLine(e); cipher = null; } }
private void encryptFile(string inputFile, string cryptFile) { FileStream fsCrypt = null; CryptoStream cryptStream = null; try { UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(TPW); fsCrypt = new FileStream(cryptFile, FileMode.Create); RijndaelManaged RMCrypto = new RijndaelManaged(); cryptStream = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write); byte[] inBytes = File.ReadAllBytes(inputFile); cryptStream.Write(inBytes, 0, inBytes.Length); } finally { if (cryptStream != null) cryptStream.Close(); if ( fsCrypt != null ) fsCrypt.Close(); } }
/// <summary> /// Recibe un texto plano y lo devuelve cifrado /// Cifrado Simetrico /// </summary> /// <param name="contenido"></param> /// <param name="clave"></param> /// <returns></returns> public static String Cifrar(String contenido, String clave) { var encoding = new UTF8Encoding(); var cripto = new RijndaelManaged(); // es un algotimo de cifrado, para cifrar //var iv = cripto.GenerateIV(); // Vector de inicialización: es un vector que tiene la semilla de inicialización // Este IV byte[] cifrado; byte[] retorno; byte[] key = GetKey(clave); // recibo una clave alfanumerica y devuelvo los bytes desde una cadena UTF8 cripto.Key = key; cripto.GenerateIV(); // genera numeros aleatorios (semillas) // voy a crear el encriptador byte[] aEncriptar = encoding.GetBytes(contenido); // recibo contenido y lo convierto a array de bites // ya lo tengo cifrado cifrado = cripto.CreateEncryptor().TransformFinalBlock(aEncriptar, 0, aEncriptar.Length); // transforma el contenido desde 0 hasta que termine // creo mi retorno retorno = new byte[cripto.IV.Length + cifrado.Length]; // longitud del IV + el tamaño del cifrado cripto.IV.CopyTo(retorno, 0); // donde quiero copiar, en que posición quiero copiar cifrado.CopyTo(retorno, cripto.IV.Length); // la mejor forma es convertirlo a base 64, datos binarios, para almacenar array de bytes return Convert.ToBase64String(retorno); // conjunto de bytes transformados en string // muy util para guardar imagenes }
/// <summary> /// 有密码的AES加密 /// </summary> /// <param name="text">加密字符</param> /// <param name="password">加密的密码</param> /// <param name="iv">密钥</param> /// <returns></returns> public static string AESEncrypt(string text, string password, string iv) { var rijndaelCipher = new RijndaelManaged { Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7, KeySize = 128, BlockSize = 128 }; var pwdBytes = System.Text.Encoding.UTF8.GetBytes(password); var keyBytes = new byte[24]; var len = pwdBytes.Length; if (len > keyBytes.Length) len = keyBytes.Length; System.Array.Copy(pwdBytes, keyBytes, len); rijndaelCipher.Key = keyBytes; var ivBytes = System.Text.Encoding.UTF8.GetBytes(iv); rijndaelCipher.IV = ivBytes; var transform = rijndaelCipher.CreateEncryptor(); var plainText = Encoding.UTF8.GetBytes(text); var cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length); return Convert.ToBase64String(cipherBytes); }
public static byte[] smethod_18(byte[] byte_0, string string_0) { System.Security.Cryptography.RijndaelManaged rijndaelManaged = new System.Security.Cryptography.RijndaelManaged(); byte[] array = new byte[32]; byte[] sourceArray = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(System.Text.Encoding.ASCII.GetBytes(string_0)); System.Array.Copy(sourceArray, 0, array, 0, 16); System.Array.Copy(sourceArray, 0, array, 15, 16); rijndaelManaged.Key = array; rijndaelManaged.Mode = System.Security.Cryptography.CipherMode.ECB; System.Security.Cryptography.ICryptoTransform cryptoTransform = rijndaelManaged.CreateEncryptor(); return(cryptoTransform.TransformFinalBlock(byte_0, 0, byte_0.Length)); }
/// <summary> /// 文字列を暗号化する /// </summary> /// <param name="sourceString">暗号化する文字列</param> /// <returns>暗号化された文字列</returns> public static string EncryptString(string sourceString) { //文字列をバイト型配列に変換する byte[] strBytes = System.Text.Encoding.UTF8.GetBytes(sourceString); //対称暗号化オブジェクトの作成 System.Security.Cryptography.ICryptoTransform encryptor = rijndael.CreateEncryptor(); //バイト型配列を暗号化する byte[] encBytes = encryptor.TransformFinalBlock(strBytes, 0, strBytes.Length); //閉じる encryptor.Dispose(); //バイト型配列を文字列に変換して返す return(System.Convert.ToBase64String(encBytes)); }
/// <summary> /// AES 加密 /// </summary> /// <param name="str">明文(待加密)</param> /// <param name="key">密文</param> /// <returns></returns> public static byte[] AesEncrypt(byte[] str, byte[] key) { byte[] toEncryptArray = str; System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged { Key = key.Take(32).ToArray(), Mode = System.Security.Cryptography.CipherMode.ECB, Padding = System.Security.Cryptography.PaddingMode.Zeros }; System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return(resultArray); }
public static String AESEncrypt(String value, String key) { Byte[] toEncryptArray = Encoding.UTF8.GetBytes(value); byte[] keyBytes = Convert.FromBase64String(key); System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged { Key = keyBytes, 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)); }
public static byte[] AESEncrypt(byte[] encryptBytes, string key) { if (encryptBytes != null && encryptBytes.Length > 0) { byte[] keyArray = Encoding.UTF8.GetBytes(key); 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.CreateEncryptor(); return(cTransform.TransformFinalBlock(encryptBytes, 0, encryptBytes.Length)); } else { return(new byte[0]); } }
public string Encrypt(string text, string key) { IsValid(text, key); Byte[] toEncryptArray = Encoding.UTF8.GetBytes(text); 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)); }
private static string AesEncrypt(string toEncrypt, string key) { byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt); System.Security.Cryptography.RijndaelManaged rDel = new System.Security.Cryptography.RijndaelManaged(); rDel.Key = SHA256(key); rDel.Mode = System.Security.Cryptography.CipherMode.CBC; rDel.Padding = System.Security.Cryptography.PaddingMode.PKCS7; rDel.BlockSize = 128; byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; rDel.IV = iv; System.Security.Cryptography.ICryptoTransform cTransform = rDel.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return(Convert.ToBase64String(resultArray, 0, resultArray.Length)); }
byte[] Transform(byte[] dataBytes, byte[] passwordBytes, bool encrypt) { /// <summary>Encrypt by using AES-256 algorithm.</summary> // Create an instance of the Rijndael class. var cipher = new System.Security.Cryptography.RijndaelManaged(); // Calculate salt to make it harder to guess key by using a dictionary attack. var hmac = new System.Security.Cryptography.HMACSHA1(passwordBytes); var salt = hmac.ComputeHash(passwordBytes); // Generate Secret Key from the password and salt. // Note: Set number of iterations to 10 in order for JavaScript example to work faster. var secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(passwordBytes, salt, 10); // Create a encryptor from the existing SecretKey bytes by using // 32 bytes (256 bits) for the secret key and // 16 bytes (128 bits) for the initialization vector (IV). var key = secretKey.GetBytes(32); var iv = secretKey.GetBytes(16); // Get cryptor as System.Security.Cryptography.ICryptoTransform class. var cryptor = encrypt ? cipher.CreateEncryptor(key, iv) : cipher.CreateDecryptor(key, iv); // Create new Input. var inputBuffer = new byte[dataBytes.Length]; // Copy data bytes to input buffer. System.Buffer.BlockCopy(dataBytes, 0, inputBuffer, 0, inputBuffer.Length); // Create a MemoryStream to hold the output bytes. var stream = new System.IO.MemoryStream(); // Create a CryptoStream through which we are going to be processing our data. var mode = System.Security.Cryptography.CryptoStreamMode.Write; var cryptoStream = new System.Security.Cryptography.CryptoStream(stream, cryptor, mode); // Start the crypting process. cryptoStream.Write(inputBuffer, 0, inputBuffer.Length); // Finish crypting. cryptoStream.FlushFinalBlock(); // Convert data from a memoryStream into a byte array. var outputBuffer = stream.ToArray(); // Close both streams. stream.Close(); cryptoStream.Close(); return(outputBuffer); }