由于项目需要,需要用公钥对秘钥进行加密,且对接系统用C#开发,需求是这样的:
注册许可证时返回的公钥spk对秘钥信息secrit进行加密。
由于公钥spk是字符串,但C#中只认可的xml字符串的公钥才能够进行加密,可以使用以下方法,先进行转换,将公钥字符串转换成XML,再进行加密,就可以得到加密后的字符:
public static string RSAEncrypt(string spk, string secrit)
{
string PublicKey = RSAPublicKey(spk);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
byte[] cipherbytes;
rsa.FromXmlString(PublicKey);
cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(secrit), false);
return Convert.ToBase64String(cipherbytes);
}
public static string RSAPublicKey(string publicKey)
{
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()));
return XML;
}
想要从字符串的pem公钥转为xml公钥,只能依赖于一个第三方库,叫做BouncyCastle,在vs中使用NuGet包管理器安装一下,就可以使用。