在 C# 中使用 RSA 公钥和私钥加密数据
本文关键字:私钥 加密 数据 公钥 RSA | 更新日期: 2023-09-27 18:34:20
我正在尝试使用 RSA 公钥加密消息并使用我的私钥对其进行解密。它加密了消息,但我无法解密它。 在最终处理之后,消息仍被加密。 当我导出私钥时,它还包括公钥。我试图删除公钥离开,但它不起作用。以下是私钥和公钥
//This is the public key
private const string public_key = "<RSAKeyValue><Modulus>uznzVPilsR1rWPkpq6m6IALaafDnVZTDDcnEyBD3A/PBx2JZTKM0DTgiTDDwCEmQBNBpPILcIBdtg3aSUgicair+2ksYrVFT+uiy0Zy1nU6qoJ+SsapLKrpCa1zHpV4LMO/pFo4Foqzw0C1FNe56FXo1xj77GPgeYl0MHUVtAUc=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
//This is the private and public key.
private const String private_key = "<RSAKeyValue><Modulus>uznzVPilsR1rWPkpq6m6IALaafDnVZTDDcnEyBD3A/PBx2JZTKM0DTgiTDDwCEmQBNBpPILcIBdtg3aSUgicair+2ksYrVFT+uiy0Zy1nU6qoJ+SsapLKrpCa1zHpV4LMO/pFo4Foqzw0C1FNe56FXo1xj77GPgeYl0MHUVtAUc=</Modulus><Exponent>AQAB</Exponent><P>+jPKs9JxpCSzNY+YNanz49Eo/A6RaU1DZWoFm/bawffZOompeL1jzpUlJUIrKVZJkNFvlxE90uXVwjxWBLv9BD==</P><Q>v5CVWKZ5Wo7W0QyoEOQS/OD8tkKS9DjzZnbnuo6lhcMaxsBrCWLstac1Xm2oFNtZgLtrPGbPfCNC5Su4Rz/P5w==</Q><DP>ZnyikmgobqEt20m3gnvcUDxT+nOJMsYYTklQhONoFj4M+EJ9bdy+Lle/gHSLM4KJ3c08VXgVh/bnSYnnfkb20Q==</DP><DQ>sSYGRfWk0W64Dpfyr7QKLxnr+Kv186zawU2CG44gWWNEVrnIAeUeWxnmi41CWw9BZH9sum2kv/pnuT/F6PWEzw==</DQ><InverseQ>XpWZQKXa1IXhF4FX3XRXVZGnIQP8YJFJlSiYx6YcdZF24Hg3+Et6CZ2/rowMFYVy+o999Y5HDC+4Qa1yWvW1vA==</InverseQ><D>Kkfb+8RrJqROKbma/3lE3xXNNQ7CL0F5CxQVrGcN8DxL9orvVdyjlJiopiwnCLgUHgIywceLjnO854Q/Zucq6ysm2ZRq36dpGLOao9eg+Qe8pYYO70oOkEe1HJCtP1Laq+f3YK7vCq7GkgvKAI9uzOd1vjQv7tIwTIADK19ObgE=</D></RSAKeyValue>";
//Encrypting the text using the public key
private RSACryptoServiceProvider cipher = null;
cipher = new RSACryptoServiceProvider();
cipher.FromXmlString(public_key);
byte[] data = Encoding.UTF8.GetBytes(txtUnencrypt.Text);
byte[] cipherText = cipher.Encrypt(data, false);
lblUnencryptMessage.Text = Convert.ToBase64String(cipherText);
// decryptText();
//Trying to decrypt the text using the private key
cipher = new RSACryptoServiceProvider();
cipher.FromXmlString(private_key);
byte[] ciphterText = Convert.FromBase64String(lblUnencryptMessage.Text);
byte[] plainText = cipher.Decrypt(ciphterText, false);
lblDecript.Text = Convert.ToBase64String(plainText);
例如,我加密了"测试"一词,加密的文本是
kkqs+UGHNI7/3cKhQvSnJrKzNeCBQX9xHX2VrlyMvnwtszJAoFuViBZlfwmpVhqddnVUrlaqqkD7971E8L3wWltfGetK9nIljeo0GeietLYljoY0Gy3gatU++JPrqajAKxpIB75tvVlKXuYIs0qE3XWZu9bj0zAa4BVT2MhVNQM="
解密的文本是
dGVzdGluZw==
我在这里错过了什么?
加密/解密代码似乎没有任何问题,只是您如何处理解密数据。具体来说,这一行:
lblDecript.Text = Convert.ToBase64String(plainText);
您正在获取解密的数据并对其进行 Base64 编码,这就是为什么您得到:dGVzdGluZw==(因为这是字符串"testing"的 Base64 编码版本)。
您需要改用以下内容:
lblDecript.Text = Encoding.UTF8.GetString(plainText);
这应该将解密的字节数组正确转换为原始字符串。