c# RSA加密解密,与java代码互通问题
RSA加密解密原本是公开算法,但是和一个java的小伙伴对接却出现了点问题,现在记录一下
首先,RSA的公钥私钥,有2种:
1、pem格式。
2、xml格式。
文章底部有pem格式和对应的xml样本数据(样本数据太长,放在尾部)
对比样本数据知道,如果对方发过来的公钥私钥是带有类似 -----BEGIN PRIVATE KEY----- 这种字符串的,那肯定是pem格式的,如果用c#来使用的话,我们得先转为 xml 格式的,如果为了方便我们直接选一家在线转换的网站即可,比如 https://the-x.cn/certificate/PemToXml.aspx (有密钥泄露风险,可以选择自己写代码来转换,c#有一个库叫 BouncyCastle 可以转换)
这样一来就有对应的xml公钥和私钥了,然后,在用下面的c#代码进行加解密就可以了。
如果和java的小伙伴还有争议的话,可以选一个第三方网站作为参照,C#的小伙伴只要把字符串加密后丢到第三方网站能解密,第三方网站加密后的结果能被c#代码解密,代表c#就没问题了,java的小伙伴也做同样的操作,就可以不用老怀疑对方写的有问题了。。。。。
第三方网站比如:https://www.bejson.com/enc/rsa/
/// <summary> /// RSA加密 /// </summary> /// <param name="xmlPublickey"></param> /// <param name="content"></param> /// <returns></returns> public static string RSAEncrypt(string xmlPublickey, string content) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); byte[] cipherbytes; rsa.FromXmlString(xmlPublickey); cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false); return Convert.ToBase64String(cipherbytes); } /// <summary> /// RSA解密 /// </summary> /// <param name="xmlPrivatekey"></param> /// <param name="content"></param> /// <returns></returns> public static string RSADecrypt(string xmlPrivatekey, string content) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); byte[] cipherbytes; rsa.FromXmlString(xmlPrivatekey); cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false); return Encoding.UTF8.GetString(cipherbytes); }
-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwF4/zAUR9+5DG3FPysdb uM3cUARJFQUsNxXmKX9dVwe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