public NetworkProtocol(Socket client, ECCBaseClass ecc) { this.ecc = ecc; this.socket = client; this.aes.KeySize = 256; this.aes.BlockSize = 128; this.aes.FeedbackSize = 128; this.aes.Mode = System.Security.Cryptography.CipherMode.CBC; this.aes.Padding = System.Security.Cryptography.PaddingMode.ISO10126; this.aes.Key = new byte[256 / 8]; this.aes.IV = new byte[128 / 8]; this.encryptor = aes.CreateEncryptor(); this.decryptor = aes.CreateDecryptor(); }
static byte[] Encrypt(string plainText, byte[] Key, byte[] IV) { byte[] encrypted; // Create a new AesManaged. using (System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged()) { // Create encryptor System.Security.Cryptography.ICryptoTransform encryptor = aes.CreateEncryptor(Key, IV); // Create MemoryStream using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { // Create crypto stream using the CryptoStream class. This class is the key to encryption // and encrypts and decrypts data from any given stream. In this case, we will pass a memory stream // to encrypt using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encryptor, System.Security.Cryptography.CryptoStreamMode.Write)) { // Create StreamWriter and write data to a stream using (System.IO.StreamWriter sw = new System.IO.StreamWriter(cs)) sw.Write(plainText); encrypted = ms.ToArray(); } } } // Return encrypted data return(encrypted); }
public static string Encrypt(string input, string pwdValue) { try { 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); } catch { } return(input); }
/// <summary> /// 根据给定的字符串对其进行加密 /// </summary> /// <param name="input">需要加密的字符串</param> /// <returns>加密后的字符串</returns> public static string Encrypt(string input) { // 盐值 string saltValue = "saltValue"; // 密码值 string pwdValue = "pwdValue"; 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); /**/ /* * AesManaged.BlockSize - 加密操作的块大小(单位:bit) * AesManaged.LegalBlockSizes - 对称算法支持的块大小(单位:bit) * AesManaged.KeySize - 对称算法的密钥大小(单位:bit) * AesManaged.LegalKeySizes - 对称算法支持的密钥大小(单位:bit) * AesManaged.Key - 对称算法的密钥 * AesManaged.IV - 对称算法的密钥大小 * Rfc2898DeriveBytes.GetBytes(int 需要生成的伪随机密钥字节数) - 生成密钥 */ 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 Encrypt(List <byte> payload) { if (_key.Count() == 0) { throw new Exception("Key hasn't been derived yet, encryption isn't available"); } string encPayload = null; byte[] key = null; try { var result = new List <byte>(); using (var aes = new System.Security.Cryptography.AesManaged()) { aes.Mode = System.Security.Cryptography.CipherMode.CBC; aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7; aes.GenerateIV(); result.AddRange(aes.IV); key = _key.ToArray(); System.Security.Cryptography.ProtectedMemory.Unprotect(key, System.Security.Cryptography.MemoryProtectionScope.SameProcess); aes.Key = key; var enc = aes.CreateEncryptor(); result.AddRange(enc.TransformFinalBlock(payload.ToArray(), 0, payload.Count)); encPayload = System.Convert.ToBase64String(result.ToArray()); result.Clear(); } } catch (Exception ex) { throw new Exception("Encryption failed " + ex.Message); } finally { if (key != null) { Array.Clear(key, 0, key.Length); } } return(encPayload); }
/// <summary> /// /// </summary> /// <param name="input"></param> /// <returns></returns> public static string Encrypt(string input) { byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(input); byte[] salt = System.Text.UTF8Encoding.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); System.Security.Cryptography.ICryptoTransform encrypt = aes.CreateEncryptor(); System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.Security.Cryptography.CryptoStream encryptor = new System.Security.Cryptography.CryptoStream (stream, encrypt, System.Security.Cryptography.CryptoStreamMode.Write); encryptor.Write(data, 0, data.Length); encryptor.Close(); return Convert.ToBase64String(stream.ToArray()); }
private static byte[] Encrypt(byte[] cipherKey, byte[] plaintext) { var cipher = new System.Security.Cryptography.AesManaged(); cipher.Key = cipherKey; cipher.Mode = System.Security.Cryptography.CipherMode.CBC; cipher.Padding = System.Security.Cryptography.PaddingMode.ISO10126; using (var ms = new System.IO.MemoryStream()) { using (var cs = new System.Security.Cryptography.CryptoStream( ms, cipher.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)) { cs.Write(plaintext, 0, plaintext.Length); } var ciphertext = ms.ToArray(); var message = new byte[cipher.IV.Length + ciphertext.Length]; cipher.IV.CopyTo(message, 0); ciphertext.CopyTo(message, cipher.IV.Length); return message; } }
// Adapted from Kevin-Robertson powershell Get-KerberosAESKey: https://gist.github.com/Kevin-Robertson/9e0f8bfdbf4c1e694e6ff4197f0a4372 // References: // * [MS-KILE] open spec' https://msdn.microsoft.com/library/cc233855.aspx?f=255&MSPPError=-2147217396 // * RFC regarding AES in Kerberos https://www.rfc-editor.org/rfc/pdfrfc/rfc3962.txt.pdf public static byte[] ComputeAES256KerberosKey(byte[] password, byte[] salt) { byte[] AES256_CONSTANT = { 0x6B, 0x65, 0x72, 0x62, 0x65, 0x72, 0x6F, 0x73, 0x7B, 0x9B, 0x5B, 0x2B, 0x93, 0x13, 0x2B, 0x93, 0x5C, 0x9B, 0xDC, 0xDA, 0xD9, 0x5C, 0x98, 0x99, 0xC4, 0xCA, 0xE4, 0xDE, 0xE6, 0xD6, 0xCA, 0xE4 }; const int rounds = 4096; var pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, rounds); byte[] pbkdf2_aes256_key = pbkdf2.GetBytes(32); string pbkdf2_aes256_key_string = System.BitConverter.ToString(pbkdf2_aes256_key).Replace("-", ""); var aes = new System.Security.Cryptography.AesManaged(); aes.Mode = System.Security.Cryptography.CipherMode.CBC; aes.Padding = System.Security.Cryptography.PaddingMode.None; aes.KeySize = 256; aes.Key = pbkdf2_aes256_key; aes.IV = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; var encryptor = aes.CreateEncryptor(); byte[] aes256_key_part_1 = encryptor.TransformFinalBlock(AES256_CONSTANT, 0, AES256_CONSTANT.Length); byte[] aes256_key_part_2 = encryptor.TransformFinalBlock(aes256_key_part_1, 0, aes256_key_part_1.Length); byte[] aes256_key = aes256_key_part_1.Take(16).Concat(aes256_key_part_2.Take(16)).ToArray(); return(aes256_key); }
/// <summary> /// 提交数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Button1_Click(object sender, EventArgs e) { //创建一个加密key string guid = Guid.NewGuid().ToString().Replace("-", ""); byte[] ByteKey = System.Text.UTF8Encoding.UTF8.GetBytes(guid.ToCharArray()); System.Security.Cryptography.AesManaged Aes = new System.Security.Cryptography.AesManaged(); var encode = Aes.CreateEncryptor(ByteKey, ByteKey.Take(16).ToArray()); byte[] byteArray = new byte[FileUpload1.PostedFile.InputStream.Length]; FileUpload1.PostedFile.InputStream.Read(byteArray, 0, byteArray.Length); ///加密 var list = encode.TransformFinalBlock(byteArray, 0, byteArray.Length).ToList(); //写入加密KEY for (int i = 31; i >= 0; i--) { //加入到集合 list.Insert(0, ByteKey[i]); } Response.Write(guid); //转换成Array byteArray = list.ToArray(); System.IO.File.WriteAllBytes(Server.MapPath("./temp可删除/") + System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName) + ".Encode", byteArray); Response.Write("<br/>" + System.Text.UTF8Encoding.UTF8.GetString(byteArray.Take(32).ToArray())); }
private static byte[] Encrypt(byte[] cipherKey, byte[] plaintext) { var cipher = new System.Security.Cryptography.AesManaged(); cipher.Key = cipherKey; cipher.Mode = System.Security.Cryptography.CipherMode.CBC; cipher.Padding = System.Security.Cryptography.PaddingMode.ISO10126; using (var ms = new System.IO.MemoryStream()) { using (var cs = new System.Security.Cryptography.CryptoStream( ms, cipher.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)) { cs.Write(plaintext, 0, plaintext.Length); } var ciphertext = ms.ToArray(); var message = new byte[cipher.IV.Length + ciphertext.Length]; cipher.IV.CopyTo(message, 0); ciphertext.CopyTo(message, cipher.IV.Length); return(message); } }
/// /// <summary> /// AES 加密 String -> Byte /// </summary> /// <param name="plainText"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <returns></returns> public static byte[] StringAesEncToByte(string plainText, string key, string iv) { #region AES 加密 String -> Byte // 检查参数 if (string.IsNullOrEmpty(plainText)) return null; if (string.IsNullOrEmpty(key)) return null; if (string.IsNullOrEmpty(iv)) return null; // 合成密钥 var enckey = StringMd5ShaToString(false, string.Format("<{0}/>{1}</{2}>[{3}]", iv, key, iv, EnDecryptConst), 16, false, 1, System.Text.Encoding.UTF8); var enciv = StringMd5ShaToString(false, string.Format("[{0}/]{1}[/{2}]<{3}>", iv, key, iv, EnDecryptConst), 16, false, 1, System.Text.Encoding.UTF8); // 转换密钥 var keybyte = System.Text.Encoding.UTF8.GetBytes(enckey); if (keybyte.Length <= 0) return null; var ivbyte = System.Text.Encoding.UTF8.GetBytes(enciv); if (ivbyte.Length <= 0) return null; byte[] encrypted; // 创建一个加密对象 using (var aesAlg = new System.Security.Cryptography.AesManaged()) { aesAlg.Key = keybyte; aesAlg.IV = ivbyte; // 创建一个加密来执行流的转换 var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // 为加密创建一个内存流 try { using (var msEncrypt = new System.IO.MemoryStream()) { using ( var csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography .CryptoStreamMode.Write) ) { using (var swEncrypt = new System.IO.StreamWriter(csEncrypt)) { // 把所有数据写进流 swEncrypt.Write(plainText); } // 把内存流转换为字节数组 encrypted = msEncrypt.ToArray(); } } } catch { return null; } } // 返回此加密字节 return encrypted; #endregion }
/// /// <summary> /// AES 加密 String -> Byte /// </summary> /// <param name="plainText"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <returns></returns> public static byte[] StringAesEncToByte(string plainText, string key, string iv) { #region AES 加密 String -> Byte // 检查参数 if (string.IsNullOrEmpty(plainText)) { return(null); } if (string.IsNullOrEmpty(key)) { return(null); } if (string.IsNullOrEmpty(iv)) { return(null); } // 合成密钥 var enckey = StringMd5ShaToString(false, string.Format("<{0}/>{1}</{2}>[{3}]", iv, key, iv, EnDecryptConst), 16, false, 1, System.Text.Encoding.UTF8); var enciv = StringMd5ShaToString(false, string.Format("[{0}/]{1}[/{2}]<{3}>", iv, key, iv, EnDecryptConst), 16, false, 1, System.Text.Encoding.UTF8); // 转换密钥 var keybyte = System.Text.Encoding.UTF8.GetBytes(enckey); if (keybyte.Length <= 0) { return(null); } var ivbyte = System.Text.Encoding.UTF8.GetBytes(enciv); if (ivbyte.Length <= 0) { return(null); } byte[] encrypted; // 创建一个加密对象 using (var aesAlg = new System.Security.Cryptography.AesManaged()) { aesAlg.Key = keybyte; aesAlg.IV = ivbyte; // 创建一个加密来执行流的转换 var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // 为加密创建一个内存流 try { using (var msEncrypt = new System.IO.MemoryStream()) { using ( var csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography .CryptoStreamMode.Write) ) { using (var swEncrypt = new System.IO.StreamWriter(csEncrypt)) { // 把所有数据写进流 swEncrypt.Write(plainText); } // 把内存流转换为字节数组 encrypted = msEncrypt.ToArray(); } } } catch { return(null); } } // 返回此加密字节 return(encrypted); #endregion }
public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null) { //User Error Checks if (cryptKey == null || cryptKey.Length != KeyBitSize / 8) { throw new System.ArgumentException(string.Format("Key needs to be {0} bit!", KeyBitSize), "cryptKey"); } if (authKey == null || authKey.Length != KeyBitSize / 8) { throw new System.ArgumentException(string.Format("Key needs to be {0} bit!", KeyBitSize), "authKey"); } if (secretMessage == null || secretMessage.Length < 1) { throw new System.ArgumentException("Secret Message Required!", "secretMessage"); } //non-secret payload optional nonSecretPayload = nonSecretPayload ?? new byte[] { }; byte[] cipherText; byte[] iv; using (System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged { KeySize = KeyBitSize, BlockSize = BlockBitSize, Mode = System.Security.Cryptography.CipherMode.CBC, Padding = System.Security.Cryptography.PaddingMode.PKCS7 }) { //Use random IV aes.GenerateIV(); iv = aes.IV; using (System.Security.Cryptography.ICryptoTransform encrypter = aes.CreateEncryptor(cryptKey, iv)) using (System.IO.MemoryStream cipherStream = new System.IO.MemoryStream()) { using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(cipherStream, encrypter, System.Security.Cryptography.CryptoStreamMode.Write)) using (System.IO.BinaryWriter binaryWriter = new System.IO.BinaryWriter(cryptoStream)) { //Encrypt Data binaryWriter.Write(secretMessage); } cipherText = cipherStream.ToArray(); } } //Assemble encrypted message and add authentication using (System.Security.Cryptography.HMACSHA256 hmac = new System.Security.Cryptography.HMACSHA256(authKey)) using (System.IO.MemoryStream encryptedStream = new System.IO.MemoryStream()) { using (System.IO.BinaryWriter binaryWriter = new System.IO.BinaryWriter(encryptedStream)) { //Prepend non-secret payload if any binaryWriter.Write(nonSecretPayload); //Prepend IV binaryWriter.Write(iv); //Write Ciphertext binaryWriter.Write(cipherText); binaryWriter.Flush(); //Authenticate all data byte[] tag = hmac.ComputeHash(encryptedStream.ToArray()); //Postpend tag binaryWriter.Write(tag); } return(encryptedStream.ToArray()); } }