40 lines
1.5 KiB
C#
40 lines
1.5 KiB
C#
using Org.BouncyCastle.Crypto.Parameters;
|
|
using Org.BouncyCastle.Security;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
namespace Lskj.QueryEssentialInfo
|
|
{
|
|
public static class RsaEntryUtil
|
|
{
|
|
public static byte[] Encrypt(string plainText, string publicKeyXml)
|
|
{
|
|
byte[] dataToEncrypt = Encoding.UTF8.GetBytes(plainText);
|
|
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
|
|
{
|
|
rsa.FromXmlString(publicKeyXml);
|
|
// 默认使用PKCS#1 v1.5填充,4.0版本不支持OAEP-SHA256,只能用OAEP-SHA1,且需要指定true
|
|
return rsa.Encrypt(dataToEncrypt, false);
|
|
}
|
|
}
|
|
public static string ToXmlPublicKey(string pubilcKey)
|
|
{
|
|
RsaKeyParameters rsaKeyParameters = PublicKeyFactory.CreateKey(Convert.FromBase64String(pubilcKey)) as RsaKeyParameters;
|
|
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
|
|
{
|
|
RSAParameters rsaParams = new RSAParameters
|
|
{
|
|
Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned(),
|
|
Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned()
|
|
};
|
|
rsa.ImportParameters(rsaParams);
|
|
return rsa.ToXmlString(false);
|
|
}
|
|
}
|
|
}
|
|
}
|