排名
7
文章
192
粉丝
15
评论
16
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256


欢迎加群交流技术

前言
在配置文件中,数据库连接字符串,缓存链接字符串等敏感信息,需要配置成加密形式。今天记录一下工作经验
我使用的是RSA加密
先安装依赖包
首先生成公钥私钥
公钥与私钥是匹配的,公钥加密过后使用对应的私钥进行解密
- /// <summary>
- /// 生成PEM格式的公钥和密钥
- /// </summary>
- /// <param name="strength">长度</param>
- /// <returns>Item1:公钥;Item2:私钥;</returns>
- public static (string, string) CreateKeyPair(int strength = 1024)
- {
- RsaKeyPairGenerator r = new RsaKeyPairGenerator();
- r.Init(new KeyGenerationParameters(new SecureRandom(), strength));
- AsymmetricCipherKeyPair keys = r.GenerateKeyPair();
- TextWriter privateTextWriter = new StringWriter();
- PemWriter privatePemWriter = new PemWriter(privateTextWriter);
- privatePemWriter.WriteObject(keys.Private);
- privatePemWriter.Writer.Flush();
- TextWriter publicTextWriter = new StringWriter();
- PemWriter publicPemWriter = new PemWriter(publicTextWriter);
- publicPemWriter.WriteObject(keys.Public);
- publicPemWriter.Writer.Flush();
- return (publicTextWriter.ToString(), privateTextWriter.ToString());
- }
RSA加密算法
- /// <summary>
- /// RSA加密
- /// </summary>
- /// <param name="publicKey">公钥</param>
- /// <param name="decryptstring">待加密的字符串(Base64)</param>
- /// <returns>加密后的字符串</returns>
- public static string Crypt(string publicKey, string decryptstring)
- {
- decryptstring = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(decryptstring));
- using (TextReader reader = new StringReader(publicKey))
- {
- dynamic key = new PemReader(reader).ReadObject();
- var rsaDecrypt = new Pkcs1Encoding(new RsaEngine());
- if (key is AsymmetricKeyParameter)
- {
- key = (AsymmetricKeyParameter)key;
- }
- else if (key is AsymmetricCipherKeyPair)
- {
- key = ((AsymmetricCipherKeyPair)key).Private;
- }
- rsaDecrypt.Init(true, key); //这里加密是true;解密是false
-
- byte[] entData = Convert.FromBase64String(decryptstring);
- entData = rsaDecrypt.ProcessBlock(entData, 0, entData.Length);
- return Convert.ToBase64String(entData);
- }
- }
RSA解密算法
- /// <summary>
- /// RSA解密,解密失败返回原字符串
- /// </summary>
- /// <param name="privateKey">私钥</param>
- /// <param name="decryptstring">待解密的字符串(Base64)</param>
- /// <returns>解密后的字符串</returns>
- public static string Decrypt(string privateKey, string decryptstring)
- {
- try
- {
- using (TextReader reader = new StringReader(privateKey))
- {
- dynamic key = new PemReader(reader).ReadObject();
- var rsaDecrypt = new Pkcs1Encoding(new RsaEngine());
- if (key is AsymmetricKeyParameter)
- {
- key = (AsymmetricKeyParameter)key;
- }
- else if (key is AsymmetricCipherKeyPair)
- {
- key = ((AsymmetricCipherKeyPair)key).Private;
- }
- rsaDecrypt.Init(false, key); //这里加密是true;解密是false
-
- byte[] entData = Convert.FromBase64String(decryptstring);
- entData = rsaDecrypt.ProcessBlock(entData, 0, entData.Length);
- return Encoding.UTF8.GetString(entData);
- }
- }
- catch (Exception e)
- {
- return decryptstring;
- }
- }
评价