c#中使用openssl

近期使用加密狗对软件进行加密,但是软件用的c#,这就比较坑了,因为c#自带的System.Security.Cryptography只支持c#格式的公钥加密私钥解密,而现在需要私钥加密公钥解密。于是网上进行资料查找,一堆资料说的都是使用BouncyCastle,但是。。。。。。没有使用不同格式的密文啊喂,你们有考虑过c#的孤独吗?

经过对结构体的分析,发现还是有些共通的地方,比如要有Modulus和Exponent,当然是对公钥来说,然后各种调用,生成公钥,一波操作猛如虎,回头一看二百五啊。。。。。。没人跟我说密文格式的不同啊喂。又是一顿搜索,知道了c#的rsa密文是xml格式的,不是简单的base64的,需要转换,咋办?我想了个办法,先用c#自带的加解密生成一个公私钥对,然后就知道格式了啊对不对,按照这个格式,我将openssl里的公钥拼凑进去,得到一个xml格式的公钥,再通过c#自带的解xml公钥,得到rsa信息,再生成base64格式的公钥串,啊哈,竟然成功了,神奇不?

xml公钥格式大概是这样的:

string strPubKey = "<RSAKeyValue><Modulus>" + str64Modulus + "</Modulus><Exponent>" + str64Exponent + "</Exponent></RSAKeyValue>";

转换xml格式公钥:

public static string FromXmlPublicKey(string xmlPublicKey)
        {
            string result = string.Empty;
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(xmlPublicKey);
                RSAParameters p = rsa.ExportParameters(false);
                RsaKeyParameters keyParams = new RsaKeyParameters(
                    false, new BigInteger(1, p.Modulus), new BigInteger(1, p.Exponent));
                SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyParams);
                result = Convert.ToBase64String(publicKeyInfo.ToAsn1Object().GetEncoded());
            }
            return result;
        }

用公钥解密:

public static string DecryptPublicKey(string publicKey, string data)
        {
            RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
            byte[] cipherbytes = Convert.FromBase64String(data);
            RsaEngine rsa = new RsaEngine();
            rsa.Init(false, publicKeyParam);
            cipherbytes = rsa.ProcessBlock(cipherbytes, 0, cipherbytes.Length);
            return Convert.ToBase64String(cipherbytes, 0, cipherbytes.Length);
        }

以上,问题解决,如果大家有更好的办法,希望留言,没有人写相关的东西,所以我粗略的写了点,不对的请指出,谢谢!

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值