C#使用 RSA 加解密的注意事项

最近项目中使用到RSA加密算法,去网上看看有没有使用C#来实现RSA加解密,一搜几乎都没有完整可用的,搜索了很多资料都没有讲明白的,找到的一些文章讲的都是片段,目前有些RSA加解密算法会提供公钥加密和私钥解密,但C#只支持XML格式的加解密,因此需要将事先提供的公钥和私钥进行XML格式的转换才行!java的实现倒是一大堆,我就废话不多说了,直接上源码:

下面这个是加密类:

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System.Security.Cryptography;
using System.Text;

namespace CcbPayWepApi
{
    public static class RSACrytoTextProvider
    {
        public static string RsaPublicKeyToXml(string publicKey)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(publicKey))
                    return "";
                if (publicKey.Contains("<RSAKeyValue>"))
                    return publicKey;
                RsaKeyParameters publicKeyParam;
                //尝试进行java格式的密钥读取
                try
                {
                    publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
                }
                catch
                {
                    publicKeyParam = null;
                }
                //非java格式密钥进行pem格式的密钥读取
                if (publicKeyParam == null)
                {
                    try
                    {
                        var pemKey = publicKey;
                        if (!pemKey.Contains("BEGIN RSA PRIVATE KEY"))
                        {
                            pemKey = @"-----BEGIN RSA PRIVATE KEY-----
                           " + publicKey + @"
                           -----END RSA PRIVATE KEY-----";
                        }
                        var array = Encoding.ASCII.GetBytes(pemKey);
                        var stream = new MemoryStream(array);
                        var reader = new StreamReader(stream);
                        var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(reader);
                        publicKeyParam = (RsaKeyParameters)pemReader.ReadObject();
                    }
                    catch
                    {
                        publicKeyParam = null;
                    }
                
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值