Encrypting & Decrypting a String in C#
在C中,满足以下要求的最现代(最好)方法是什么?
1 2 3 | string encryptedString = SomeStaticClass.Encrypt(sourceString); string decryptedString = SomeStaticClass.Decrypt(encryptedString); |
但最少的小题大做涉及盐,钥匙,弄脏字节[]等。
一直在谷歌搜索和困惑我的发现(你可以看到类似的清单,所以Q看到这是一个欺骗性的问题问)。
更新时间:2015年12月23日:由于这个答案似乎得到了很多的支持,我更新了它来修复愚蠢的错误,并根据评论和反馈来改进代码。有关具体改进的列表,请参见文章的结尾。
正如其他人所说,密码学并不简单,所以最好避免"滚动自己的"加密算法。
但是,您可以围绕类似于内置
Rijndael是当前高级加密标准的算法名称,因此您肯定使用了一种可以被视为"最佳实践"的算法。
下面的类是我前一段时间编写的一个类,用于执行您所追求的类型,它是一个简单的单一方法调用,允许使用基于字符串的密码对一些基于字符串的明文进行加密,生成的加密字符串也被表示为一个字符串。当然,有一种等价的方法可以用相同的密码解密加密字符串。
与此代码的第一个版本(每次使用完全相同的salt和iv值)不同,此较新版本将每次生成随机salt和iv值。由于给定字符串的加密和解密之间的salt和iv必须相同,因此salt和iv在加密时被预先设置为密码文本,并再次从中提取,以便执行解密。其结果是,用完全相同的密码对完全相同的明文进行加密,每次得到完全不同的密文结果。
使用它的"优势"来自于使用
最后,需要注意的是,这仍然是未经身份验证的加密。加密仅提供隐私(即第三方不知道消息),而认证加密旨在提供隐私和真实性(即收件人知道消息是由发件人发送的)。
在不知道您的确切需求的情况下,很难说这里的代码是否足够安全,以满足您的需求,但是,它的产生是为了在相对简单的实现与"质量"之间实现良好的平衡。例如,如果加密字符串的"接收者"直接从受信任的"发送者"接收该字符串,则可能不需要进行身份验证。
如果您需要更复杂的东西,并且需要提供经过身份验证的加密,请查看本文中的实现。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | using System; using System.Text; using System.Security.Cryptography; using System.IO; using System.Linq; namespace EncryptStringSample { public static class StringCipher { // 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 = 256; // 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 = Generate256BitsOfRandomEntropy(); var ivStringBytes = Generate256BitsOfRandomEntropy(); 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 = 256; symmetricKey.Mode = CipherMode.CBC; symmetricKey.Padding = PaddingMode.PKCS7; using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes)) { using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes. var cipherTextBytes = saltStringBytes; cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray(); cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray(); memoryStream.Close(); cryptoStream.Close(); return Convert.ToBase64String(cipherTextBytes); } } } } } } public static string 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 = 256; 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[] Generate256BitsOfRandomEntropy() { var randomBytes = new byte[32]; // 32 Bytes will give us 256 bits. using (var rngCsp = new RNGCryptoServiceProvider()) { // Fill the array with cryptographically secure random bytes. rngCsp.GetBytes(randomBytes); } return randomBytes; } } } |
上面的类可以非常简单地与类似于以下代码一起使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | using System; namespace EncryptStringSample { class Program { static void Main(string[] args) { Console.WriteLine("Please enter a password to use:"); string password = Console.ReadLine(); Console.WriteLine("Please enter a string to encrypt:"); string plaintext = Console.ReadLine(); Console.WriteLine(""); Console.WriteLine("Your encrypted string is:"); string encryptedstring = StringCipher.Encrypt(plaintext, password); Console.WriteLine(encryptedstring); Console.WriteLine(""); Console.WriteLine("Your decrypted string is:"); string decryptedstring = StringCipher.Decrypt(encryptedstring, password); Console.WriteLine(decryptedstring); Console.WriteLine(""); Console.WriteLine("Press any key to exit..."); Console.ReadLine(); } } } |
(您可以在这里下载一个简单的VS2013示例解决方案(包括一些单元测试)。
2015年12月23日更新:代码的具体改进列表如下:
- 修正了加密和解密。由于生成salt&iv值的机制发生了变化,因此不再需要编码。
- 由于salt/iv的更改,先前的代码注释错误地指示16个字符串的utf8编码产生32个字节不再适用(因为不再需要编码)。
- 被取代的pbkdf1算法的使用已经被更现代的pbkdf2算法所取代。
- 密码派生现在被适当地加盐,而以前根本没有加盐(另一个愚蠢的错误被压扁)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | using System.IO; using System.Text; using System.Security.Cryptography; public static class EncryptionHelper { public static string Encrypt(string clearText) { string EncryptionKey ="abc123"; 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; } public static string Decrypt(string cipherText) { string EncryptionKey ="abc123"; 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; } } |
试试这个班:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | public class DataEncryptor { TripleDESCryptoServiceProvider symm; #region Factory public DataEncryptor() { this.symm = new TripleDESCryptoServiceProvider(); this.symm.Padding = PaddingMode.PKCS7; } public DataEncryptor(TripleDESCryptoServiceProvider keys) { this.symm = keys; } public DataEncryptor(byte[] key, byte[] iv) { this.symm = new TripleDESCryptoServiceProvider(); this.symm.Padding = PaddingMode.PKCS7; this.symm.Key = key; this.symm.IV = iv; } #endregion #region Properties public TripleDESCryptoServiceProvider Algorithm { get { return symm; } set { symm = value; } } public byte[] Key { get { return symm.Key; } set { symm.Key = value; } } public byte[] IV { get { return symm.IV; } set { symm.IV = value; } } #endregion #region Crypto public byte[] Encrypt(byte[] data) { return Encrypt(data, data.Length); } public byte[] Encrypt(byte[] data, int length) { try { // Create a MemoryStream. var ms = new MemoryStream(); // Create a CryptoStream using the MemoryStream // and the passed key and initialization vector (IV). var cs = new CryptoStream(ms, symm.CreateEncryptor(symm.Key, symm.IV), CryptoStreamMode.Write); // Write the byte array to the crypto stream and flush it. cs.Write(data, 0, length); cs.FlushFinalBlock(); // Get an array of bytes from the // MemoryStream that holds the // encrypted data. byte[] ret = ms.ToArray(); // Close the streams. cs.Close(); ms.Close(); // Return the encrypted buffer. return ret; } catch (CryptographicException ex) { Console.WriteLine("A cryptographic error occured: {0}", ex.Message); } return null; } public string EncryptString(string text) { return Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(text))); } public byte[] Decrypt(byte[] data) { return Decrypt(data, data.Length); } public byte[] Decrypt(byte[] data, int length) { try { // Create a new MemoryStream using the passed // array of encrypted data. MemoryStream ms = new MemoryStream(data); // Create a CryptoStream using the MemoryStream // and the passed key and initialization vector (IV). CryptoStream cs = new CryptoStream(ms, symm.CreateDecryptor(symm.Key, symm.IV), CryptoStreamMode.Read); // Create buffer to hold the decrypted data. byte[] result = new byte[length]; // Read the decrypted data out of the crypto stream // and place it into the temporary buffer. cs.Read(result, 0, result.Length); return result; } catch (CryptographicException ex) { Console.WriteLine("A cryptographic error occured: {0}", ex.Message); } return null; } public string DecryptString(string data) { return Encoding.UTF8.GetString(Decrypt(Convert.FromBase64String(data))).TrimEnd('\0'); } #endregion } |
像这样使用:
1 2 3 4 5 6 | string message="A very secret message here."; DataEncryptor keys=new DataEncryptor(); string encr=keys.EncryptString(message); // later string actual=keys.DecryptString(encr); |
如果需要将密码存储在内存中并希望对其进行加密,则应使用SecureString:
http://msdn.microsoft.com/en-us/library/system.security.securestring.aspx
对于更一般的使用,我将使用FIPS批准的算法,如高级加密标准,以前称为rijndael。有关实现示例,请参见本页:
http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndael.aspx
如果您的目标是尚未支持
首先,将应用程序配置为使用数据保护:
1 2 3 4 5 6 7 8 | public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddDataProtection(); } // ... } |
然后您就可以注入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public class MyService : IService { private const string Purpose ="my protection purpose"; private readonly IDataProtectionProvider _provider; public MyService(IDataProtectionProvider provider) { _provider = provider; } public string Encrypt(string plainText) { var protector = _provider.CreateProtector(Purpose); return protector.Protect(plainText); } public string Decrypt(string cipherText) { var protector = _provider.CreateProtector(Purpose); return protector.Unprotect(cipherText); } } |
有关详细信息,请参阅本文。
您可能正在查找
我见过的最简单的加密方法是通过RSA
查看其上的msdn:http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoServiceProvider.aspx
它确实涉及到使用字节,但是当涉及到它时,你确实希望加密和解密很难理解,否则它将很容易被黑客攻击。