目前官方只提供了Java的实现方法,这里提供一种C#的实现方法,使用nuget包:Portable.BouncyCastle,安装后使用一下帮助类即可:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
public class RSAHelper
{
public static string publicKey = @"替换成你自己的PUBLIC KEY";
public static string RsaEncrypt(string value, bool usePkcs8 = false)
{
if (string.IsNullOrEmpty(value)) return value;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);
rsa.FromXmlString(RSAPublicKeyJava2DotNet(publicKey));//将公钥导入到RSA对象中,准备加密;
var buffer = Encoding.UTF8.GetBytes(value);
buffer = rsa.Encrypt(buffer, false);
return Convert.ToBase64String(buffer);
}
/***************以下是java提供的公私钥转成.net公私钥XML的方式*************************************/
/// <summary>
/// RSA公钥格式转换,java->.net
/// </summary>
/// <param name="publicKey">java生成的公钥</param>
/// <returns></returns>
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()));
}
}
|