公钥到RSA公钥的c#
本文关键字:公钥 RSA | 更新日期: 2023-09-27 18:09:21
我需要在c#项目中使用RSA加密将加密的数据发送到服务。Service给了我一个这样的公钥:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjU/bq6YZD2H0DUhbtEBg
JIyiurM8eX3aH02/ZWr6VZ27WF93ylWC4cGAe50sSgiA8NCW0G/UL77kAkebJQrJ
jVdt7SvDypSPk1mXNK0i9cI9DrdmAHLGLlYJx7eeY6h4JShLhOBnKRghi0S4uL5N
L7W4OUgCeUlGWcmz8ssNEQ5w17rfUF9TxYEFVKFMGN/SSaYNUr4znGt2r97YPsPy
0Sk4dGHhMXr1QGR05UQeVuU43OuRAFxA71YbuCRUYg5ENwKM/1RnNcu8v7kXFA4L
qGV9AncHLIZEOqWgY+4balVXlKIcMVN6W+PXKJpowOyB9QIq1Ec3OMaJ3sGpOppx
KQIDAQAB
-----END PUBLIC KEY-----
我如何将其转换为base64字符串与此代码一起使用?
public static string EncryptData(string publicKey, string clearText)
{
IBuffer keyBuffer = CryptographicBuffer.DecodeFromBase64String(publicKey);
AsymmetricKeyAlgorithmProvider asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
CryptographicKey key = asym.ImportPublicKey(keyBuffer, CryptographicPublicKeyBlobType.Capi1PublicKey);
IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(clearText, BinaryStringEncoding.Utf8);
IBuffer encryptedBuffer = CryptographicEngine.Encrypt(key, plainBuffer, null);
byte[] encryptedBytes;
CryptographicBuffer.CopyToByteArray(encryptedBuffer, out encryptedBytes);
return Convert.ToBase64String(encryptedBytes);
}
我找到了解决方案,很简单:我需要使用:
CryptographicKey key = asym.ImportPublicKey(keyBuffer, CryptographicPublicKeyBlobType.X509SubjectPublicKeyInfo);