目前最流行的加密算法莫过于RSA了,以下是我们.net/.net core C#生成环境用的RSA加密工具类,在此分享给大家。

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text; namespace Common
{
/// <summary>
/// RSA加密工具类
/// </summary>
public class RSACryptoUtil
{
/// <summary>
/// rsa私钥
/// </summary>
private static readonly RSACryptoServiceProvider _privateKeyRsaProvider;
/// <summary>
/// rsa公钥
/// </summary>
private static readonly RSACryptoServiceProvider _publicKeyRsaProvider; static RSACryptoUtil()
{
//string root = AppDomain.CurrentDomain.RelativeSearchPath; string publicKey = @"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqc7Mgsct5yaU+Ihxwz28luI/0xJe/uZQPwkMyOJpz+tDi5p9V0JYaYg3SrhIqkNQFluBBSRCnp1NNzfT3qUn93eJ1g9/8wwBloiK+W0s6DuSQj93+T8ZM1+qnnBOUiNrHBmynjR1frN4CJVmdXP1+w3CqLoMaHkw46Vy5UvEf9yedetjcCwIbmjRJzE2Mv3qQz67HbgQIDAQAB";//File.ReadAllText($"公钥位置", Encoding.ASCII);
string privateKey = @"MIIEpAIBAAKCAQEAqc7Mgsct5yaU+Ihxwz28luI/0xJe/uZQPwkMyOJpz+tDi5p9V0JYaYg3SrhIqkNQFluBBSRCnp1NNzfT3qUn93eJ1g9/8wwBloiK+W0s6DuSQj9picqP0n5bEDxPzfd7kTM1+Cf4SZDpzz7BPDGt2qQc9bE8Cmwj3PSCu0pDo3baIxiz0sWaprYEP/YvLYaJN/5+2mQ0q+yogzSt8WthlTGbMO6IRFre467s/pQbQOzSNPMQsL5lbmtNThUlg3+T8ZM1+qnnBOUiNrHBmynjR1frN4CJVmdXP1+w3CqLoMaHkw46Vy5UvEf9yedetjcCwIbmjRJzE2Mv3qQz67HbgQIDAQABAoIBACWmb5vzk87ztAYjIq46iw0dXy9qnFuCL3q6g/YqlXF/Z+So87wp81pTUKxwv2Fl0CpPyMkQA6Jx2bApf2eN7JMMo4xuY5nOaf9/1zfG1f/3UQZJaB0LPqHsdQrtHN19qn0vzU4m+d2JP0CgYEA5wtsWb17ORg8Dv0ndOHQGIaNzrmKNyaCMz9sph9GKuB7lnASotXfJmk3piyf9D4qj+++j5FKVlnew49SGlUU/SQyD0FvW1w0mAmB5VHTa8qEP5EtB8x2hfrAh0Z1dAqnc6Oo+TWbID1tLR6xfR2UBKiIKI7N6vz543wbjmeQ7uMCgYEAvCYgZ3LBONDioM/VAxHNnvWsJKIRH6Pu1gPfhdt6ATR6z4baZV0SpzjzA2D7hjasIwvT7ZM6HdCjzdgfeDuFnr9xk4q50YIHKyiQeK5J+hyv7doDJaMHpv8rJ9IfJgLl4pvBxxxEu2S4gET/RubvRSFAo2fOkARPl2+gdpTz1UsCgYEAg+ZLlvfLbw7cypnPerSnfjjioA/gThfX4LXmqvfTsQqyw3F70iZS3LTYpi93qZIL7lwp6ABD9gQcXnxlnM7RyqptQbRThE6hX+Kdm3MZRcI5uaiBkqAxUc+TNicNSpAChMv73TmzM7adq1KIdSr7o6UrBixwdiSx7CKgAK4zWY0CgYBTM3T+6hMiAdVGEcH7soLAOZmfNX/nAwJZ56qPsgeYwtFQNi0bx/W4twlXxCpWJpUmhlN4arO3fY0COQFplMC4+6XI/f6/9AUhg7WneENEdC0kPFVJ7ncy1QILgPK/R2bLN9+QIiMOzzJ7nodYnkTOyC6iVARXUWC08er+pU3SUwKBgQDaxEpdU3T92xgAE2Pw3H4gD0rs02xV0nlX6c+KvDHBH5iFdKh82FB5kGrsVG+KrLSN/VH7ZYtGCj0reudbvYA1dIuTsMyc8DnjV7u4sCXQEVbGJVeODuMnEJXvqn5LnXyPRUWy8XyZzZI/Lp7OWXpqgzx0I8YDEcXG0SAqWzhUvQ==";//File.ReadAllText($"私钥位置", Encoding.ASCII); if (!string.IsNullOrWhiteSpace(publicKey))
{
_publicKeyRsaProvider = CreateRsaProviderFromPublicKey(publicKey);
}
if (!string.IsNullOrWhiteSpace(privateKey))
{
_privateKeyRsaProvider = CreateRsaProviderFromPrivateKey(privateKey);
}
} /// <summary>
/// 解密
/// </summary>
/// <param name="cipherText"></param>
/// <returns></returns>
public static string Decrypt(string cipherText)
{
if (_privateKeyRsaProvider == null)
{
LogUtil.Logger.Error("_privateKeyRsaProvider is null");
return string.Empty;
} try
{
return Encoding.UTF8.GetString(_privateKeyRsaProvider.Decrypt(Convert.FromBase64String(cipherText), false));
}
catch (Exception ex)
{
LogUtil.Logger.Error(ex, $"RSA解密失败:{cipherText}");
return string.Empty;
}
} /// <summary>
/// 加密
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string Encrypt(string text)
{
if (_publicKeyRsaProvider == null)
{
LogUtil.Logger.Error("_publicKeyRsaProvider is null");
return string.Empty;
} return Convert.ToBase64String(_publicKeyRsaProvider.Encrypt(Encoding.UTF8.GetBytes(text), false));
} /// <summary>
/// 创建rsa公钥对象
/// </summary>
/// <param name="publicKeyString"></param>
/// <returns></returns>
private static RSACryptoServiceProvider CreateRsaProviderFromPublicKey(string publicKeyString)
{
// encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
byte[] x509key = Convert.FromBase64String(publicKeyString); // --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------
using (MemoryStream mem = new MemoryStream(x509key))
{
using (BinaryReader binr = new BinaryReader(mem)) //wrap Memory Stream with BinaryReader for easy reading
{
ushort twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else return null; byte[] seq = binr.ReadBytes(15); //read the Sequence OID
if (!CompareBytearrays(seq, SeqOID)) //make sure Sequence for OID is correct
return null; twobytes = binr.ReadUInt16();
if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8203) binr.ReadInt16(); //advance 2 bytes
else return null; byte bt = binr.ReadByte();
if (bt != 0x00) //expect null byte next
return null; twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230) binr.ReadInt16(); //advance 2 bytes
else return null; twobytes = binr.ReadUInt16();
byte lowbyte = 0x00;
byte highbyte = 0x00; if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81)
lowbyte = binr.ReadByte(); // read next bytes which is bytes in modulus
else if (twobytes == 0x8202)
{
highbyte = binr.ReadByte(); //advance 2 bytes
lowbyte = binr.ReadByte();
}
else return null; byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; //reverse byte order since asn.1 key uses big endian order
int modsize = BitConverter.ToInt32(modint, 0); int firstbyte = binr.PeekChar();
if (firstbyte == 0x00)
{ //if first byte (highest order) of modulus is zero, don't include it
binr.ReadByte(); //skip this null byte
modsize -= 1; //reduce modulus buffer size by 1
} byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data
return null; int expbytes = binr.ReadByte(); // should only need one byte for actual exponent data (for all useful values)
byte[] exponent = binr.ReadBytes(expbytes); // ------- create RSACryptoServiceProvider instance and initialize with public key -----
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAKeyInfo = new RSAParameters();
RSAKeyInfo.Modulus = modulus;
RSAKeyInfo.Exponent = exponent;
RSA.ImportParameters(RSAKeyInfo); return RSA;
}
}
} /// <summary>
/// 创建rsa私钥对象
/// </summary>
/// <param name="privateKey"></param>
/// <returns></returns>
private static RSACryptoServiceProvider CreateRsaProviderFromPrivateKey(string privateKey)
{
var privateKeyBits = Convert.FromBase64String(privateKey); var RSA = new RSACryptoServiceProvider();
var RSAparams = new RSAParameters(); using (BinaryReader binr = new BinaryReader(new MemoryStream(privateKeyBits)))
{
ushort twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) binr.ReadByte();
else if (twobytes == 0x8230) binr.ReadInt16();
else throw new Exception("Unexpected value read binr.ReadUInt16()"); twobytes = binr.ReadUInt16();
if (twobytes != 0x0102) throw new Exception("Unexpected version"); byte bt = binr.ReadByte();
if (bt != 0x00) throw new Exception("Unexpected value read binr.ReadByte()"); RSAparams.Modulus = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.Exponent = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.D = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.P = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.Q = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.DP = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.DQ = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.InverseQ = binr.ReadBytes(GetIntegerSize(binr));
} RSA.ImportParameters(RSAparams);
return RSA;
} private static int GetIntegerSize(BinaryReader binr)
{
int count; byte bt = binr.ReadByte(); if (bt != 0x02) return 0;
bt = binr.ReadByte(); if (bt == 0x81) count = binr.ReadByte();
else if (bt == 0x82)
{
byte highbyte = binr.ReadByte();
byte lowbyte = binr.ReadByte();
byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
count = BitConverter.ToInt32(modint, 0);
}
else count = bt; while (binr.ReadByte() == 0x00) count -= 1; binr.BaseStream.Seek(-1, SeekOrigin.Current); return count;
} private static bool CompareBytearrays(byte[] a, byte[] b)
{
if (a.Length != b.Length) return false; int i = 0;
foreach (byte c in a)
{
if (c != b[i]) return false;
i++;
} return true;
}
}
}

