C# RSA 非对称加密
代码:
RSAHelper.cs(RSA加密工具类):

using System;
using System.Security.Cryptography;
using System.Text; namespace Utils
{
/// <summary>
/// RSA加密工具类
/// </summary>
public class RSAHelper
{
/// <summary>
/// RSA加密
/// </summary>
public static string RSAEncrypt_LongContent(string publicKey, string content)
{
byte[] bytes = Encoding.UTF8.GetBytes(content); int pageSize = 117;
int pageCount = (bytes.Length - 1) / pageSize + 1; StringBuilder result = new StringBuilder();
for (int page = 1; page <= pageCount; page++)
{
int start = pageSize * (page - 1); byte[] subBytes = page == pageCount ? new byte[bytes.Length - start] : new byte[pageSize]; Array.Copy(bytes, start, subBytes, 0, subBytes.Length); string strEncrypted = RSAEncrypt(publicKey, Encoding.UTF8.GetString(subBytes));
result.Append(strEncrypted);
} return result.ToString();
} /// <summary>
/// RSA解密
/// </summary>
public static string RSADecrypt_LongContent(string privateKey, string content)
{
int pageSize = 172;
int pageCount = (content.Length - 1) / pageSize + 1; StringBuilder result = new StringBuilder();
for (int page = 1; page <= pageCount; page++)
{
int start = pageSize * (page - 1); string subContent = null;
if (page != pageCount)
{
subContent = content.Substring(start, pageSize);
}
else
{
subContent = content.Substring(start, content.Length - start);
} string strEncrypted = RSADecrypt(privateKey, subContent);
result.Append(strEncrypted);
} return result.ToString();
} /// <summary>
/// RSA加密
/// </summary>
public static string RSAEncrypt(string publicKey, string content)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(publicKey);
byte[] cipherBytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false); return Convert.ToBase64String(cipherBytes);
} /// <summary>
/// RSA解密
/// </summary>
public static string RSADecrypt(string privateKey, string content)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(privateKey);
byte[] cipherBytes = rsa.Decrypt(Convert.FromBase64String(content), false); return Encoding.UTF8.GetString(cipherBytes);
} /// <summary>
/// 创建公钥私钥
/// </summary>
public static RSAKey CreateKey()
{
RSAKey rsaKey = new RSAKey(); using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsaKey.PublicKey_NET = rsa.ToXmlString(false); // 公钥
rsaKey.PrivateKey_NET = rsa.ToXmlString(true); // 私钥 rsaKey.PublicKey_Java = RSAKeyConvert.RSAPublicKeyDotNet2Java(rsaKey.PublicKey_NET);
rsaKey.PrivateKey_Java = RSAKeyConvert.RSAPrivateKeyDotNet2Java(rsaKey.PrivateKey_NET);
} return rsaKey;
}
} public class RSAKey
{
public string PublicKey_NET { get; set; } public string PrivateKey_NET { get; set; } public string PublicKey_Java { get; set; } public string PrivateKey_Java { get; set; }
}
}
RSAKeyConvert.cs(Java .NET RSA密钥格式转换)(需要安装NuGet包BouncyCastle):

