#1 楼
EDIT 2013年10月:尽管我已经为解决缺点而逐步编辑了此答案,但请参阅jbtule的答案以获取更可靠,更明智的解决方案。https://stackoverflow.com/a/10366194/ 188474
原始答案:
这是一个有效的示例,该示例源自“ RijndaelManaged Class”文档和MCTS培训套件。
编辑2012年4月:对该答案进行了编辑,以便在jbtule的建议之前添加IV,如下所示:
http://msdn.microsoft.com/en -us / library / system.security.cryptography.aesmanaged%28v = vs.95%29.aspx
祝你好运!
public class Crypto
{
//While an app specific salt is not the best practice for
//password based encryption, it's probably safe enough as long as
//it is truly uncommon. Also too much work to alter this answer otherwise.
private static byte[] _salt = __To_Do__("Add a app specific salt here");
/// <summary>
/// Encrypt the given string using AES. The string can be decrypted using
/// DecryptStringAES(). The sharedSecret parameters must match.
/// </summary>
/// <param name="plainText">The text to encrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for encryption.</param>
public static string EncryptStringAES(string plainText, string sharedSecret)
{
if (string.IsNullOrEmpty(plainText))
throw new ArgumentNullException("plainText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
string outStr = null; // Encrypted string to return
RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create a RijndaelManaged object
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
// Create a decryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
// prepend the IV
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))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
}
outStr = Convert.ToBase64String(msEncrypt.ToArray());
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
// Return the encrypted bytes from the memory stream.
return outStr;
}
/// <summary>
/// Decrypt the given string. Assumes the string was encrypted using
/// EncryptStringAES(), using an identical sharedSecret.
/// </summary>
/// <param name="cipherText">The text to decrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for decryption.</param>
public static string DecryptStringAES(string cipherText, string sharedSecret)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException("cipherText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
// Declare the RijndaelManaged object
// used to decrypt the data.
RijndaelManaged aesAlg = null;
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create the streams used for decryption.
byte[] bytes = Convert.FromBase64String(cipherText);
using (MemoryStream msDecrypt = new MemoryStream(bytes))
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
// Get the initialization vector from the encrypted stream
aesAlg.IV = ReadByteArray(msDecrypt);
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
return plaintext;
}
private static byte[] ReadByteArray(Stream s)
{
byte[] rawLength = new byte[sizeof(int)];
if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
{
throw new SystemException("Stream did not contain properly formatted byte array");
}
byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
{
throw new SystemException("Did not read byte array properly");
}
return buffer;
}
}
评论
To Bret-您好,谢谢。也许有人认为-我对密钥长度有问题-我对MD5进行了修改,所以如果有人在功能部件中使用您的示例,请使用此示例进行密钥规范化(或者您可以使用其他哈希算法:HashAlgorithm hash = new MD5CryptoServiceProvider(); UnicodeEncoding UE =新的UnicodeEncoding(); byte []键= hash.ComputeHash(UE.GetBytes(encrypt_password)); ps:对不起,我的英语:) slinti
–user593912
2011年1月29日16:19
上面的代码是不安全的,它破坏了aes语义安全的最基本规则,您永远不要使用同一密钥多次使用同一IV。每当您使用相同的密钥时,这总是给出相同的IV。
– jbtule
2012年4月24日在22:54
在密钥派生过程中使用盐不会造成伤害。常量不是很好的盐,就像常量不是很好的IV一样。
– CodesInChaos
13年8月14日在15:48
关于AES与Rijndael的混淆:AES是Rijndael的子集。如果将Rijndael与128位块和128、192或256位密钥一起使用,则使用的是AES。
– CodesInChaos
13年8月14日在15:50
盐增加了混淆度,以防止破裂。建议您阅读下面生成盐的jbtules示例。
–布雷特
2014年10月6日20:16
#2 楼
字符串的对称身份验证加密的现代示例。对称加密的一般最佳实践是使用带有关联数据的身份验证加密(AEAD),但这不是标准.net加密库的一部分。因此,第一个示例使用AES256,然后使用HMAC256(两步加密,然后是MAC),这需要更多的开销和更多的密钥。
第二个示例使用更简单的AES256-GCM实践,使用开源Bouncy Castle (通过nuget)。两个示例都具有一个主要功能,该功能接收秘密消息字符串,密钥和可选的非秘密有效载荷,并返回和经过身份验证的加密字符串,并可选地以非秘密数据为前缀。理想情况下,您可以将它们与随机生成的256位密钥一起使用,请参见
NewKey()
。两个示例还具有使用字符串密码来生成密钥的辅助方法。提供这些帮助程序方法是为了方便与其他示例匹配,但是它们的安全性要差得多,因为密码的强度将远小于256位密钥。更新:
添加了
byte[]
重载,由于StackOverflow的答案限制,只有Gist才具有4个空格的缩进和api文档的完整格式。.NET内置加密(AES)- Then-MAC(HMAC)[要点]
/*
* This work (Modern Encryption of a String C#, by James Tuley),
* identified by James Tuley, is free of known copyright restrictions.
* https://gist.github.com/4336842
* http://creativecommons.org/publicdomain/mark/1.0/
*/
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Encryption
{
public static class AESThenHMAC
{
private static readonly RandomNumberGenerator Random = RandomNumberGenerator.Create();
//Preconfigured Encryption Parameters
public static readonly int BlockBitSize = 128;
public static readonly int KeyBitSize = 256;
//Preconfigured Password Key Derivation Parameters
public static readonly int SaltBitSize = 64;
public static readonly int Iterations = 10000;
public static readonly int MinPasswordLength = 12;
/// <summary>
/// Helper that generates a random key on each call.
/// </summary>
/// <returns></returns>
public static byte[] NewKey()
{
var key = new byte[KeyBitSize / 8];
Random.GetBytes(key);
return key;
}
/// <summary>
/// Simple Encryption (AES) then Authentication (HMAC) for a UTF8 Message.
/// </summary>
/// <param name="secretMessage">The secret message.</param>
/// <param name="cryptKey">The crypt key.</param>
/// <param name="authKey">The auth key.</param>
/// <param name="nonSecretPayload">(Optional) Non-Secret Payload.</param>
/// <returns>
/// Encrypted Message
/// </returns>
/// <exception cref="System.ArgumentException">Secret Message Required!;secretMessage</exception>
/// <remarks>
/// Adds overhead of (Optional-Payload + BlockSize(16) + Message-Padded-To-Blocksize + HMac-Tag(32)) * 1.33 Base64
/// </remarks>
public static string SimpleEncrypt(string secretMessage, byte[] cryptKey, byte[] authKey,
byte[] nonSecretPayload = null)
{
if (string.IsNullOrEmpty(secretMessage))
throw new ArgumentException("Secret Message Required!", "secretMessage");
var plainText = Encoding.UTF8.GetBytes(secretMessage);
var cipherText = SimpleEncrypt(plainText, cryptKey, authKey, nonSecretPayload);
return Convert.ToBase64String(cipherText);
}
/// <summary>
/// Simple Authentication (HMAC) then Decryption (AES) for a secrets UTF8 Message.
/// </summary>
/// <param name="encryptedMessage">The encrypted message.</param>
/// <param name="cryptKey">The crypt key.</param>
/// <param name="authKey">The auth key.</param>
/// <param name="nonSecretPayloadLength">Length of the non secret payload.</param>
/// <returns>
/// Decrypted Message
/// </returns>
/// <exception cref="System.ArgumentException">Encrypted Message Required!;encryptedMessage</exception>
public static string SimpleDecrypt(string encryptedMessage, byte[] cryptKey, byte[] authKey,
int nonSecretPayloadLength = 0)
{
if (string.IsNullOrWhiteSpace(encryptedMessage))
throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
var cipherText = Convert.FromBase64String(encryptedMessage);
var plainText = SimpleDecrypt(cipherText, cryptKey, authKey, nonSecretPayloadLength);
return plainText == null ? null : Encoding.UTF8.GetString(plainText);
}
/// <summary>
/// Simple Encryption (AES) then Authentication (HMAC) of a UTF8 message
/// using Keys derived from a Password (PBKDF2).
/// </summary>
/// <param name="secretMessage">The secret message.</param>
/// <param name="password">The password.</param>
/// <param name="nonSecretPayload">The non secret payload.</param>
/// <returns>
/// Encrypted Message
/// </returns>
/// <exception cref="System.ArgumentException">password</exception>
/// <remarks>
/// Significantly less secure than using random binary keys.
/// Adds additional non secret payload for key generation parameters.
/// </remarks>
public static string SimpleEncryptWithPassword(string secretMessage, string password,
byte[] nonSecretPayload = null)
{
if (string.IsNullOrEmpty(secretMessage))
throw new ArgumentException("Secret Message Required!", "secretMessage");
var plainText = Encoding.UTF8.GetBytes(secretMessage);
var cipherText = SimpleEncryptWithPassword(plainText, password, nonSecretPayload);
return Convert.ToBase64String(cipherText);
}
/// <summary>
/// Simple Authentication (HMAC) and then Descryption (AES) of a UTF8 Message
/// using keys derived from a password (PBKDF2).
/// </summary>
/// <param name="encryptedMessage">The encrypted message.</param>
/// <param name="password">The password.</param>
/// <param name="nonSecretPayloadLength">Length of the non secret payload.</param>
/// <returns>
/// Decrypted Message
/// </returns>
/// <exception cref="System.ArgumentException">Encrypted Message Required!;encryptedMessage</exception>
/// <remarks>
/// Significantly less secure than using random binary keys.
/// </remarks>
public static string SimpleDecryptWithPassword(string encryptedMessage, string password,
int nonSecretPayloadLength = 0)
{
if (string.IsNullOrWhiteSpace(encryptedMessage))
throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
var cipherText = Convert.FromBase64String(encryptedMessage);
var plainText = SimpleDecryptWithPassword(cipherText, password, nonSecretPayloadLength);
return plainText == null ? null : Encoding.UTF8.GetString(plainText);
}
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 ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "cryptKey");
if (authKey == null || authKey.Length != KeyBitSize / 8)
throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "authKey");
if (secretMessage == null || secretMessage.Length < 1)
throw new ArgumentException("Secret Message Required!", "secretMessage");
//non-secret payload optional
nonSecretPayload = nonSecretPayload ?? new byte[] { };
byte[] cipherText;
byte[] iv;
using (var aes = new AesManaged
{
KeySize = KeyBitSize,
BlockSize = BlockBitSize,
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7
})
{
//Use random IV
aes.GenerateIV();
iv = aes.IV;
using (var encrypter = aes.CreateEncryptor(cryptKey, iv))
using (var cipherStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write))
using (var binaryWriter = new BinaryWriter(cryptoStream))
{
//Encrypt Data
binaryWriter.Write(secretMessage);
}
cipherText = cipherStream.ToArray();
}
}
//Assemble encrypted message and add authentication
using (var hmac = new HMACSHA256(authKey))
using (var encryptedStream = new MemoryStream())
{
using (var binaryWriter = new 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
var tag = hmac.ComputeHash(encryptedStream.ToArray());
//Postpend tag
binaryWriter.Write(tag);
}
return encryptedStream.ToArray();
}
}
public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] cryptKey, byte[] authKey, int nonSecretPayloadLength = 0)
{
//Basic Usage Error Checks
if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)
throw new ArgumentException(String.Format("CryptKey needs to be {0} bit!", KeyBitSize), "cryptKey");
if (authKey == null || authKey.Length != KeyBitSize / 8)
throw new ArgumentException(String.Format("AuthKey needs to be {0} bit!", KeyBitSize), "authKey");
if (encryptedMessage == null || encryptedMessage.Length == 0)
throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
using (var hmac = new HMACSHA256(authKey))
{
var sentTag = new byte[hmac.HashSize / 8];
//Calculate Tag
var calcTag = hmac.ComputeHash(encryptedMessage, 0, encryptedMessage.Length - sentTag.Length);
var ivLength = (BlockBitSize / 8);
//if message length is to small just return null
if (encryptedMessage.Length < sentTag.Length + nonSecretPayloadLength + ivLength)
return null;
//Grab Sent Tag
Array.Copy(encryptedMessage, encryptedMessage.Length - sentTag.Length, sentTag, 0, sentTag.Length);
//Compare Tag with constant time comparison
var compare = 0;
for (var i = 0; i < sentTag.Length; i++)
compare |= sentTag[i] ^ calcTag[i];
//if message doesn't authenticate return null
if (compare != 0)
return null;
using (var aes = new AesManaged
{
KeySize = KeyBitSize,
BlockSize = BlockBitSize,
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7
})
{
//Grab IV from message
var iv = new byte[ivLength];
Array.Copy(encryptedMessage, nonSecretPayloadLength, iv, 0, iv.Length);
using (var decrypter = aes.CreateDecryptor(cryptKey, iv))
using (var plainTextStream = new MemoryStream())
{
using (var decrypterStream = new CryptoStream(plainTextStream, decrypter, CryptoStreamMode.Write))
using (var binaryWriter = new BinaryWriter(decrypterStream))
{
//Decrypt Cipher Text from Message
binaryWriter.Write(
encryptedMessage,
nonSecretPayloadLength + iv.Length,
encryptedMessage.Length - nonSecretPayloadLength - iv.Length - sentTag.Length
);
}
//Return Plain Text
return plainTextStream.ToArray();
}
}
}
}
public static byte[] SimpleEncryptWithPassword(byte[] secretMessage, string password, byte[] nonSecretPayload = null)
{
nonSecretPayload = nonSecretPayload ?? new byte[] {};
//User Error Checks
if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)
throw new ArgumentException(String.Format("Must have a password of at least {0} characters!", MinPasswordLength), "password");
if (secretMessage == null || secretMessage.Length ==0)
throw new ArgumentException("Secret Message Required!", "secretMessage");
var payload = new byte[((SaltBitSize / 8) * 2) + nonSecretPayload.Length];
Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length);
int payloadIndex = nonSecretPayload.Length;
byte[] cryptKey;
byte[] authKey;
//Use Random Salt to prevent pre-generated weak password attacks.
using (var generator = new Rfc2898DeriveBytes(password, SaltBitSize / 8, Iterations))
{
var salt = generator.Salt;
//Generate Keys
cryptKey = generator.GetBytes(KeyBitSize / 8);
//Create Non Secret Payload
Array.Copy(salt, 0, payload, payloadIndex, salt.Length);
payloadIndex += salt.Length;
}
//Deriving separate key, might be less efficient than using HKDF,
//but now compatible with RNEncryptor which had a very similar wireformat and requires less code than HKDF.
using (var generator = new Rfc2898DeriveBytes(password, SaltBitSize / 8, Iterations))
{
var salt = generator.Salt;
//Generate Keys
authKey = generator.GetBytes(KeyBitSize / 8);
//Create Rest of Non Secret Payload
Array.Copy(salt, 0, payload, payloadIndex, salt.Length);
}
return SimpleEncrypt(secretMessage, cryptKey, authKey, payload);
}
public static byte[] SimpleDecryptWithPassword(byte[] encryptedMessage, string password, int nonSecretPayloadLength = 0)
{
//User Error Checks
if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)
throw new ArgumentException(String.Format("Must have a password of at least {0} characters!", MinPasswordLength), "password");
if (encryptedMessage == null || encryptedMessage.Length == 0)
throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
var cryptSalt = new byte[SaltBitSize / 8];
var authSalt = new byte[SaltBitSize / 8];
//Grab Salt from Non-Secret Payload
Array.Copy(encryptedMessage, nonSecretPayloadLength, cryptSalt, 0, cryptSalt.Length);
Array.Copy(encryptedMessage, nonSecretPayloadLength + cryptSalt.Length, authSalt, 0, authSalt.Length);
byte[] cryptKey;
byte[] authKey;
//Generate crypt key
using (var generator = new Rfc2898DeriveBytes(password, cryptSalt, Iterations))
{
cryptKey = generator.GetBytes(KeyBitSize / 8);
}
//Generate auth key
using (var generator = new Rfc2898DeriveBytes(password, authSalt, Iterations))
{
authKey = generator.GetBytes(KeyBitSize / 8);
}
return SimpleDecrypt(encryptedMessage, cryptKey, authKey, cryptSalt.Length + authSalt.Length + nonSecretPayloadLength);
}
}
}
Bouncy Castle AES-GCM [要点]
/*
* This work (Modern Encryption of a String C#, by James Tuley),
* identified by James Tuley, is free of known copyright restrictions.
* https://gist.github.com/4336842
* http://creativecommons.org/publicdomain/mark/1.0/
*/
using System;
using System.IO;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
namespace Encryption
{
public static class AESGCM
{
private static readonly SecureRandom Random = new SecureRandom();
//Preconfigured Encryption Parameters
public static readonly int NonceBitSize = 128;
public static readonly int MacBitSize = 128;
public static readonly int KeyBitSize = 256;
//Preconfigured Password Key Derivation Parameters
public static readonly int SaltBitSize = 128;
public static readonly int Iterations = 10000;
public static readonly int MinPasswordLength = 12;
/// <summary>
/// Helper that generates a random new key on each call.
/// </summary>
/// <returns></returns>
public static byte[] NewKey()
{
var key = new byte[KeyBitSize / 8];
Random.NextBytes(key);
return key;
}
/// <summary>
/// Simple Encryption And Authentication (AES-GCM) of a UTF8 string.
/// </summary>
/// <param name="secretMessage">The secret message.</param>
/// <param name="key">The key.</param>
/// <param name="nonSecretPayload">Optional non-secret payload.</param>
/// <returns>
/// Encrypted Message
/// </returns>
/// <exception cref="System.ArgumentException">Secret Message Required!;secretMessage</exception>
/// <remarks>
/// Adds overhead of (Optional-Payload + BlockSize(16) + Message + HMac-Tag(16)) * 1.33 Base64
/// </remarks>
public static string SimpleEncrypt(string secretMessage, byte[] key, byte[] nonSecretPayload = null)
{
if (string.IsNullOrEmpty(secretMessage))
throw new ArgumentException("Secret Message Required!", "secretMessage");
var plainText = Encoding.UTF8.GetBytes(secretMessage);
var cipherText = SimpleEncrypt(plainText, key, nonSecretPayload);
return Convert.ToBase64String(cipherText);
}
/// <summary>
/// Simple Decryption & Authentication (AES-GCM) of a UTF8 Message
/// </summary>
/// <param name="encryptedMessage">The encrypted message.</param>
/// <param name="key">The key.</param>
/// <param name="nonSecretPayloadLength">Length of the optional non-secret payload.</param>
/// <returns>Decrypted Message</returns>
public static string SimpleDecrypt(string encryptedMessage, byte[] key, int nonSecretPayloadLength = 0)
{
if (string.IsNullOrEmpty(encryptedMessage))
throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
var cipherText = Convert.FromBase64String(encryptedMessage);
var plainText = SimpleDecrypt(cipherText, key, nonSecretPayloadLength);
return plainText == null ? null : Encoding.UTF8.GetString(plainText);
}
/// <summary>
/// Simple Encryption And Authentication (AES-GCM) of a UTF8 String
/// using key derived from a password (PBKDF2).
/// </summary>
/// <param name="secretMessage">The secret message.</param>
/// <param name="password">The password.</param>
/// <param name="nonSecretPayload">The non secret payload.</param>
/// <returns>
/// Encrypted Message
/// </returns>
/// <remarks>
/// Significantly less secure than using random binary keys.
/// Adds additional non secret payload for key generation parameters.
/// </remarks>
public static string SimpleEncryptWithPassword(string secretMessage, string password,
byte[] nonSecretPayload = null)
{
if (string.IsNullOrEmpty(secretMessage))
throw new ArgumentException("Secret Message Required!", "secretMessage");
var plainText = Encoding.UTF8.GetBytes(secretMessage);
var cipherText = SimpleEncryptWithPassword(plainText, password, nonSecretPayload);
return Convert.ToBase64String(cipherText);
}
/// <summary>
/// Simple Decryption and Authentication (AES-GCM) of a UTF8 message
/// using a key derived from a password (PBKDF2)
/// </summary>
/// <param name="encryptedMessage">The encrypted message.</param>
/// <param name="password">The password.</param>
/// <param name="nonSecretPayloadLength">Length of the non secret payload.</param>
/// <returns>
/// Decrypted Message
/// </returns>
/// <exception cref="System.ArgumentException">Encrypted Message Required!;encryptedMessage</exception>
/// <remarks>
/// Significantly less secure than using random binary keys.
/// </remarks>
public static string SimpleDecryptWithPassword(string encryptedMessage, string password,
int nonSecretPayloadLength = 0)
{
if (string.IsNullOrWhiteSpace(encryptedMessage))
throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
var cipherText = Convert.FromBase64String(encryptedMessage);
var plainText = SimpleDecryptWithPassword(cipherText, password, nonSecretPayloadLength);
return plainText == null ? null : Encoding.UTF8.GetString(plainText);
}
public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] key, byte[] nonSecretPayload = null)
{
//User Error Checks
if (key == null || key.Length != KeyBitSize / 8)
throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "key");
if (secretMessage == null || secretMessage.Length == 0)
throw new ArgumentException("Secret Message Required!", "secretMessage");
//Non-secret Payload Optional
nonSecretPayload = nonSecretPayload ?? new byte[] { };
//Using random nonce large enough not to repeat
var nonce = new byte[NonceBitSize / 8];
Random.NextBytes(nonce, 0, nonce.Length);
var cipher = new GcmBlockCipher(new AesFastEngine());
var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload);
cipher.Init(true, parameters);
//Generate Cipher Text With Auth Tag
var cipherText = new byte[cipher.GetOutputSize(secretMessage.Length)];
var len = cipher.ProcessBytes(secretMessage, 0, secretMessage.Length, cipherText, 0);
cipher.DoFinal(cipherText, len);
//Assemble Message
using (var combinedStream = new MemoryStream())
{
using (var binaryWriter = new BinaryWriter(combinedStream))
{
//Prepend Authenticated Payload
binaryWriter.Write(nonSecretPayload);
//Prepend Nonce
binaryWriter.Write(nonce);
//Write Cipher Text
binaryWriter.Write(cipherText);
}
return combinedStream.ToArray();
}
}
public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] key, int nonSecretPayloadLength = 0)
{
//User Error Checks
if (key == null || key.Length != KeyBitSize / 8)
throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "key");
if (encryptedMessage == null || encryptedMessage.Length == 0)
throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
using (var cipherStream = new MemoryStream(encryptedMessage))
using (var cipherReader = new BinaryReader(cipherStream))
{
//Grab Payload
var nonSecretPayload = cipherReader.ReadBytes(nonSecretPayloadLength);
//Grab Nonce
var nonce = cipherReader.ReadBytes(NonceBitSize / 8);
var cipher = new GcmBlockCipher(new AesFastEngine());
var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload);
cipher.Init(false, parameters);
//Decrypt Cipher Text
var cipherText = cipherReader.ReadBytes(encryptedMessage.Length - nonSecretPayloadLength - nonce.Length);
var plainText = new byte[cipher.GetOutputSize(cipherText.Length)];
try
{
var len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0);
cipher.DoFinal(plainText, len);
}
catch (InvalidCipherTextException)
{
//Return null if it doesn't authenticate
return null;
}
return plainText;
}
}
public static byte[] SimpleEncryptWithPassword(byte[] secretMessage, string password, byte[] nonSecretPayload = null)
{
nonSecretPayload = nonSecretPayload ?? new byte[] {};
//User Error Checks
if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)
throw new ArgumentException(String.Format("Must have a password of at least {0} characters!", MinPasswordLength), "password");
if (secretMessage == null || secretMessage.Length == 0)
throw new ArgumentException("Secret Message Required!", "secretMessage");
var generator = new Pkcs5S2ParametersGenerator();
//Use Random Salt to minimize pre-generated weak password attacks.
var salt = new byte[SaltBitSize / 8];
Random.NextBytes(salt);
generator.Init(
PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()),
salt,
Iterations);
//Generate Key
var key = (KeyParameter)generator.GenerateDerivedMacParameters(KeyBitSize);
//Create Full Non Secret Payload
var payload = new byte[salt.Length + nonSecretPayload.Length];
Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length);
Array.Copy(salt,0, payload,nonSecretPayload.Length, salt.Length);
return SimpleEncrypt(secretMessage, key.GetKey(), payload);
}
public static byte[] SimpleDecryptWithPassword(byte[] encryptedMessage, string password, int nonSecretPayloadLength = 0)
{
//User Error Checks
if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)
throw new ArgumentException(String.Format("Must have a password of at least {0} characters!", MinPasswordLength), "password");
if (encryptedMessage == null || encryptedMessage.Length == 0)
throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
var generator = new Pkcs5S2ParametersGenerator();
//Grab Salt from Payload
var salt = new byte[SaltBitSize / 8];
Array.Copy(encryptedMessage, nonSecretPayloadLength, salt, 0, salt.Length);
generator.Init(
PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()),
salt,
Iterations);
//Generate Key
var key = (KeyParameter)generator.GenerateDerivedMacParameters(KeyBitSize);
return SimpleDecrypt(encryptedMessage, key.GetKey(), salt.Length + nonSecretPayloadLength);
}
}
}
评论
也将这些样本发布在代码审查中。
– jbtule
2012年12月3日14:27
这是一个很好的问题,它们使用的是Authenticated Encryption示例,除了对其进行加密以外,还具有MAC来验证密文是否未被其他人修改,这主要是为了阻止选择密文攻击。因此,在解密时,它会计算MAC以检查附加的MAC以对其进行身份验证,如果它对它进行了身份验证,则解密,如果不是,则返回null。
– jbtule
2012-12-19 13:41
MAC上的阵列检查会执行所有索引,因为如果定时攻击返回不匹配的第一个字节,则可以使用计时攻击在伪密文上计算新的MAC。
– jbtule
2012-12-19 13:42
那是一本好书,而且相对较新。我还要推荐的是Dan Boneh编写的免费在线课程“密码学I”。真的很好的视频,真的很好的测验,以及真的很好的机器问题,它们为密码学的使用提供了良好的实践基础。关于AesCryptoServiceProvider,应该使用最舒适的方式。
– jbtule
2012-12-19 20:08
一个很好解释的用法部分将非常有帮助。
–罗克兰
2015年9月28日在6:42
#3 楼
这是使用RSA的示例。重要提示:可以使用RSA加密
KeySize - MinimumPadding
加密的数据大小有限制。例如256个字节(假设2048位密钥)-42个字节(最小OEAP填充)= 214个字节(最大纯文本大小)将your_rsa_key替换为RSA密钥。
var provider = new System.Security.Cryptography.RSACryptoServiceProvider();
provider.ImportParameters(your_rsa_key);
var encryptedBytes = provider.Encrypt(
System.Text.Encoding.UTF8.GetBytes("Hello World!"), true);
string decryptedTest = System.Text.Encoding.UTF8.GetString(
provider.Decrypt(encryptedBytes, true));
有关更多信息,请访问MSDN-RSACryptoServiceProvider
评论
很抱歉提出这样一个简单的问题,但是谁能告诉我从哪里获得RSA密钥或如何生成一个?
– Akash Kava
09年11月5日在17:36
为什么选择RSA? RSA有其用途,但没有任何迹象表明这是其中之一。
– CodesInChaos
2011年7月17日下午13:35
即使在最初的问题中,也没有迹象表明RSA可能很合适。非对称加密有其用途,但它不是默认加密的正确选择。对于较长的字符串,您的示例代码将失败,因为RSA类不是为通用加密而设计的。如果需要非对称功能,则应使用RSA加密对称密钥,并使用该对称密钥加密实际数据。因此,我仍然相信您的答案是错误的建议。
– CodesInChaos
2011年7月27日9:08
我印象深刻,因为错误的答案是70票!!!,因为CodesInChaos表示,对于这种类型的加密,您需要对称密钥,而不是对称密钥。
–奥托·卡内利斯(Otto Kanellis)
2014-02-16 8:46
这不是一个错误的答案,只是过于繁琐而又开销巨大……使用AES /其他任何对称方法可获得更好的结果。
– Tomer W
15年2月22日在12:32
#4 楼
如果您使用的是ASP.Net,则现在可以使用.Net 4.0及更高版本中的内置功能。<br />System.Web.Security.MachineKey
.Net 4.5具有
MachineKey.Protect()
和MachineKey.Unprotect()
。.Net 4.0具有
MachineKey.Encode()
和MachineKey.Decode()
。您应该只将MachineKeyProtection设置为'All'。在ASP.Net之外,此类似乎在每次重新启动应用程序时都会生成一个新密钥,因此不起作用。快速浏览一下ILSpy,在我看来,如果缺少适当的app.settings,它将生成自己的默认值。因此,您实际上可以在ASP.Net外部进行设置。
在System.Web命名空间之外,我找不到等效的非ASP.Net。
评论
嗯,有人可以告诉我为什么这个答案选票太少吗?对于ASP.NET应用程序来说,这似乎是一种非常方便的方法
–德克·波尔(Dirk Boer)
2014年3月27日在12:04
@DirkBoer在问了问题几年后才添加了此功能,我添加了对这个问题的回答,以使人们知道今天有更简单的方法。这也只适用于没有某些app.config-fu的ASP.Net,如果您不知道自己在做什么,那将是非常危险的。
–mattmanser
2014年3月27日12:38
请原谅我的无知,但从网页上我找不到答案。如果我在一台机器上对字符串进行加密,然后将其写入数据库,然后在另一台机器上读取,那么只要目的参数具有相同的值,我就能解密该字符串吗?也许我对类名“ MachineKey”感到困惑
– Adriaan Davel
16-2-24在15:33
另一个问题,我可以在WPF应用程序中使用它吗?它没有Web引用,可以将引用添加到System.Web吗?
– Adriaan Davel
16-2-24在15:57
@AdriaanDavel根据链接的文档,“ MachineKey API仅应在ASP.NET应用程序中使用。MachineKeyAPI在ASP.NET应用程序上下文之外的行为是未定义的” –仅当您喜欢以下游戏时才使用它俄罗斯轮盘
– Mark Sowul
16 Dec 19'在19:16
#5 楼
BouncyCastle是适用于.NET的出色加密库,它可以作为Nuget包提供,可以安装到您的项目中。我喜欢它比System.Security.Cryptography库中当前提供的东西更多。它为您提供了更多可用算法方面的选项,并为这些算法提供了更多模式。这是一个实现TwoFish的示例,该示例由Bruce Schneier(对我们所有人都是英雄)编写。偏执的人在那里)。这是一种对称算法,例如Rijndael
(又名AES)。它是AES标准的三个入围者之一,并且是Bruce Schneier编写的另一种著名算法BlowFish的兄弟。
bouncycastle的第一件事是创建一个加密器类,这将使实现起来更容易库中的其他分组密码。以下加密程序类接受通用参数T,其中T实现IBlockCipher并具有默认构造函数。
UPDATE:由于普遍的需求,我决定实现生成随机IV并将HMAC包含到其中。这个班。尽管从样式的角度来看,这违反了单一责任的SOLID原则,但由于我拒绝了此类的性质,因此我认为。此类现在将使用两个通用参数,一个用于密码,一个用于摘要。它使用RNGCryptoServiceProvider自动生成IV,以提供良好的RNG熵,并允许您使用想要从BouncyCastle获得的任何摘要算法来生成MAC。
using System;
using System.Security.Cryptography;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;
public sealed class Encryptor<TBlockCipher, TDigest>
where TBlockCipher : IBlockCipher, new()
where TDigest : IDigest, new()
{
private Encoding encoding;
private IBlockCipher blockCipher;
private BufferedBlockCipher cipher;
private HMac mac;
private byte[] key;
public Encryptor(Encoding encoding, byte[] key, byte[] macKey)
{
this.encoding = encoding;
this.key = key;
this.Init(key, macKey, new Pkcs7Padding());
}
public Encryptor(Encoding encoding, byte[] key, byte[] macKey, IBlockCipherPadding padding)
{
this.encoding = encoding;
this.key = key;
this.Init(key, macKey, padding);
}
private void Init(byte[] key, byte[] macKey, IBlockCipherPadding padding)
{
this.blockCipher = new CbcBlockCipher(new TBlockCipher());
this.cipher = new PaddedBufferedBlockCipher(this.blockCipher, padding);
this.mac = new HMac(new TDigest());
this.mac.Init(new KeyParameter(macKey));
}
public string Encrypt(string plain)
{
return Convert.ToBase64String(EncryptBytes(plain));
}
public byte[] EncryptBytes(string plain)
{
byte[] input = this.encoding.GetBytes(plain);
var iv = this.GenerateIV();
var cipher = this.BouncyCastleCrypto(true, input, new ParametersWithIV(new KeyParameter(key), iv));
byte[] message = CombineArrays(iv, cipher);
this.mac.Reset();
this.mac.BlockUpdate(message, 0, message.Length);
byte[] digest = new byte[this.mac.GetUnderlyingDigest().GetDigestSize()];
this.mac.DoFinal(digest, 0);
var result = CombineArrays(digest, message);
return result;
}
public byte[] DecryptBytes(byte[] bytes)
{
// split the digest into component parts
var digest = new byte[this.mac.GetUnderlyingDigest().GetDigestSize()];
var message = new byte[bytes.Length - digest.Length];
var iv = new byte[this.blockCipher.GetBlockSize()];
var cipher = new byte[message.Length - iv.Length];
Buffer.BlockCopy(bytes, 0, digest, 0, digest.Length);
Buffer.BlockCopy(bytes, digest.Length, message, 0, message.Length);
if (!IsValidHMac(digest, message))
{
throw new CryptoException();
}
Buffer.BlockCopy(message, 0, iv, 0, iv.Length);
Buffer.BlockCopy(message, iv.Length, cipher, 0, cipher.Length);
byte[] result = this.BouncyCastleCrypto(false, cipher, new ParametersWithIV(new KeyParameter(key), iv));
return result;
}
public string Decrypt(byte[] bytes)
{
return this.encoding.GetString(DecryptBytes(bytes));
}
public string Decrypt(string cipher)
{
return this.Decrypt(Convert.FromBase64String(cipher));
}
private bool IsValidHMac(byte[] digest, byte[] message)
{
this.mac.Reset();
this.mac.BlockUpdate(message, 0, message.Length);
byte[] computed = new byte[this.mac.GetUnderlyingDigest().GetDigestSize()];
this.mac.DoFinal(computed, 0);
return AreEqual(digest,computed);
}
private static bool AreEqual(byte [] digest, byte[] computed)
{
if(digest.Length != computed.Length)
{
return false;
}
int result = 0;
for (int i = 0; i < digest.Length; i++)
{
// compute equality of all bytes before returning.
// helps prevent timing attacks:
// https://codahale.com/a-lesson-in-timing-attacks/
result |= digest[i] ^ computed[i];
}
return result == 0;
}
private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, ICipherParameters parameters)
{
try
{
cipher.Init(forEncrypt, parameters);
return this.cipher.DoFinal(input);
}
catch (CryptoException)
{
throw;
}
}
private byte[] GenerateIV()
{
using (var provider = new RNGCryptoServiceProvider())
{
// 1st block
byte[] result = new byte[this.blockCipher.GetBlockSize()];
provider.GetBytes(result);
return result;
}
}
private static byte[] CombineArrays(byte[] source1, byte[] source2)
{
byte[] result = new byte[source1.Length + source2.Length];
Buffer.BlockCopy(source1, 0, result, 0, source1.Length);
Buffer.BlockCopy(source2, 0, result, source1.Length, source2.Length);
return result;
}
}
接下来只需调用新类上的加密和解密方法,这是使用twofish的示例:
var encrypt = new Encryptor<TwofishEngine, Sha1Digest>(Encoding.UTF8, key, hmacKey);
string cipher = encrypt.Encrypt("TEST");
string plainText = encrypt.Decrypt(cipher);
替换另一个分组密码(如TripleDES)也很容易:
var des = new Encryptor<DesEdeEngine, Sha1Digest>(Encoding.UTF8, key, hmacKey);
string cipher = des.Encrypt("TEST");
string plainText = des.Decrypt(cipher);
最后,如果要将AES与SHA256 HMAC一起使用,可以执行以下操作:
var aes = new Encryptor<AesEngine, Sha256Digest>(Encoding.UTF8, key, hmacKey);
cipher = aes.Encrypt("TEST");
plainText = aes.Decrypt(cipher);
关于加密最困难的部分实际上是处理密钥而不是算法。您将不得不考虑将密钥存储在什么地方,以及是否必须交换密钥。这些算法经受住了时间的考验,并且很难破解。想要从您那里窃取信息的人不会花费永恒的时间对您的消息进行密码分析,他们将试图弄清楚您的密钥是什么或在哪里。因此,#1明智地选择密钥,#2将其存储在安全的地方,如果您使用web.config和IIS,则可以加密web.config的一部分,最后,如果您必须交换密钥,请确保
更新2
更改了比较方法以减轻定时攻击。在http://codahale.com/a-lesson-in-timing-attacks/中查看更多信息。还更新为默认设置为PKCS7填充,并添加了新的构造函数,以使最终用户能够选择他们想使用的填充。感谢@CodesInChaos的建议。
评论
1)该类非常令人讨厌,因为您将IV管理的负担加在了几乎肯定会弄错的用户身上。 2)MAC的缺乏使它容易受填充预言。
– CodesInChaos
13年8月14日在16:47
1)你的填充物对我来说很碎。您添加零填充,但不要删除它。零填充是一个坏主意,因为它不能可靠地删除。请改用PKCS#7填充。我希望bouncycastle加密/解密功能已经支持此功能。 2)您应该使用恒定时间比较来验证MAC,而不是SequenceEqual。这避免了定时侧信道泄漏了所呈现的MAC的前缀和实际的MAC匹配多长时间。
– CodesInChaos
2014年10月10日17:08
@CodesInChaos我同意,感谢您对此进行检查,我进行了编辑以解决这些问题。 – nerdybeardo
–nerdybeardo
2014年3月11日上午10:10
好答案,只是一个问题....什么是密钥和hmacKey,我是crypto的新手..谢谢!
–Terkhos
15年7月24日在15:35
@Terkhos您应该使用安全的随机数生成器来生成类似RNGCryptoServiceProvider的密钥,永远不要使用密码短语或可预测的内容。您还应该使用算法将提供的最大长度,例如AES 256使用的密钥大小为256位,因此最好使用32个随机字节.HMAC密钥大小通常基于算法的大小,例如SHA2( 256)由安全随机数生成器生成的256位密钥就足够了。经常更换钥匙!越多越好!
–nerdybeardo
15年7月27日在1:07
#6 楼
免责声明:此解决方案仅应用于未公开的静态数据(例如-配置文件或DB)。仅在这种情况下,由于维护成本较低,因此可以认为快速和肮脏的解决方案比@jbtule的解决方案更好。原始帖子:
我发现jbtule的答案对于a快速,肮脏的安全AES字符串加密,Brett的答案存在一个错误,因为Initialization Vector是固定值,因此容易受到填充攻击,因此我修复了Brett的代码,并添加了随机IV,该IV被添加到切片字符串中,从而创建了不同的加密为每个具有相同值的加密设置值:
加密:
public static string Encrypt(string clearText)
{
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
byte[] IV = new byte[15];
rand.NextBytes(IV);
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, IV);
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(IV) + Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
解密:
public static string Decrypt(string cipherText)
{
byte[] IV = Convert.FromBase64String(cipherText.Substring(0, 20));
cipherText = cipherText.Substring(20).Replace(" ", "+");
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, IV);
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
用您的密钥替换EncryptionKey。
在我的实现中,密钥被保存在配置文件(web.config \ app.config)中,因为您不应该对其进行硬编码。配置文件也应该加密,这样密钥就不会保存为明文。
protected static string _Key = "";
protected static string EncryptionKey
{
get
{
if (String.IsNullOrEmpty(_Key))
{
_Key = ConfigurationManager.AppSettings["AESKey"].ToString();
}
return _Key;
}
}
评论
尽管即使使用相同的纯文本,您的Encrypt方法也会为每个调用生成不同的值,但是Substring(20)每次都相同,对吗?
– dub stylee
16年3月18日在16:57
我没有注意到Encrypt每次都会生成不同的IV。由于某种原因,我一直认为每次IV都是相同的,这基本上使它毫无意义。
– dub stylee
16 Mar 24 '16 at 19:10
我理解您说的@jbtule,但实际上完全是关于风险管理的。如果您需要做的只是在本地存储一些机密信息,并且希望使用AES进行额外的防御,那么该解决方案可能会满足您的需求。
–吉尔·科恩(Gil Cohen)
17 Mar 30 '17 at 12:15
@GilCohen Well在此声明了一个很大的免责声明,并说仅用于静态数据,不提供服务,然后您可以提出风险管理要求。但是,您的又快又脏又马虎。例如,为什么在解密时只用加号代替空格,反之亦然呢?这是因为在获取密码之前,还有其他东西正在修改密文吗?就像通过url查询字符串,cookie或表单变量hmm传递一样,这听起来像是一种服务,当您需要验证密文时,绝对是一种服务。
– jbtule
17 Mar 30 '17 at 14:52
@jbtule实际上不,出于某种原因,这是Base64函数的编码。这确实是用于静态数据的,我同意您的评论。我将其添加。
–吉尔·科恩(Gil Cohen)
17年8月6日在12:28
#7 楼
加密 public string EncryptString(string inputString)
{
MemoryStream memStream = null;
try
{
byte[] key = { };
byte[] IV = { 12, 21, 43, 17, 57, 35, 67, 27 };
string encryptKey = "aXb2uy4z"; // MUST be 8 characters
key = Encoding.UTF8.GetBytes(encryptKey);
byte[] byteInput = Encoding.UTF8.GetBytes(inputString);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
memStream = new MemoryStream();
ICryptoTransform transform = provider.CreateEncryptor(key, IV);
CryptoStream cryptoStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);
cryptoStream.Write(byteInput, 0, byteInput.Length);
cryptoStream.FlushFinalBlock();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
return Convert.ToBase64String(memStream.ToArray());
}
解密:
public string DecryptString(string inputString)
{
MemoryStream memStream = null;
try
{
byte[] key = { };
byte[] IV = { 12, 21, 43, 17, 57, 35, 67, 27 };
string encryptKey = "aXb2uy4z"; // MUST be 8 characters
key = Encoding.UTF8.GetBytes(encryptKey);
byte[] byteInput = new byte[inputString.Length];
byteInput = Convert.FromBase64String(inputString);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
memStream = new MemoryStream();
ICryptoTransform transform = provider.CreateDecryptor(key, IV);
CryptoStream cryptoStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);
cryptoStream.Write(byteInput, 0, byteInput.Length);
cryptoStream.FlushFinalBlock();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
Encoding encoding1 = Encoding.UTF8;
return encoding1.GetString(memStream.ToArray());
}
评论
-1这非常弱。 1)DES具有56位密钥,易于暴力破解。 2)密钥是二进制的,而不是UTF8。如果密钥由ASCII字符组成(实际上可能是这样),则这会将有效密钥大小减小到48位。 3)每个消息的IV均应不同。4)MAC不足会使您容易受到主动式攻击,包括填充预言。
– CodesInChaos
15年2月19日在21:29
+1 OP有一个非常简单的问题,不需要最大的强度,而这个答案恰好与此相对应。至少我可以使用它,因为我也有一个简单的加密用法。
–罗兰
15-10-28在15:47
-1 @Roland如CodesInChaos所述,每条消息的IV都需要不同,非常简单,如果没有,则您使用的API错误,因此永远不要使用此代码。期。不要掩盖48位密钥,这使得一天之内没有密钥的任何人都可以解密,因此这不再是加密,因此无法回答问题。
– jbtule
17 Mar 29 '17 at 17:29
安全警告:请勿使用此代码,请参见上文@CodesInChaos的评论
– jbtule
17年5月8日在21:59
将其用于简单的应用程序如果您要保护核秘密,请使用其他方法。这是按原样工作的。
–约翰·皮塔维(John Pittaway)
19-09-27在23:30
#8 楼
下面的示例演示如何加密和解密示例数据: // This constant is used to determine the keysize of the encryption algorithm in bits.
// We divide this by 8 within the code below to get the equivalent number of bytes.
private const int Keysize = 128;
// This constant determines the number of iterations for the password bytes generation function.
private const int DerivationIterations = 1000;
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 = GenerateBitsOfRandomEntropy(16);
var ivStringBytes = GenerateBitsOfRandomEntropy(16);
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.BlockSize = 128;
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 Decrypt(string cipherText, string passPhrase)
{
// Get the complete stream of bytes that represent:
// [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
// Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
// Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
// Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.BlockSize = 128;
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream(cipherTextBytes))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
var plainTextBytes = new byte[cipherTextBytes.Length];
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
}
}
}
}
}
private static byte[] GenerateBitsOfRandomEntropy(int size)
{
// 32 Bytes will give us 256 bits.
// 16 Bytes will give us 128 bits.
var randomBytes = new byte[size];
using (var rngCsp = new RNGCryptoServiceProvider())
{
// Fill the array with cryptographically secure random bytes.
rngCsp.GetBytes(randomBytes);
}
return randomBytes;
}
评论
谢谢@reza ..如果可以的话,它可以用于一些家庭项目吗?
– Arrie
3月2日,19:42
#9 楼
通过在c#中对字符串进行加密和解密,我找到了一个很好的解决方案:static readonly string PasswordHash = "P@@Sw0rd";
static readonly string SaltKey = "S@LT&KEY";
static readonly string VIKey = "@1B2c3D4e5F6g7H8";
对于Encrypt
public static string Encrypt(string plainText)
{
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
byte[] cipherTextBytes;
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
cipherTextBytes = memoryStream.ToArray();
cryptoStream.Close();
}
memoryStream.Close();
}
return Convert.ToBase64String(cipherTextBytes);
}
用于解密
public static string Decrypt(string encryptedText)
{
byte[] cipherTextBytes = Convert.FromBase64String(encryptedText);
byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };
var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
var memoryStream = new MemoryStream(cipherTextBytes);
var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("q4312078q".ToCharArray());
}
评论
硬编码的Salt和IV,并使用ASCII表示形式,这是各种错误。
– jbtule
17年3月29日在17:43
安全警告:请勿使用此代码请参阅我的评论。
– jbtule
17年5月8日在22:00
抱歉,我没有说明。 IV并不是关键,而将其保密将提供零附加安全性,并且使其可预测会失去很多安全性。对任何真正知道如何使用AES-CBC加密的人来说,对IV进行硬编码是完全不合理的/不合逻辑的/错误的。 Encoding.ASCII.GetBytes用于旨在将熵添加到人类选择的事物上的数据,其熵将远小于预期的熵,这是一个非常新手的错误。这些都是很容易纠正的东西,但实际上并非如此,由于安全隐患,我的大胆警告仍然存在。
– jbtule
17年5月9日下午4:59
拉胡尔,放松一下!坐下来,放松一下,想一想为什么@jbtule的所有3条评论都得到了投票。为了使您走上正确的道路,他在讲一些明智的话。没有什么可冒犯的。您是新来的。您将意识到它最终是如何工作的。
– Nikhil Vartak
17年5月25日在7:26
#10 楼
支持mattmanser的答案。这是一个使用MachineKey类加密/解密URL安全值的示例。需要记住的一点是,如前所述,它将使用计算机配置设置(https://msdn.microsoft.com/zh-cn/library/ff649308.aspx)。您可以在web.config文件中手动设置加密和解密密钥/算法(如果您的站点在多个服务器上运行,则可能特别需要此设置)。您可以从IIS生成密钥(请参阅此处:https://blogs.msdn.microsoft.com/vijaysk/2009/05/13/iis-7-tip-10-you-can-generate-machine-keys-from- -iis-manager /),也可以使用在线机器密钥生成器,例如:http://www.developerfusion.com/tools/generatemachinekey/
private static readonly UTF8Encoding Encoder = new UTF8Encoding();
public static string Encrypt(string unencrypted)
{
if (string.IsNullOrEmpty(unencrypted))
return string.Empty;
try
{
var encryptedBytes = MachineKey.Protect(Encoder.GetBytes(unencrypted));
if (encryptedBytes != null && encryptedBytes.Length > 0)
return HttpServerUtility.UrlTokenEncode(encryptedBytes);
}
catch (Exception)
{
return string.Empty;
}
return string.Empty;
}
public static string Decrypt(string encrypted)
{
if (string.IsNullOrEmpty(encrypted))
return string.Empty;
try
{
var bytes = HttpServerUtility.UrlTokenDecode(encrypted);
if (bytes != null && bytes.Length > 0)
{
var decryptedBytes = MachineKey.Unprotect(bytes);
if(decryptedBytes != null && decryptedBytes.Length > 0)
return Encoder.GetString(decryptedBytes);
}
}
catch (Exception)
{
return string.Empty;
}
return string.Empty;
}
#11 楼
这是一个简单的示例,它使用AES CBC模式,随机IV和HMAC和密码派生的密钥以C#方式对字符串进行加密,以显示基本的移动部分:private byte[] EncryptBytes(byte[] key, byte[] plaintext)
{
using (var cipher = new RijndaelManaged { Key = key })
{
using (var encryptor = cipher.CreateEncryptor())
{
var ciphertext = encryptor.TransformFinalBlock(plaintext, 0, plaintext.Length);
// IV is prepended to ciphertext
return cipher.IV.Concat(ciphertext).ToArray();
}
}
}
private byte[] DecryptBytes(byte[] key, byte[] packed)
{
using (var cipher = new RijndaelManaged { Key = key })
{
int ivSize = cipher.BlockSize / 8;
cipher.IV = packed.Take(ivSize).ToArray();
using (var encryptor = cipher.CreateDecryptor())
{
return encryptor.TransformFinalBlock(packed, ivSize, packed.Length - ivSize);
}
}
}
private byte[] AddMac(byte[] key, byte[] data)
{
using (var hmac = new HMACSHA256(key))
{
var macBytes = hmac.ComputeHash(data);
// HMAC is appended to data
return data.Concat(macBytes).ToArray();
}
}
private bool BadMac(byte[] found, byte[] computed)
{
int mismatch = 0;
// Aim for consistent timing regardless of inputs
for (int i = 0; i < found.Length; i++)
{
mismatch += found[i] == computed[i] ? 0 : 1;
}
return mismatch != 0;
}
private byte[] RemoveMac(byte[] key, byte[] data)
{
using (var hmac = new HMACSHA256(key))
{
int macSize = hmac.HashSize / 8;
var packed = data.Take(data.Length - macSize).ToArray();
var foundMac = data.Skip(packed.Length).ToArray();
var computedMac = hmac.ComputeHash(packed);
if (this.BadMac(foundMac, computedMac))
{
throw new Exception("Bad MAC");
}
return packed;
}
}
private List<byte[]> DeriveTwoKeys(string password)
{
var salt = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
var kdf = new Rfc2898DeriveBytes(password, salt, 10000);
var bytes = kdf.GetBytes(32); // Two keys 128 bits each
return new List<byte[]> { bytes.Take(16).ToArray(), bytes.Skip(16).ToArray() };
}
public byte[] EncryptString(string password, String message)
{
var keys = this.DeriveTwoKeys(password);
var plaintext = Encoding.UTF8.GetBytes(message);
var packed = this.EncryptBytes(keys[0], plaintext);
return this.AddMac(keys[1], packed);
}
public String DecryptString(string password, byte[] secret)
{
var keys = this.DeriveTwoKeys(password);
var packed = this.RemoveMac(keys[1], secret);
var plaintext = this.DecryptBytes(keys[0], packed);
return Encoding.UTF8.GetString(plaintext);
}
public void Example()
{
var password = "correcthorsebatterystaple";
var secret = this.EncryptString(password, "Hello World");
Console.WriteLine("secret: " + BitConverter.ToString(secret));
var recovered = this.DecryptString(password, secret);
Console.WriteLine(recovered);
}
评论
有两个问题:1)您在密钥派生中没有使用盐,而是启用了多目标攻击。 2)由于您转移了秘密数据,因此MAC比较功能可能会受到侧信道/定时攻击的攻击。使用不匹配+ = found [i] ^ computed [i]之类的东西。 3)您使用的PBKDF2-HMAC-SHA-1字节超过20个,这会使KDF降低2倍,而不会降低攻击者的速度
– CodesInChaos
2014年8月11日上午10:59
@CodesInChaos:1)这只是一个简单的示例,可以让人们入门-我仅出于清晰起见省略了随机盐。但是,好点。 2)好的,微妙的观点。 3)您建议在20个字节中派生两个16个字节的密钥吗?
– Jim Flood
2014年8月11日在20:47
最简单的方法是使用SHA-2对慢速哈希的输出进行哈希。比较好的方法是HKDF或只是再次应用PBKDF2,但这一次迭代设置为1。
– CodesInChaos
2014年8月12日在8:00
@CodesInChaos我不会使用SHA-2。哈希函数的工作与密钥派生函数的工作不同。哈希仅需要是不可预测的,并且可以在输入更改时更改。密钥必须与随机密钥没有区别。我仍然会从KDF中提取32个字节。在这种情况下,您过早进行优化并增加了风险。
– Jim Flood
14年8月14日在16:27
#12 楼
用于AES-GCM加密的BouncyCastle的替代方法是libsodium-net。它包装了libsodium C库。一个不错的优点是,它使用CPU中的AES-NI扩展来进行非常快速的加密。不利的一面是,如果CPU没有扩展,它将根本无法工作。没有软件退回。#13 楼
以下代码是Ghazal对类似问题的回答的改进版本。 public class EncryptionHelper
{
private Aes aesEncryptor;
public EncryptionHelper()
{
}
private void BuildAesEncryptor(string key)
{
aesEncryptor = Aes.Create();
var pdb = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
aesEncryptor.Key = pdb.GetBytes(32);
aesEncryptor.IV = pdb.GetBytes(16);
}
public string EncryptString(string clearText, string key)
{
BuildAesEncryptor(key);
var clearBytes = Encoding.Unicode.GetBytes(clearText);
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, aesEncryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
}
var encryptedText = Convert.ToBase64String(ms.ToArray());
return encryptedText;
}
}
public string DecryptString(string cipherText, string key)
{
BuildAesEncryptor(key);
cipherText = cipherText.Replace(" ", "+");
var cipherBytes = Convert.FromBase64String(cipherText);
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, aesEncryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
}
var clearText = Encoding.Unicode.GetString(ms.ToArray());
return clearText;
}
}
}
#14 楼
这是布雷特在这里布置的课。但是,我进行了少量编辑,因为在将其用于URL字符串进行加密和解密时收到错误“ Base-64 char数组的长度无效”。public class CryptoURL
{
private static byte[] _salt = Encoding.ASCII.GetBytes("Catto_Salt_Enter_Any_Value99");
/// <summary>
/// Encrypt the given string using AES. The string can be decrypted using
/// DecryptStringAES(). The sharedSecret parameters must match.
/// The SharedSecret for the Password Reset that is used is in the next line
/// string sharedSecret = "OneUpSharedSecret9";
/// </summary>
/// <param name="plainText">The text to encrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for encryption.</param>
public static string EncryptString(string plainText, string sharedSecret)
{
if (string.IsNullOrEmpty(plainText))
throw new ArgumentNullException("plainText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
string outStr = null; // Encrypted string to return
RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create a RijndaelManaged object
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
// Create a decryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
// prepend the IV
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))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
}
outStr = HttpServerUtility.UrlTokenEncode(msEncrypt.ToArray());
//outStr = Convert.ToBase64String(msEncrypt.ToArray());
// you may need to add a reference. right click reference in solution explorer => "add Reference" => .NET tab => select "System.Web"
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
// Return the encrypted bytes from the memory stream.
return outStr;
}
/// <summary>
/// Decrypt the given string. Assumes the string was encrypted using
/// EncryptStringAES(), using an identical sharedSecret.
/// </summary>
/// <param name="cipherText">The text to decrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for decryption.</param>
public static string DecryptString(string cipherText, string sharedSecret)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException("cipherText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
// Declare the RijndaelManaged object
// used to decrypt the data.
RijndaelManaged aesAlg = null;
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
byte[] inputByteArray;
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create the streams used for decryption.
//byte[] bytes = Convert.FromBase64String(cipherText);
inputByteArray = HttpServerUtility.UrlTokenDecode(cipherText);
using (MemoryStream msDecrypt = new MemoryStream(inputByteArray))
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
// Get the initialization vector from the encrypted stream
aesAlg.IV = ReadByteArray(msDecrypt);
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
catch (System.Exception ex)
{
return "ERROR";
//throw ex;
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
return plaintext;
}
static string ConvertStringArrayToString(string[] array)
{
//
// Concatenate all the elements into a StringBuilder.
//
StringBuilder builder = new StringBuilder();
foreach (string value in array)
{
builder.Append(value);
builder.Append('.');
}
return builder.ToString();
}
private static byte[] ReadByteArray(Stream s)
{
byte[] rawLength = new byte[sizeof(int)];
if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
{
throw new SystemException("Stream did not contain properly formatted byte array");
}
byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
{
throw new SystemException("Did not read byte array properly");
}
return buffer;
}
}
评论
ConvertStringArrayToString()方法用于什么?
– abenci
16/09/14在12:49
#15 楼
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class Program
{
public static void Main()
{
var key = Encoding.UTF8.GetBytes("SUkbqO2ycDo7QwpR25kfgmC7f8CoyrZy");
var data = Encoding.UTF8.GetBytes("testData");
//Encrypt data
var encrypted = CryptoHelper.EncryptData(data,key);
//Decrypt data
var decrypted = CryptoHelper.DecryptData(encrypted,key);
//Display result
Console.WriteLine(Encoding.UTF8.GetString(decrypted));
}
}
public static class CryptoHelper
{
public static byte[] EncryptData(byte[] data, byte[] key)
{
using (var aesAlg = Aes.Create())
{
aesAlg.Mode = CipherMode.CBC;
using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))
{
using (var msEncrypt = new MemoryStream())
{
msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
csEncrypt.Write(data, 0, data.Length);
return msEncrypt.ToArray();
}
}
}
}
public static byte[] DecryptData(byte[] encrypted, byte[] key)
{
var iv = new byte[16];
Buffer.BlockCopy(encrypted, 0, iv, 0, iv.Length);
using (var aesAlg = Aes.Create())
{
aesAlg.Mode = CipherMode.CBC;
using (var decryptor = aesAlg.CreateDecryptor(key, iv))
{
using (var msDecrypt = new MemoryStream(encrypted, iv.Length, encrypted.Length - iv.Length))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var resultStream = new MemoryStream())
{
csDecrypt.CopyTo(resultStream);
return resultStream.ToArray();
}
}
}
}
}
}
}
#16 楼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.IO;
using System.Text;
/// <summary>
/// Summary description for Encryption
/// </summary>
public class Encryption
{
public TripleDES CreateDES(string key)
{
MD5 md5 = new MD5CryptoServiceProvider();
TripleDES des = new TripleDESCryptoServiceProvider();
des.Key = md5.ComputeHash(Encoding.Unicode.GetBytes(key));
des.IV = new byte[des.BlockSize / 8];
return des;
}
public byte[] Encryptiondata(string PlainText)
{
TripleDES des = CreateDES("DreamMLMKey");
ICryptoTransform ct = des.CreateEncryptor();
byte[] input = Encoding.Unicode.GetBytes(PlainText);
return ct.TransformFinalBlock(input, 0, input.Length);
}
public string Decryptiondata(string CypherText)
{
string stringToDecrypt = CypherText.Replace(" ", "+");
int len = stringToDecrypt.Length;
byte[] inputByteArray = Convert.FromBase64String(stringToDecrypt);
byte[] b = Convert.FromBase64String(CypherText);
TripleDES des = CreateDES("DreamMLMKey");
ICryptoTransform ct = des.CreateDecryptor();
byte[] output = ct.TransformFinalBlock(b, 0, b.Length);
return Encoding.Unicode.GetString(output);
}
public string Decryptiondataurl(string CypherText)
{
string newcyperttext=CypherText.Replace(' ', '+');
byte[] b = Convert.FromBase64String(newcyperttext);
TripleDES des = CreateDES("DreamMLMKey");
ICryptoTransform ct = des.CreateDecryptor();
byte[] output = ct.TransformFinalBlock(b, 0, b.Length);
return Encoding.Unicode.GetString(output);
}
#region encryption & Decription
public string Encrypt(string input, string key)
{
byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input);
TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
tripleDES.Mode = CipherMode.ECB;
tripleDES.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tripleDES.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
tripleDES.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
public string Decrypt(string input, string key)
{
byte[] inputArray = Convert.FromBase64String(input);
TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
tripleDES.Mode = CipherMode.ECB;
tripleDES.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tripleDES.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
tripleDES.Clear();
return UTF8Encoding.UTF8.GetString(resultArray);
}
public string encrypt(string encryptString)
{
string EncryptionKey = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
byte[] clearBytes = Encoding.Unicode.GetBytes(encryptString);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] {
0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76
});
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
encryptString = Convert.ToBase64String(ms.ToArray());
}
}
return encryptString;
}
public string Decrypt(string cipherText)
{
string EncryptionKey = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cipherText = cipherText.Replace(" ", "+");
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] {
0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76
});
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
#endregion
}
评论
MD5是最不安全的。不推荐。
–vapcguy
2月14日下午21:13
#17 楼
加密是编程中非常普遍的事情。我认为最好安装一个软件包来为您完成任务。也许是一个简单的开源Nuget项目,例如Simple Aes Encryption
密钥位于配置文件中,因此在生产环境中很容易更改,我看不到任何缺点
<MessageEncryption>
<EncryptionKey KeySize="256" Key="3q2+796tvu/erb7v3q2+796tvu/erb7v3q2+796tvu8="/>
</MessageEncryption>
评论
最大的缺点是它不是经过身份验证的加密。
– jbtule
17年3月29日在17:13
#18 楼
从我的答案中复制了一个类似的问题:基于C#的简单双向加密。基于多个答案和注释。
随机初始化矢量被附加到加密文本(@jbtule)
使用TransformFinalBlock()代替MemoryStream(@RenniePet)
没有预填充密钥,以避免任何人复制和粘贴灾难
正确处置和使用模式
代码:
/// <summary>
/// Simple encryption/decryption using a random initialization vector
/// and prepending it to the crypto text.
/// </summary>
/// <remarks>Based on multiple answers in https://stackoverflow.com/questions/165808/simple-two-way-encryption-for-c-sharp </remarks>
public class SimpleAes : IDisposable
{
/// <summary>
/// Initialization vector length in bytes.
/// </summary>
private const int IvBytes = 16;
/// <summary>
/// Must be exactly 16, 24 or 32 characters long.
/// </summary>
private static readonly byte[] Key = Convert.FromBase64String("FILL ME WITH 16, 24 OR 32 CHARS");
private readonly UTF8Encoding _encoder;
private readonly ICryptoTransform _encryptor;
private readonly RijndaelManaged _rijndael;
public SimpleAes()
{
_rijndael = new RijndaelManaged {Key = Key};
_rijndael.GenerateIV();
_encryptor = _rijndael.CreateEncryptor();
_encoder = new UTF8Encoding();
}
public string Decrypt(string encrypted)
{
return _encoder.GetString(Decrypt(Convert.FromBase64String(encrypted)));
}
public void Dispose()
{
_rijndael.Dispose();
_encryptor.Dispose();
}
public string Encrypt(string unencrypted)
{
return Convert.ToBase64String(Encrypt(_encoder.GetBytes(unencrypted)));
}
private byte[] Decrypt(byte[] buffer)
{
// IV is prepended to cryptotext
byte[] iv = buffer.Take(IvBytes).ToArray();
using (ICryptoTransform decryptor = _rijndael.CreateDecryptor(_rijndael.Key, iv))
{
return decryptor.TransformFinalBlock(buffer, IvBytes, buffer.Length - IvBytes);
}
}
private byte[] Encrypt(byte[] buffer)
{
// Prepend cryptotext with IV
byte[] inputBuffer = _rijndael.IV.Concat(buffer).ToArray();
return _encryptor.TransformFinalBlock(inputBuffer, IvBytes, buffer.Length);
}
}
评论
您应该添加MAC以防止主动攻击,例如填充预言。
– CodesInChaos
15年2月19日在21:31
您可能是对的,我绝不是精通这一领域。当我最初访问此主题时,我只是想要一些简单且有效且安全的东西。对于绝对敏感的数据,我绝对会使用经过尝试和验证的库。
– Angularsen
15年2月20日在7:36
#19 楼
这是最初由ASP片段组成的简单片段using System.Text;
using System.Security.Cryptography;
using System.IO;
private string Encrypt(string clearText)
{
string EncryptionKey = "yourkey";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
private string Decrypt(string cipherText)
{
string EncryptionKey = "yourkey";
cipherText = cipherText.Replace(" ", "+");
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
评论
您不检查完整性/身份验证。您应该添加一个MAC。
– Artjom B.
2014年12月17日在9:18
实际上,上面的示例实际上是对字符串变量进行加密/解密。
– AirCodeOne
2015年1月6日,下午5:01
密文应进行身份验证(例如使用HMAC),以防止填充Oracle攻击。当我再次浏览此代码时,似乎您正在使用ECB模式,因为它在语义上不安全,因此永远不要使用。同样,当您从主密钥和盐导出密钥和IV时,盐是静态的。这会导致静态IV,从而破坏了IV的整个概念,并使您的方案在语义上再次变得不安全。
– Artjom B.
2015年1月6日在9:33
谢谢Brother,如果您可以在此处传递更正的代码,那将是非常有用的帮助。
– AirCodeOne
2015年1月9日在2:35
#20 楼
AES算法:public static class CryptographyProvider
{
public static string EncryptString(string plainText, out string Key)
{
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
using (Aes _aesAlg = Aes.Create())
{
Key = Convert.ToBase64String(_aesAlg.Key);
ICryptoTransform _encryptor = _aesAlg.CreateEncryptor(_aesAlg.Key, _aesAlg.IV);
using (MemoryStream _memoryStream = new MemoryStream())
{
_memoryStream.Write(_aesAlg.IV, 0, 16);
using (CryptoStream _cryptoStream = new CryptoStream(_memoryStream, _encryptor, CryptoStreamMode.Write))
{
using (StreamWriter _streamWriter = new StreamWriter(_cryptoStream))
{
_streamWriter.Write(plainText);
}
return Convert.ToBase64String(_memoryStream.ToArray());
}
}
}
}
public static string DecryptString(string cipherText, string Key)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException("cipherText");
if (string.IsNullOrEmpty(Key))
throw new ArgumentNullException("Key");
string plaintext = null;
byte[] _initialVector = new byte[16];
byte[] _Key = Convert.FromBase64String(Key);
byte[] _cipherTextBytesArray = Convert.FromBase64String(cipherText);
byte[] _originalString = new byte[_cipherTextBytesArray.Length - 16];
Array.Copy(_cipherTextBytesArray, 0, _initialVector, 0, _initialVector.Length);
Array.Copy(_cipherTextBytesArray, 16, _originalString, 0, _cipherTextBytesArray.Length - 16);
using (Aes _aesAlg = Aes.Create())
{
_aesAlg.Key = _Key;
_aesAlg.IV = _initialVector;
ICryptoTransform decryptor = _aesAlg.CreateDecryptor(_aesAlg.Key, _aesAlg.IV);
using (MemoryStream _memoryStream = new MemoryStream(_originalString))
{
using (CryptoStream _cryptoStream = new CryptoStream(_memoryStream, decryptor, CryptoStreamMode.Read))
{
using (StreamReader _streamReader = new StreamReader(_cryptoStream))
{
plaintext = _streamReader.ReadToEnd();
}
}
}
}
return plaintext;
}
}
评论
1)IV作为参数传入,这意味着开发人员必须进行IV管理,否则他们会出错。相反,IV应该随机生成并与密文一起存储。 2)由于IV和密钥将在Encryption方法的多次执行之间改变,并且不会持久存在,因此除了出于演示目的之外,根本不需要使用此方法。 3)没有对密文进行身份验证,因此攻击者可能会在未检测到密文的情况下对其进行操作(请参阅:padding oracle Attack)。
– Artjom B.
16 Jun 10'在8:23
hai @ArtjomB。开发人员不必担心iv管理,因为它将与加密字符串一起生成并添加。
–头骨
16-6-10上午9:56
我不同意。 IV存储在_iv类变量中,而不写入密文中。那么,您认为接收方将如何知道密钥和IV?它们将必须以其他方式分发。由于IV不应被认为是秘密的,因此应为每种加密随机生成IV,并将其与密文一起分发。
– Artjom B.
16年10月10日在10:03
1)在上面的链接中,您可以不用任何方式实现aes的实现,不必担心iv管理,因为iv也随字符串一起被加密了。 2)由于您引用的函数包含私有访问修饰符,因此您无法在外部调用它。为了加密,我们只能使用Cryptographyclass.Encrytion(“ SAMPLEstring”)函数
–头骨
16 Jun 15'12:37
#21 楼
这是如何使用Bouncy Castle包进行AES-GCM加密/解密的示例。我发现该示例在Google搜索时有可能从GOlang
crypto/aes
api中解密数据:<净样本的工作原理类似于带有密钥(256位),mac(128位)和随机数(96位)的超级按钮。
#22 楼
一个很好的例子,如何使用带有BouncyCastle的PGPCore来执行此操作,非常简单的解决方案:https://blog.bitscry.com/2018/07/05/pgp-encryption-and-decryption-in-c/我尝试了不同的解决方案,但这对我来说最有效,有些有错误,但是对我来说是完美的。
using (PGP pgp = new PGP())
{
// Generate keys
pgp.GenerateKey(@"C:\TEMP\keys\public.asc", @"C:\TEMP\keys\private.asc", "email@email.com", "password");
// Encrypt file
pgp.EncryptFile(@"C:\TEMP\keys\content.txt", @"C:\TEMP\keys\content__encrypted.pgp", @"C:\TEMP\keys\public.asc", true, true);
// Encrypt and sign file
pgp.EncryptFileAndSign(@"C:\TEMP\keys\content.txt", @"C:\TEMP\keys\content__encrypted_signed.pgp", @"C:\TEMP\keys\public.asc", @"C:\TEMP\keys\private.asc", "password", true, true);
// Decrypt file
pgp.DecryptFile(@"C:\TEMP\keys\content__encrypted.pgp", @"C:\TEMP\keys\content__decrypted.txt", @"C:\TEMP\keys\private.asc", "password");
// Decrypt signed file
pgp.DecryptFile(@"C:\TEMP\keys\content__encrypted_signed.pgp", @"C:\TEMP\keys\content__decrypted_signed.txt", @"C:\TEMP\keys\private.asc", "password");
// Encrypt stream
using (FileStream inputFileStream = new FileStream(@"C:\TEMP\keys\content.txt", FileMode.Open))
using (Stream outputFileStream = File.Create(@"C:\TEMP\keys\content__encrypted2.pgp"))
using (Stream publicKeyStream = new FileStream(@"C:\TEMP\keys\public.asc", FileMode.Open))
pgp.EncryptStream(inputFileStream, outputFileStream, publicKeyStream, true, true);
// Decrypt stream
using (FileStream inputFileStream = new FileStream(@"C:\TEMP\keys\content__encrypted2.pgp", FileMode.Open))
using (Stream outputFileStream = File.Create(@"C:\TEMP\keys\content__decrypted2.txt"))
using (Stream privateKeyStream = new FileStream(@"C:\TEMP\keys\private.asc", FileMode.Open))
pgp.DecryptStream(inputFileStream, outputFileStream, privateKeyStream, "password");
}
#23 楼
我有一个名为X509Crypto的开源项目,该项目利用证书来加密和解密字符串。它很容易使用。以下是使用方法的示例:1。使用X509Crypto命令行界面(CLI)生成新的加密证书和密钥对。
>x509crypto.exe
X509Crypto> makecert -context user -keysize medium -alias myvault
Certificate with thumbprint B31FE7E7AE5229F8186782742CF579197FA859FD was added to X509Alias "myvault" in the user X509Context
X509Crypto>
2。使用“加密CLI”命令将密钥添加到新的X509Alias
X509Crypto> encrypt -text -alias myvault -context user -secret apikey -in "80EAF03248965AC2B78090"
Secret apikey has been added to X509Alias myvault in the user X509Context
X509Crypto>
3。引用程序中的密钥
一旦建立了X509Alias并添加了密钥,在安装Org.X509Crypto nuget软件包的程序中检索它们就很简单了:
using Org.X509Crypto;
namespace SampleApp
{
class Program
{
static void Main(string[] args)
{
var Alias = new X509Alias(@"myvault", X509Context.UserReadOnly);
var apiKey = Alias.RecoverSecret(@"apikey");
}
}
}
#24 楼
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions; // This is for password validation
using System.Security.Cryptography;
using System.Configuration; // This is where the hash functions reside
namespace BullyTracker.Common
{
public class HashEncryption
{
//public string GenerateHashvalue(string thisPassword)
//{
// MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
// byte[] tmpSource;
// byte[] tmpHash;
// tmpSource = ASCIIEncoding.ASCII.GetBytes(thisPassword); // Turn password into byte array
// tmpHash = md5.ComputeHash(tmpSource);
// StringBuilder sOutput = new StringBuilder(tmpHash.Length);
// for (int i = 0; i < tmpHash.Length; i++)
// {
// sOutput.Append(tmpHash[i].ToString("X2")); // X2 formats to hexadecimal
// }
// return sOutput.ToString();
//}
//public Boolean VerifyHashPassword(string thisPassword, string thisHash)
//{
// Boolean IsValid = false;
// string tmpHash = GenerateHashvalue(thisPassword); // Call the routine on user input
// if (tmpHash == thisHash) IsValid = true; // Compare to previously generated hash
// return IsValid;
//}
public string GenerateHashvalue(string toEncrypt, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
// Get the key from config file
string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));
//System.Windows.Forms.MessageBox.Show(key);
if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
/// <summary>
/// DeCrypt a string using dual encryption method. Return a DeCrypted clear string
/// </summary>
/// <param name="cipherString">encrypted string</param>
/// <param name="useHashing">Did you use hashing to encrypt this data? pass true is yes</param>
/// <returns></returns>
public string Decrypt(string cipherString, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = Convert.FromBase64String(cipherString);
System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
//Get your key from config file to open the lock!
string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));
if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
return UTF8Encoding.UTF8.GetString(resultArray);
}
}
}
评论
质量真的很差。 1)ECB模式(这也意味着没有IV)2)3DES 3)混淆密钥和密码。 4)命名错误5)没有MAC
– CodesInChaos
2014年4月10日在10:28
#25 楼
为简单起见,我为自己创建了用于非加密目的的此功能:将“ yourpassphrase”替换为您的密码...using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace My
{
public class strCrypto
{
// This constant string is used as a "salt" value for the PasswordDeriveBytes function calls.
// This size of the IV (in bytes) must = (keysize / 8). Default keysize is 256, so the IV must be
// 32 bytes long. Using a 16 character string here gives us 32 bytes when converted to a byte array.
private const string initVector = "r5dm5fgm24mfhfku";
private const string passPhrase = "yourpassphrase"; // email password encryption password
// This constant is used to determine the keysize of the encryption algorithm.
private const int keysize = 256;
public static string encryptString(string plainText)
{
//if the plaintext is empty or null string just return an empty string
if (plainText == "" || plainText == null )
{
return "";
}
byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
byte[] keyBytes = password.GetBytes(keysize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
return Convert.ToBase64String(cipherTextBytes);
}
public static string decryptString(string cipherText)
{
//if the ciphertext is empty or null string just return an empty string
if (cipherText == "" || cipherText == null )
{
return "";
}
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
byte[] keyBytes = password.GetBytes(keysize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
}
}
评论
1)关键推导中没有盐2)常数IV,它错过了IV的全部要点。每种加密应该不同。 3)没有身份验证=>填充oracle是一个威胁4)加密器。TransformFinalBlock比使用那些内存和加密流更简单。
– CodesInChaos
2014年4月23日在16:09
#26 楼
using System;
using System.Data;
using System.Configuration;
using System.Text;
using System.Security.Cryptography;
namespace Encription
{
class CryptorEngine
{
public static string Encrypt(string ToEncrypt, bool useHasing)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(ToEncrypt);
//System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
string Key = "Bhagwati";
if (useHasing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(Key));
hashmd5.Clear();
}
else
{
keyArray = UTF8Encoding.UTF8.GetBytes(Key);
}
TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();
tDes.Key = keyArray;
tDes.Mode = CipherMode.ECB;
tDes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tDes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tDes.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
public static string Decrypt(string cypherString, bool useHasing)
{
byte[] keyArray;
byte[] toDecryptArray = Convert.FromBase64String(cypherString);
//byte[] toEncryptArray = Convert.FromBase64String(cypherString);
//System.Configuration.AppSettingsReader settingReader = new AppSettingsReader();
string key = "Bhagwati";
if (useHasing)
{
MD5CryptoServiceProvider hashmd = new MD5CryptoServiceProvider();
keyArray = hashmd.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd.Clear();
}
else
{
keyArray = UTF8Encoding.UTF8.GetBytes(key);
}
TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();
tDes.Key = keyArray;
tDes.Mode = CipherMode.ECB;
tDes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tDes.CreateDecryptor();
try
{
byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length);
tDes.Clear();
return UTF8Encoding.UTF8.GetString(resultArray,0,resultArray.Length);
}
catch (Exception ex)
{
throw ex;
}
}
}
}
评论
ECB密码模式不是很大的禁忌吗?
– John Bubriski♦
2012年1月27日20:14
是的,ECB是最不安全的选择。请参阅MS的注释:“重要:不建议使用此模式,因为它为多种安全利用打开了方便之门。” msdn.microsoft.com/zh-CN/library/…
–丰富
2012年12月5日上午10:34
#27 楼
我想用我用AESRfc2898DeriveBytes
(此处为文档)algorhytm的代码(用C#(.NET Framework 4)编写,并且也可以在有限的平台上完全正常工作)为我做出贡献,例如适用于Windows Phone 7.0+的.NET Compact Framework。所有平台都支持.NET框架的每种加密方法!)。希望这对任何人都可以有所帮助!
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public static class Crypto
{
private static readonly byte[] IVa = new byte[] { 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x11, 0x11, 0x12, 0x13, 0x14, 0x0e, 0x16, 0x17 };
public static string Encrypt(this string text, string salt)
{
try
{
using (Aes aes = new AesManaged())
{
Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(salt));
aes.Key = deriveBytes.GetBytes(128 / 8);
aes.IV = aes.Key;
using (MemoryStream encryptionStream = new MemoryStream())
{
using (CryptoStream encrypt = new CryptoStream(encryptionStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
byte[] cleanText = Encoding.UTF8.GetBytes(text);
encrypt.Write(cleanText, 0, cleanText.Length);
encrypt.FlushFinalBlock();
}
byte[] encryptedData = encryptionStream.ToArray();
string encryptedText = Convert.ToBase64String(encryptedData);
return encryptedText;
}
}
}
catch
{
return String.Empty;
}
}
public static string Decrypt(this string text, string salt)
{
try
{
using (Aes aes = new AesManaged())
{
Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(salt));
aes.Key = deriveBytes.GetBytes(128 / 8);
aes.IV = aes.Key;
using (MemoryStream decryptionStream = new MemoryStream())
{
using (CryptoStream decrypt = new CryptoStream(decryptionStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
{
byte[] encryptedData = Convert.FromBase64String(text);
decrypt.Write(encryptedData, 0, encryptedData.Length);
decrypt.Flush();
}
byte[] decryptedData = decryptionStream.ToArray();
string decryptedText = Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);
return decryptedText;
}
}
}
catch
{
return String.Empty;
}
}
}
}
评论
1)为什么要使用名为IVa的变量,该变量不是IV,而是密码? 2)为什么要设置IV = Key?每种加密都需要一个新的随机IV。 3)MAC不足会导致填充Oracle攻击
– CodesInChaos
13年8月14日在16:44
#28 楼
您必须使用System.Security.Cryptography使用名称空间; useHashing是布尔类型true或false。字符串变量“ key”对于加密和解密应该相同。//Encryption
public string EncryptText(string toEncrypt, bool useHashing)
{
try
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
string key = "String Key Value"; //Based on this key stirng is encrypting
//System.Windows.Forms.MessageBox.Show(key);
//If hashing use get hashcode regards to your key
if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
//Always release the resources and flush data
//of the Cryptographic service provide. Best Practice
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
//set the secret key for the tripleDES algorithm
tdes.Key = keyArray;
//mode of operation. there are other 4 modes. We choose ECB(Electronic code Book)
tdes.Mode = CipherMode.ECB;
//padding mode(if any extra byte added)
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateEncryptor();
//transform the specified region of bytes array to resultArray
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
//Release resources held by TripleDes Encryptor
tdes.Clear();
//Return the encrypted data into unreadable string format
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
catch (Exception e)
{
throw e;
}
}
//Decryption
public string DecryptText(string cipherString, bool useHashing)
{
try
{
byte[] keyArray;
//get the byte code of the string
byte[] toEncryptArray = Convert.FromBase64String(cipherString);
string key = "String Key Value"; //Based on this key string is decrypted
if (useHashing)
{
//if hashing was used get the hash code with regards to your key
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
//release any resource held by the MD5CryptoServiceProvider
hashmd5.Clear();
}
else
{
//if hashing was not implemented get the byte code of the key
keyArray = UTF8Encoding.UTF8.GetBytes(key);
}
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
//set the secret key for the tripleDES algorithm
tdes.Key = keyArray;
//mode of operation. there are other 4 modes.
//We choose ECB(Electronic code Book)
tdes.Mode = CipherMode.ECB;
//padding mode(if any extra byte added)
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock
(toEncryptArray, 0, toEncryptArray.Length);
//Release resources held by TripleDes Encryptor
tdes.Clear();
//return the Clear decrypted TEXT
return UTF8Encoding.UTF8.GetString(resultArray);
}
catch (Exception ex)
{
throw ex;
}
}
评论
-1 1)ECB模式非常弱2)MAC不足使您容易受到主动攻击,例如填充预言。 3)为什么现在仍然使用3DES?它没有损坏,但是AES显然是更好的选择。
– CodesInChaos
2015年2月19日在21:34
#29 楼
BCrypt是一种安全地对数据进行散列的好算法:bcrypt除了包含盐以防止彩虹表攻击外,
bcrypt是一种自适应功能:随着时间的推移,迭代计数可以增加
使其变慢,因此即使提高了计算能力,它仍然可以抵抗暴力搜索攻击。
.NET有一个不错的.NET实现BCrypt也可以作为NuGet包提供。
评论
该问题询问如何加密和解密字符串。除非我遗漏了一些东西,否则如何在BCrypt中解密字符串? BCrypt,尽管它的名字,是一个哈希函数。
–The1nk
16年7月1日在15:50
评论
检查此链接codeproject.com/KB/recipes/Encrypt_an_string.aspx需要一些简单的方法...此链接对我有用saipanyam.net/2010/03/encrypt-query-strings.html
我强烈建议删除3DES并使用AES-GCM。在.NET 4.5加密库中找不到AES-GCM,它与“常规AES”(通常为AES-CBC模式)不同。由于我不愿透露密码,AES-GCM远远优于“常规” AES。因此,在此Bouncy Castle AES-GCM小节中,jbtule具有最佳答案。如果您不相信我们,请至少相信NSA的专家(NSA Suite B @ nsa.gov/ia/programs/suiteb_cryptography/index.shtml:Galois / Counter模式(GCM)是首选的AES模式。)
@Sid我个人在大多数情况下都更喜欢AES-CBC + HMAC-SHA2,而不是AES-GCM。如果您重复使用随机数,则GCM将会严重失败。
@Sid Nonce重用是一个坏主意,是的。但是,即使有能力的程序员/密码学家,我也看到过这种情况的发生。如果发生这种情况,则GCM会完全崩溃,而CBC + HMAC只会出现一些小弱点。使用类似SSL的协议,GCM很好,但是我不满意它作为标准的“加密和认证” API。