以上公钥私钥不可用,如需生成请使用“支付宝开放平台密钥工具”,官方下载链接:密钥工具下载 - 支付宝文档中心 (alipay.com)

以下是工具使用步骤:

第一步:选择RSA2算法,生成密钥

第二步:复制公钥,直接赋值给工具类变量“publicKey”,复制私钥,进行下一步使用

第三步:到“格式转换”栏,把私钥粘贴到“应用私钥”,点击“转换”,我们可以看到下边有“PKCS1”字样,这就是.net环境中RSA算法支持的私钥格式,复制“输出”,赋值给“privateKey”即可。

以上就是工具使用步骤,快来用最安全的对称加密算法加密你的内容吧!

.net通用RSA加密工具类的更多相关文章

  1. RSA加密工具类(非对称加密算法)

    import com.jfinal.log.Log;import org.apache.commons.codec.binary.Base64; import javax.crypto.Cipher; ...

  2. java 加密工具类(MD5、RSA、AES等加密方式)

    1.加密工具类encryption MD5加密 import org.apache.commons.codec.digest.DigestUtils; /** * MD5加密组件 * * @autho ...

  3. Java中使用最频繁及最通用的Java工具类

    在Java中,工具类定义了一组公共方法,Java中使用最频繁及最通用的Java工具类. 一. org.apache.commons.io.IOUtils closeQuietly:关闭一个IO流.so ...

  4. App开发流程之加密工具类

    科技优家 2016-09-08 18:10 从这篇记录开始,记录的都算是干货了,都是一些编程日常的积累. 我建议先将基础的工具加入项目,后续的开发效率会呈指数增长.如果在专注功能开发过程中,才发现缺少 ...

  5. 加密工具类 - CryptoUtils.java

    加密工具类,包含MD5,BASE64,SHA,CRC32的加密与解密方法. 源码如下:(点击下载  - CryptoUtils.java.commons-io-2.4.jar.commons-code ...

  6. android开发MD5加密工具类(一)

    MD5加密工具类整理: package com.gzcivil.utils; import java.io.UnsupportedEncodingException; import java.secu ...

  7. wemall app商城源码android开发MD5加密工具类

    wemall-mobile是基于WeMall的android app商城,只需要在原商城目录下上传接口文件即可完成服务端的配置,客户端可定制修改.本文分享android开发MD5加密工具类主要代码,供 ...

  8. Java AES 加密工具类

    package com.microwisdom.utils; import java.security.NoSuchAlgorithmException; import java.security.S ...

  9. c# 加密工具类

    using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Sec ...

  10. java MD5Utils 加密工具类

    package com.sicdt.library.core.utils; import java.io.File; import java.io.FileInputStream; import ja ...

随机推荐

  1. es6的Symbol数据类型

    ES6引入了一种新的原始数据类型Symbol,表示独一无二的值.它是JavaScript语言的第七种数据类型,前六种是:Undefined.Null.布尔值(Boolean).字符串(String). ...

  2. antv x6 神奇的图片边框

    昨天才把html节点中的图片转成base格式的,今天就发现一个用户体验的问题:那么是啥呢?就是我从左侧的树形菜单中拖拽节点的时候(鼠标按下也是同样问题),发现节点的图片区域那里会出现一个边框,持续时间 ...

  3. WPF 引用字体文件资源

    外部字体文件 1.后台代码引用字体 将一个名为"ChineseCharacterSpecialFont.ttf"的ttf文件,放在桌面路径,后台引用方式如下: 1 var ttfF ...

  4. LeetCode刷题之652寻找重复的子树

    继续每日分享一道算法题,监督自己学习,不落下算法,有需要一起打卡的uu,可以一起加油呀! 好了,现在开始看题了哈: 给定一棵二叉树 root,返回所有重复的子树. 对于同一类的重复子树,你只需要返回其 ...

  5. SpringBoot 自动扫描第三方包及spring.factories失效的问题

    为什么会找不到 Spring 依赖注入 就是要让spring找到要注入的类 并且识别到了 @Component.@Service 等注解. 1. 当在开发的第三方包里写明了 @Component.@S ...

  6. git仓库过渡,同时向两个仓库推送代码

    公司部门被大佬收购,产品项目迁移新公司仓库,过渡期间产品上线流程继续使用原公司的,新公司部署新系统后通过域名重定向逐渐将用户引流到新系统上完成切换,最后关闭原公司系统及上线流程. 过渡期间新功能代码需 ...

  7. SpringBoot集成Jpa对数据进行排序、分页、条件查询和过滤

    之前介绍了SpringBoot集成Jpa的简单使用,接下来介绍一下使用Jpa连接数据库对数据进行排序.分页.条件查询和过滤操作.首先创建Springboot工程并已经继承JPA依赖,如果不知道可以查看 ...

  8. 2022-12-26:有一个数组包含0、1、2三种值, 有m次修改机会,第一种将所有连通的1变为0,修改次数-1, 第二种将所有连通的2变为1或0,修改次数-2, 返回m次修改机会的情况下,让最大的0

    2022-12-26:有一个数组包含0.1.2三种值, 有m次修改机会,第一种将所有连通的1变为0,修改次数-1, 第二种将所有连通的2变为1或0,修改次数-2, 返回m次修改机会的情况下,让最大的0 ...

  9. 2021-12-30:分裂问题。 一个数n,可以分裂成一个数组[n/2, n%2, n/2], 这个数组中哪个数不是1或者0,就继续分裂下去。 比如 n = 5,一开始分裂成[2, 1, 2], [2

    2021-12-30:分裂问题. 一个数n,可以分裂成一个数组[n/2, n%2, n/2], 这个数组中哪个数不是1或者0,就继续分裂下去. 比如 n = 5,一开始分裂成[2, 1, 2], [2 ...

  10. 2021-08-21:给定一个数组arr,长度为N > 1,从中间切一刀,保证左部分和右部分都有数字,一共有N-1种切法,如此多的切法中,每一种都有:绝对值(左部分最大值 – 右部分最大值)。返回最大

    2021-08-21:给定一个数组arr,长度为N > 1,从中间切一刀,保证左部分和右部分都有数字,一共有N-1种切法,如此多的切法中,每一种都有:绝对值(左部分最大值 – 右部分最大值).返 ...