using System;
using System.Xml;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509; namespace Utils
{
/// <summary>
/// RSA密钥格式转换
/// </summary>
public class RSAKeyConvert
{
/// <summary>
/// RSA私钥格式转换,java->.net
/// </summary>
/// <param name="privateKey">java生成的RSA私钥</param>
public static string RSAPrivateKeyJava2DotNet(string privateKey)
{
RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey)); return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()));
} /// <summary>
/// RSA私钥格式转换,.net->java
/// </summary>
/// <param name="privateKey">.net生成的私钥</param>
public static string RSAPrivateKeyDotNet2Java(string privateKey)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(privateKey);
BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
BigInteger exp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
BigInteger d = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
BigInteger q = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
BigInteger dp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
BigInteger dq = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
BigInteger qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText)); RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv); PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);
byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
return Convert.ToBase64String(serializedPrivateBytes);
} /// <summary>
/// RSA公钥格式转换,java->.net
/// </summary>
/// <param name="publicKey">java生成的公钥</param>
public static string RSAPublicKeyJava2DotNet(string publicKey)
{
RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",
Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned()));
} /// <summary>
/// RSA公钥格式转换,.net->java
/// </summary>
/// <param name="publicKey">.net生成的公钥</param>
public static string RSAPublicKeyDotNet2Java(string publicKey)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(publicKey);
BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
RsaKeyParameters pub = new RsaKeyParameters(false, m, p); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);
byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
return Convert.ToBase64String(serializedPublicBytes);
}
}
}
C# RSA 非对称加密的更多相关文章
- Atitit RSA非对称加密原理与解决方案
Atitit RSA非对称加密原理与解决方案 1.1. 一.一点历史 1 1.2. 八.加密和解密 2 1.3. 二.基于RSA的消息传递机制 3 1.4. 基于rsa的授权验证机器码 4 1.5. ...
- CryptoAPI与openssl RSA非对称加密解密(PKCS1 PADDING)交互
(以下代码中都只做测试用,有些地方没有释放内存...这个自己解决下) 1.RSA非对称的,首先提供一个供测试用的证书和私钥的数据 1)pem格式的证书和私钥(公私钥是对应的)的base64编码 voi ...
- RSA非对称加密Java实现
原文 加密基础方法类 import java.security.MessageDigest; import sun.misc.BASE64Decoder; import sun.misc.BASE64 ...
- 前端js,后台python实现RSA非对称加密
先熟悉使用 在后台使用RSA实现秘钥生产,加密,解密; # -*- encoding:utf-8 -*- import base64 from Crypto import Random from Cr ...
- 前后端数据加密传输 RSA非对称加密
任务需求:要求登陆时将密码加密之后再进行传输到后端. 经过半天查询摸索折腾,于是有了如下成果: 加密方式:RSA非对称加密.实现方式:公钥加密,私钥解密.研究进度:javascript与java端皆已 ...
- php RSA非对称加密 的实现
基本概念 加密的意义 加密的意义在于数据的传输过程中,即使被第三方获取到传输的数据,第三方也不能获取到数据的具体含义. 加密方式分为对称加密和非对称加密 什么是对称加密? 对称加密只使用一个秘钥,加密 ...
- ssh rsa 非对称加密 基本原理
我们常用的ssh 免密登陆是用了 非对称加密的rsa算法(最为常用),与对称加密的相比会慢一些,但是更安全.秘钥长度超过768位无法破解. 默认长度是2048位(无法破解,非常安全) ssh-keyg ...
- RSA 非对称加密,私钥转码为pkcs8 错误总结
RSA 非对称加密,私钥转码为pkcs8 错误总结 最近在和某上市公司对接金融方面的业务时,关于RSA对接过程中遇到了一个坑,特来分享下解决方案. 该上市公司简称为A公司,我们简称为B公司.A-B两家 ...
- JSON 接口如何实现 RSA 非对称加密与签名
代码地址如下:http://www.demodashi.com/demo/14000.html 一.概述 1. 数字签名的作用:保证数据完整性,机密性和发送方角色的不可抵赖性,加密与签字结合时,两套公 ...
- javascript版前端页面RSA非对称加密解密
最近由于项目需要做一个url传参,并在页面显示参数内容的需求,这样就会遇到一个url地址可能会被假冒, 并传递非法内容显示在页面的尴尬情况 比如xxx.shtml?server=xxx是坏人& ...
随机推荐
- Ubuntu 20.04 挂载局域网络共享硬盘
创建挂载目录 mkdir /media/nas 创建认证文件.若无密码可以忽略这一步. sudo vim /root/.examplecredentials 按照以下格式写入用户名密码: userna ...
- Kubernetes Gateway API 攻略:解锁集群流量服务新维度!
Kubernetes Gateway API 刚刚 GA,旨在改进将集群服务暴露给外部的过程.这其中包括一套更标准.更强大的 API资源,用于管理已暴露的服务.在这篇文章中,我将介绍 Gateway ...
- JSX、TSX 整体理解
可以少去理解一些不必要的概念,而多去思考为什么会有这样的东西,它解决了什么问题,或者它的运行机制是什么? JS JavaScript 是互联网上最流行的脚本语言,这门语言可用于 HTML 和 web, ...
- CPF C#跨平台UI框架开源了
介绍 C#跨平台UI框架 提供NETStandard2.0和net4的库,通过Netcore可以跨平台,支持Windows.Mac.Linux,Net4的可以支持XP. 各个平台运行效果一致,不依赖系 ...
- OPC 协议数据采集
kepserver OPC Connectivity Suite 让系统和应用程序工程师能够从单一应用程序中管理他们的 OPC 数据访问 (DA) 和 OPC 统一架构 (UA) 服务器.通过减少 ...
- Ubuntu下安装多个JDK,并设置其中一个为默认JDK
由于使用需要,要在机器上同时安装OpenJDK 8和11,并将8设置为默认JDK 首先安装OpenJDK sudo apt-get install openjdk-8-jdk sudo apt-get ...
- 主界面(零基础适合小白)基础javaweb前端项目实战【包含增删改查,mysql】三
首先编写sp文件(index.jsp) <%@ page contentType="text/html;charset=UTF-8" language="java& ...
- [ABC246F] typewriter
Problem Statement We have a typewriter with $N$ rows. The keys in the $i$-th row from the top can ty ...
- [ABC265C] Belt Conveyor
Problem Statement We have a grid with $H$ horizontal rows and $W$ vertical columns. $(i, j)$ denotes ...
- MySQL InnoDB加锁规则分析
1. 基础知识回顾 1.索引的有序性,索引本身就是有序的 2.InnoDB中间隙锁的唯一目的是防止其他事务插入间隙.间隙锁可以共存.一个事务取得的间隙锁并不会阻止另一个事务取得同一间隙上的间隙锁.共 ...