C# RSA加密算法PEM格式转换XML
Posted Walter_lee2008
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# RSA加密算法PEM格式转换XML相关的知识,希望对你有一定的参考价值。
c# rsa加密需要xml公钥 如何将pem格式转换成xml (c# rsa只支持XML格式的)
RSA PEM格式(蓝色部分是公钥=publicKey):
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUABgQD5MIb5ZQhNGhsUjfFbn7y6nY6tsqV9LcC2s/rLpu9sz8CplsTy2SuTG0o7y9ICXW6oRUC9bVxI8TfTK4bbSrNQ6UoExzQFdbc3pEGun3iCy+inBhIC6xf5Z7lN+WqTKCZ607iLwKh+wDdZc6U4x1rxF4vngk1sXIdnYEoGjpRNLQIDAQAB
-----END PUBLIC KEY-----
使用BouncyCastle组件,PM> Install-Package BouncyCastle
/// <summary>
/// RSA公钥格式转换,
/// </summary>
/// <param name="publicKey">pem公钥</param>
/// <returns></returns>
public static string RSAPublicKeyXML(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()));
最终写法:
/// <summary>
/// RSA公钥pem-->XML格式转换,
/// </summary>
/// <param name="publicKey">pem公钥</param>
/// <param name="content">要加密的内容:比如密码</param>
/// <returns></returns>
public string RSAPublicKey(string publicKey,string content)
RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
string XML = string.Format("<RSAKeyValue><Modulus>0</Modulus><Exponent>1</Exponent></RSAKeyValue>",
Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned()));
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
byte[] cipherbytes;
rsa.FromXmlString(XML);
cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);
return Convert.ToBase64String(cipherbytes);
XML to PEM 和 PEM to XML相互转换:
https://superdry.apphb.com/tools/online-rsa-key-converter
在线RSA加密解密,RSA公钥私钥加密解密
http://www.metools.info/code/c81.html
JS加密公钥的方法:
var crypt = new JSEncrypt(
default_key_size: 1024
);
crypt.setPublicKey("MIGfMA0GCSqGSIb3DQEBAQgQDIDOFZiLonAYjlUg+fLIs6HbMFpnw+legVMfVsBB+lnsLYsaPYv/0RMMvjY06uPmdya6ymmYxRieGJiaf0N024oHNqtGnSNK/a8YP1nZLBtBwk2VzEb/rBbdCLhkznIOkNMwy20VG/M5LOXiLkYRry8AEQIDAQAB");
var PWD = crypt.encrypt('1');
console.log(PWD);------------->最终的公钥加密字符串,可以用于向后台接口请求数据。
以上是关于C# RSA加密算法PEM格式转换XML的主要内容,如果未能解决你的问题,请参考以下文章
将 PEM RSA 密钥转换为 C# RSACryptoServiceProvider.FromXmlString 的 xml