目录
一、数据加密标准 - Data Encryption Standard(DES)
二、高级加密标准 - Advanced Encryption Standard(AES)
三、消息摘要算法第五版 - Message-Digest Algorithm 5(MD5)
四、安全哈希算法 - Secure Hash Algorithm(SHA1)
五、公钥加密算法(RSA)
六、干扰项 - 盐(Salt)
七、RSA密钥格式Pkcs8
八、源码下载
数据加密标准 - Data Encryption Standard(DES)
简介
DES全称为Data Encryption Standard,即数据加密标准,是一种使用密钥加密的块算法,1976年被美国联邦政府的国家标准局确定为联邦资料处理标准(FIPS),随后在国际上广泛流传开来。
核心代码
public class DesCryptoUtil : IDesCryptoUtil { /// <summary> /// The key, length is 8, generated on https://www.random.org/strings/ /// You can also use the GenerateKey method in the DESCryptoServiceProvider to generate the key. /// </summary> private static readonly byte[] Key = Encoding.ASCII.GetBytes("0e3Nl9Z9"); /// <summary> /// The iv, length is 8, generated on https://www.random.org/strings/ /// You can also use the GenerateIV method in the DESCryptoServiceProvider to generate the iv. /// </summary> private static readonly byte[] Iv = Encoding.ASCII.GetBytes("62EcX79F"); public byte[] Encrypt(byte[] plainBytes) { using (var provider = new DESCryptoServiceProvider()) { provider.Key = Key; provider.IV = Iv; using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, provider.CreateEncryptor(), CryptoStreamMode.Write)) { cryptoStream.Write(plainBytes, 0, plainBytes.Length); cryptoStream.FlushFinalBlock(); } return memoryStream.ToArray(); } } } public byte[] Decrypt(byte[] encryptedBytes) { using (var provider = new DESCryptoServiceProvider()) { provider.Key = Key; provider.IV = Iv; using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, provider.CreateDecryptor(), CryptoStreamMode.Write)) { cryptoStream.Write(encryptedBytes, 0, encryptedBytes.Length); cryptoStream.FlushFinalBlock(); } return memoryStream.ToArray(); } } } }
调用示例
[TestCase("123456")] [TestCase("abcdef")] public void Encrypt(string plainText) { var plainBytes = Encoding.UTF8.GetBytes(plainText); var encryptedBytes = _desCryptoUtil.Encrypt(plainBytes); var encryptedText = Convert.ToBase64String(encryptedBytes); Console.WriteLine("Plain text:{0}, encrypted text:{1}", plainText, encryptedText); } [TestCase("ecIwYJUsLa0=")] [TestCase("iPsXCjS+O0c=")] public void Decrypt(string encryptedText) { var encryptedBytes = Convert.FromBase64String(encryptedText); var plainBytes = _desCryptoUtil.Decrypt(encryptedBytes); var plainText = Encoding.UTF8.GetString(plainBytes); Console.WriteLine("Encrypted text:{0}, plain text:{1}", encryptedText, plainText); }
高级加密标准 - Advanced Encryption Standard(AES)
简介
高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。经过五年的甄选流程,高级加密标准由美国国家标准与技术研究院(NIST)于2001年11月26日发布于FIPS PUB 197,并在2002年5月26日成为有效的标准。2006年,高级加密标准已然成为对称密钥加密中最流行的算法之一。
核心代码
public class AesCryptoUtil : IAesCryptoUtil { /// <summary> /// A system key and the length should be 16. /// You can use tool to generate the string on https://www.random.org/strings/ or other website. /// </summary> private const string SystemKeyPart = "84ImUeBn432oPkqo"; /// <summary> /// A custom key and the lenth should between 4 and 16. You can use the project name as the custom key. /// </summary> private const string UserKeyPart = "AecCrypto"; /// <summary> /// The combine key. /// </summary> private static readonly byte[] Key = Encoding.ASCII.GetBytes(UserKeyPart.PadRight(16, ‘#‘) + SystemKeyPart); /// <summary> /// Please indicate a random string here, and the length must be 16. /// You can use tool to generate the string on https://www.random.org/strings/ or other website. /// </summary> private static readonly byte[] Iv = Encoding.ASCII.GetBytes("bCNtStALc7bRqREq"); public byte[] Encrypt(byte[] plainBytes) { return Encrypt(plainBytes, CipherMode.CBC, PaddingMode.PKCS7); } public byte[] Decrypt(byte[] encryptedBytes) { return Decrypt(encryptedBytes, CipherMode.CBC, PaddingMode.PKCS7); } private static byte[] Encrypt(byte[] plainBytes, CipherMode cipher, PaddingMode padding) { using (var aes = Rijndael.Create()) { aes.Mode = cipher; aes.Padding = padding; using (var transform = aes.CreateEncryptor(Key, Iv)) { var encryptedBytes = transform.TransformFinalBlock(plainBytes, 0, plainBytes.Length); return encryptedBytes; } } } private static byte[] Decrypt(byte[] encryptedBytes, CipherMode cipher, PaddingMode padding) { using (var aes = Rijndael.Create()) { aes.Mode = cipher; aes.Padding = padding; using (var transform = aes.CreateDecryptor(Key, Iv)) { var plainBytes = transform.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length); return plainBytes; } } } }
调用示例
[TestCase("123456")] [TestCase("abcdef")] public void Encrypt(string plainText) { var plainBytes = Encoding.UTF8.GetBytes(plainText); var encryptedBytes = _aesCryptoUtil.Encrypt(plainBytes); var encryptedText = Convert.ToBase64String(encryptedBytes); Console.WriteLine("Plain text:{0}, encrypted text:{1}", plainText, encryptedText); } [TestCase("HDHlYOQuENPmtjFKvLZIEA==")] [TestCase("YO3ErLZ5/izaDgD0M0uYDg==")] public void Decrypt(string encryptedText) { var encryptedBytes = Convert.FromBase64String(encryptedText); var plainBytes = _aesCryptoUtil.Decrypt(encryptedBytes); var plainText = Encoding.UTF8.GetString(plainBytes); Console.WriteLine("Encrypted text:{0}, plain text:{1}", encryptedText, plainText); }
消息摘要算法第五版 - Message-Digest Algorithm 5(MD5)
简介
MD5即Message-Digest Algorithm 5(信息-摘要算法5),用于确保信息传输完整一致。是计算机广泛使用的杂凑算法之一(又译摘要算法、哈希算法),主流编程语言普遍已有MD5实现。将数据(如汉字)运算为另一固定长度值,是杂凑算法的基础原理,MD5的前身有MD2、MD3和MD4。
MD5算法具有以下特点:
1、压缩性:任意长度的数据,算出的MD5值长度都是固定的。
2、容易计算:从原数据计算出MD5值很容易。
3、抗修改性:对原数据进行任何改动,哪怕只修改1个字节,所得到的MD5值都有很大区别。
4、强抗碰撞:已知原数据和其MD5值,想找到一个具有相同MD5值的数据(即伪造数据)是非常困难的。
注:MD5常用于密码加密。
核心代码
public class Md5CryptoUtil : IMd5CryptoUtil { public byte[] Encrypt(byte[] plainBytes) { using (var md5 = MD5.Create()) { var encryptedBytes = md5.ComputeHash(plainBytes); return encryptedBytes; } } }
调用示例
[TestCase("123456")] [TestCase("abcdef")] public void Encrypt(string plainText) { var plainBytes = Encoding.UTF8.GetBytes(plainText); var encryptedBytes = _md5CryptoUtil.Encrypt(plainBytes); var stringBuilder = new StringBuilder(); foreach (var b in encryptedBytes) { stringBuilder.AppendFormat("{0:X2}", b); } var encryptedText = stringBuilder.ToString(); Console.WriteLine("Plain text:{0}, encrypted text:{1}", plainText, encryptedText); }
安全哈希算法 - Secure Hash Algorithm(SHA1)
简介
安全哈希算法(Secure Hash Algorithm)主要适用于数字签名标准 (Digital Signature Standard DSS)里面定义的数字签名算法(Digital Signature Algorithm DSA)。对于长度小于2^64位的消息,SHA1会产生一个160位的消息摘要。当接收到消息的时候,这个消息摘要可以用来验证数据的完整性。在传输的过程中,数据很可能会发生变化,那么这时候就会产生不同的消息摘要。 SHA1有如下特性:不可以从消息摘要中复原信息;两个不同的消息不会产生同样的消息摘要,(但会有1x10 ^ 48分之一的机率出现相同的消息摘要,一般使用时忽略)。
核心代码
public class Sha1CryptoUtil : ISha1CryptoUtil { public byte[] Encrypt(byte[] plainBytes) { using (var sha1 = SHA1.Create()) { var encryptedBytes = sha1.ComputeHash(plainBytes); return encryptedBytes; } } }
调用示例
[TestCase("123456")] [TestCase("abcdef")] public void Encrypt(string plainText) { var plainBytes = _bytesUtil.FromString(plainText); var encryptedBytes = _sha1CryptoUtil.Encrypt(plainBytes); var encryptedText = _bytesUtil.ToHex(encryptedBytes); Console.WriteLine("Plain text:{0}, encrypted text:{1}", plainText, encryptedText); }
公钥加密算法(RSA)
简介
RSA公钥加密算法是1977年由罗纳德·李维斯特(Ron Rivest)、阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的。
RSA是目前最有影响力的公钥加密算法,它能够抵抗到目前为止已知的绝大多数密码攻击,已被ISO推荐为公钥数据加密标准。
RSA算法基于一个十分简单的数论事实:将两个大素数相乘十分容易,但是想要对其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥。
核心代码
public class RsaCryptoUtil : IRsaCryptoUtil { public RsaKey GenerateKeys() { using (var rsa = new RSACryptoServiceProvider()) { var key = new RsaKey { Private = rsa.ToXmlString(true), Public = rsa.ToXmlString(false) }; return key; } } public byte[] Sign(byte[] bytes, string privateKey) { using (var rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(privateKey); var signature = rsa.SignData(bytes, new MD5CryptoServiceProvider()); return signature; } } public bool Verify(byte[] bytes, byte[] signature, string publicKey) { using (var rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(publicKey); return rsa.VerifyData(bytes, new MD5CryptoServiceProvider(), signature); } } public byte[] Encrypt(byte[] plainBytes, string publicKey) { using (var rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(publicKey); var encryptedBytes = rsa.Encrypt(plainBytes, false); return encryptedBytes; } } public byte[] Decrypt(byte[] encryptedBytes, string privateKey) { using (var rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(privateKey); var decryptedBytes = rsa.Decrypt(encryptedBytes, false); return decryptedBytes; } } }
调用示例
[TestCase("123456")] [TestCase("abcdef")] public void Sign(string text) { var bytes = _bytesUtil.FromString(text); var signatureBytes = _rsaCryptoUtil.Sign(bytes, _key.Private); var signature = _bytesUtil.ToBase64(signatureBytes); Console.WriteLine("Text:{0}, signature:{1}", text, signature); } [TestCase("123456", "T5BS2WHA2ZvDexuEIPRSbnB7SlC1blNPi4BGcwiGovE54bmAiLIqf6p9dmsMMS+wgyKX2JPKkiNKtzts+q1yVmosqqjcmrNZbP+YF9YNqbO4Da0CJRjH1rwCa+XC7cJFKIDn85KQqtLpdr7yong0SjtXA+cDMD3dP9RoZLb+k/k=")] [TestCase("abcdef", "Gxf9LGx2AFmW114ex7nemDXIiEXkYmBA4bR0SMWp4M/uule171rtPIyZlX17CeNM2kmNKtxYAqsJj0Pfxb1znydtNLo/lFNkZDZkxAMx7uTLdw9Os4g5ZKXKkBbYi3aYBNY0bbICfetGRNGaGU4p8HlKm+KrijbURBKH6wE1DyI=")] public void Verify(string text, string signature) { var bytes = _bytesUtil.FromString(text); var signatureBytes = _bytesUtil.FromBase64(signature); var isVerified = _rsaCryptoUtil.Verify(bytes, signatureBytes, _key.Public); Console.WriteLine("Text:{0}, signature:{1}, is verified:{2}", text, signature, isVerified); } [TestCase("123456")] [TestCase("abcdef")] public void Encrypt(string plainText) { var plainBytes = _bytesUtil.FromString(plainText); var encryptedBytes = _rsaCryptoUtil.Encrypt(plainBytes, _key.Public); var encryptedText = _bytesUtil.ToBase64(encryptedBytes); Console.WriteLine("Plain text:{0}, encrypted text:{1}", plainText, encryptedText); } [TestCase("ZfT/2r0VqY6LX8eL+rfgufT/q+kMZsvRcDK6NafoHb+zvBN5KNxI5MAIG07Oqe3EiRH3yXrjKnePUiVvPJGW40xHm6S2yRBar61ZB3DONavwjlKQBBPGJNuW1S8aevdxFIGHazFjzv7FMCcJaAFrnNlZlkdsk67z0FbubPylPbY=")] [TestCase("m8rS9i1DGE6MqW0L6vcS+lthiBzFTWrfK4XS97TDyC8t0xecNsLteIGEDgrzUMVf9j0ue0HpGHslYiOUAiX1wnFcVM0aX3SAZ1NmsIFEoYhz3av3lPj/tX9Ccirn7YhQw/N5BHwxPYT3ZcRfy+ozVXBo0EFDNGoJMcysfA0u5Uk=")] public void Decrypt(string encryptedText) { var encryptedBytes = _bytesUtil.FromBase64(encryptedText); var plainBytes = _rsaCryptoUtil.Decrypt(encryptedBytes, _key.Private); var plainText = _bytesUtil.ToString(plainBytes); Console.WriteLine("Encrypted text:{0}, plain text:{1}", encryptedText, plainText); }
干扰项 - 盐(Salt)
简介
相同的明文用同样的加密方法(如MD5)进行加密会得到相同的密文。
如用MD5的方式加密“123456”,你总会得到密文“E10ADC3949BA59ABBE56E057F20F883E”。
那么,当数据库信息泄漏时,如果你的密码设置的比较简单,对方是很容易猜到你的密码,或者通过彩虹表来破解你的密码。
因此,你需要在明文中添加干扰项-盐(Salt)。
对于加盐的方式,我认为有两种。
1.对于只加密,但不解密的算法,如MD5,SHA1。我们需要把盐和密文都存在数据库中,用户输入密码时,我们把用户密码和盐组成新的明文,进行加密,然后得到密文,最后对比该密文是否与库中密文匹配。
2.对于可加解密的算法,我们可以定义一些规则,如明文前加长度为3的盐,在明文后加长度为5的盐,然后进行加密。解密的时候可以按预先设置的规则把盐去掉就能得到真正的明文。
核心代码
public class SaltUtil : ISaltUtil { public byte[] GenerateSalt(int size) { using (var rng = new RNGCryptoServiceProvider()) { var salt = new byte[size]; rng.GetBytes(salt); return salt; } } }
调用示例
MD5
[TestCase("123456")] [TestCase("abcdef")] public void EncryptWithSalt(string plainText) { var plainBytes = _bytesUtil.FromString(plainText); var headSalt = _saltUtil.GenerateSalt(SaltSetting.HeadSize); var tailSalt = _saltUtil.GenerateSalt(SaltSetting.TailSize); var plainBytesWithSalts = _bytesUtil.Combine(headSalt, plainBytes, tailSalt); var encryptedBytes = _md5CryptoUtil.Encrypt(plainBytesWithSalts); var encryptedText = _bytesUtil.ToHex(encryptedBytes); Console.WriteLine("Plain text:{0}, encrypted text:{1}", plainText, encryptedText); }
AES
[TestCase("123456")] [TestCase("abcdef")] public void EncryptWithSalt(string plainText) { var plainBytes = _bytesUtil.FromString(plainText); var headSalt = _saltUtil.GenerateSalt(SaltSetting.HeadSize); var tailSalt = _saltUtil.GenerateSalt(SaltSetting.TailSize); var plainBytesWithSalts = _bytesUtil.Combine(headSalt, plainBytes, tailSalt); var encryptedBytes = _aesCryptoUtil.Encrypt(plainBytesWithSalts); var encryptedText = _bytesUtil.ToBase64(encryptedBytes); Console.WriteLine("Plain text:{0}, encrypted text:{1}", plainText, encryptedText); } [TestCase("Leu9NnY9qA3/9u5uUZoXGQ==")] [TestCase("eqcbaEOL9mHlQh3ERnGNeA==")] public void DecryptWithSalt(string encryptedText) { var encryptedBytes = _bytesUtil.FromBase64(encryptedText); var plainBytesWithSalts = _aesCryptoUtil.Decrypt(encryptedBytes); var plainBytes = plainBytesWithSalts.Skip(SaltSetting.HeadSize).Take(plainBytesWithSalts.Length - SaltSetting.HeadSize - SaltSetting.TailSize).ToArray(); var plainText = _bytesUtil.ToString(plainBytes); Console.WriteLine("Encrypted text:{0}, plain text:{1}", encryptedText, plainText); }
RSA密钥格式Pkcs8
简介
对于RSA密钥的格式,不同的语言是不同的,如C#是xml格式,Java是二进制流,其他语言又可能是另外一种格式。为了解决这个问题,一种统一的密钥格式Pkcs8应运而生。
核心代码
public class RsaPkcs8CryptoUtil : IRsaCryptoUtil { public RsaKey GenerateKeys() { using (var rsa = new RSACryptoServiceProvider()) { var keyPair = DotNetUtilities.GetRsaKeyPair(rsa); var key = new RsaKey { Private = GeneratePrivateKey(keyPair.Private), Public = GeneratePublicKey(keyPair.Public) }; return key; } } public byte[] Sign(byte[] bytes, string privateKey) { using (var rsa = new RSACryptoServiceProvider()) { var key = ParsePrivateKey(privateKey); rsa.ImportParameters(key); var signature = rsa.SignData(bytes, new MD5CryptoServiceProvider()); return signature; } } public bool Verify(byte[] bytes, byte[] signature, string publicKey) { using (var rsa = new RSACryptoServiceProvider()) { var key = ParsePublicKey(publicKey); rsa.ImportParameters(key); return rsa.VerifyData(bytes, new MD5CryptoServiceProvider(), signature); } } public byte[] Encrypt(byte[] plainBytes, string publicKey) { using (var rsa = new RSACryptoServiceProvider()) { var key = ParsePublicKey(publicKey); rsa.ImportParameters(key); var encryptedBytes = rsa.Encrypt(plainBytes, false); return encryptedBytes; } } public byte[] Decrypt(byte[] encryptedBytes, string privateKey) { using (var rsa = new RSACryptoServiceProvider()) { var key = ParsePrivateKey(privateKey); rsa.ImportParameters(key); var decryptedBytes = rsa.Decrypt(encryptedBytes, false); return decryptedBytes; } } private static string GeneratePrivateKey(AsymmetricKeyParameter key) { var builder = new StringBuilder(); using (var writer = new StringWriter(builder)) { var pkcs8Gen = new Pkcs8Generator(key); var pemObj = pkcs8Gen.Generate(); var pemWriter = new PemWriter(writer); pemWriter.WriteObject(pemObj); } return builder.ToString(); } private static string GeneratePublicKey(AsymmetricKeyParameter key) { var builder = new StringBuilder(); using (var writer = new StringWriter(builder)) { var pemWriter = new PemWriter(writer); pemWriter.WriteObject(key); } return builder.ToString(); } private static RSAParameters ParsePrivateKey(string privateKey) { using (var reader = new StringReader(privateKey)) { var pemReader = new PemReader(reader); var key = (RsaPrivateCrtKeyParameters)pemReader.ReadObject(); var parameter = new RSAParameters { Modulus = key.Modulus.ToByteArrayUnsigned(), Exponent = key.PublicExponent.ToByteArrayUnsigned(), D = key.Exponent.ToByteArrayUnsigned(), P = key.P.ToByteArrayUnsigned(), Q = key.Q.ToByteArrayUnsigned(), DP = key.DP.ToByteArrayUnsigned(), DQ = key.DQ.ToByteArrayUnsigned(), InverseQ = key.QInv.ToByteArrayUnsigned() }; return parameter; } } private static RSAParameters ParsePublicKey(string publicKey) { using (var reader = new StringReader(publicKey)) { var pemReader = new PemReader(reader); var key = (RsaKeyParameters)pemReader.ReadObject(); var parameter = new RSAParameters { Modulus = key.Modulus.ToByteArrayUnsigned(), Exponent = key.Exponent.ToByteArrayUnsigned() }; return parameter; } } }
调用示例
[TestCase("123456")] [TestCase("abcdef")] public void Sign(string text) { var bytes = _bytesUtil.FromString(text); var signatureBytes = _rsaCryptoUtil.Sign(bytes, _key.Private); var signature = _bytesUtil.ToBase64(signatureBytes); Console.WriteLine("Text:{0}, signature:{1}", text, signature); } [TestCase("123456", "Pj4Z4P1ktNM+MLoqO3WUBZogZjVcjz5cvMVBJ741d2wq1X8UuI2AclZueltRahGHURiJ8djTYCSEGG1oHSc1K0ilk4lz40HFu1mqv65bwglqKrX2ks1wnwnBHusbfiu4HYXNy5HN/fcjB1ah8MxZSofxaGth1xAygY9bKkIBFS0=")] [TestCase("abcdef", "UUOTnyWRU/b4CvALxw4VHusKBXjv32RTjuTVyZHeBaQKvlqVuMCwrdey0Z9wrh20GRspA2Je3uUfbFSxYStDnzVsXJLB3wtNvWX+NcE+h1g1LXijnediJKn6uh4UorCpVru0tZX3XrMJPeY5u8+ZBFMUP8zw078t7w1c60XpioQ=")] public void Verify(string text, string signature) { var bytes = _bytesUtil.FromString(text); var signatureBytes = _bytesUtil.FromBase64(signature); var isVerified = _rsaCryptoUtil.Verify(bytes, signatureBytes, _key.Public); Console.WriteLine("Text:{0}, signature:{1}, is verified:{2}", text, signature, isVerified); } [TestCase("123456")] [TestCase("abcdef")] public void Encrypt(string plainText) { var plainBytes = _bytesUtil.FromString(plainText); var encryptedBytes = _rsaCryptoUtil.Encrypt(plainBytes, _key.Public); var encryptedText = _bytesUtil.ToBase64(encryptedBytes); Console.WriteLine("Plain text:{0}, encrypted text:{1}", plainText, encryptedText); } [TestCase("Ku82IhLYSuthVU1uN5NvUAFImWLwqaHmSuWA8dlTBLjYcJdGJmfY/BMK4JULBUauFDIyYHkFZ2j2oK+lQDw2UuXWbojLrnPZAvAbW+HB/5nuCS1mElVJr7YTq3tHb2mjcwAKx2qSnWgDO9V8akCnMMNVGLg9IN5gnjctlgu44iU=")] [TestCase("hBWYekZUiEiPgQTgVtVB+Ax1UOa6tKkVk4UMU2CjwFpYoOndtJu/Frs/woRdvfJBZbD/lmMOpGoK35mlX9Y0RKrZdLRM0RG8/maiQQFWCM3ELgBWqYkdVLc4RQULxfWaVFuQolXWwVk+gCUaWeCaaMEBZ28dXiUP7npaWexEcB8=")] public void Decrypt(string encryptedText) { var encryptedBytes = _bytesUtil.FromBase64(encryptedText); var plainBytes = _rsaCryptoUtil.Decrypt(encryptedBytes, _key.Private); var plainText = _bytesUtil.ToString(plainBytes); Console.WriteLine("Encrypted text:{0}, plain text:{1}", encryptedText, plainText); }
源码下载
https://github.com/ErikXu/Crypto