【发布时间】:2015-06-07 22:04:25
【问题描述】:
我正在尝试使用 OpenSSL 生成的密钥对和 Bouncy Castle 在 C# 中实现字符串加密-解密。
OpenSSL 授予我密钥对,我将其分成 2 个文件。现在我正在使用 Bouncy Castle 的 Pemreader 读取密钥并将其更改为 AsymmetricKeyParameters。
下面的代码运行了,但是解密后的字符串和原来的不一样——我得到了一堆?。
如果我打印出密钥,它们看起来就像在文本文件中一样。
有人能指出我做错了什么吗?阅读程序或引擎使用似乎是原因。没有填充的 2048 位密钥,这种加密有多强?
string test = "qwerty12345";
AsymmetricKeyParameter keyparmeter = readPublicKey(public_path); // Read public key into string
/* Print the test key */
Console.WriteLine("test key = " + test);
/* Convert test to byte array */
byte[] bytes = new byte[test.Length * sizeof(char)];
System.Buffer.BlockCopy(test.ToCharArray(), 0, bytes, 0, bytes.Length);
byte[] cipheredbytes = null;
/* Initiate rsa engine */
RsaEngine e = new RsaEngine();
e.Init(true, keyparmeter); // initialize engine true, encrypting
/* Crypt! */
cipheredbytes = e.ProcessBlock(bytes, 0, bytes.Length);
// ## NOW DECRYPTION ##
/* Get the private key */
AsymmetricKeyParameter privkeyparameter = readPrivKey(privkey_path);
byte[] reversedbytes = null;
/* Initiate rsa decrypting engine */
RsaEngine d = new RsaEngine();
d.Init(false, privkeyparameter); // initialize engine false, decrypting
/* Decrypt! */
reversedbytes = d.ProcessBlock(cipheredbytes, 0, cipheredbytes.Length);
char[] chars = new char[cipheredbytes.Length / sizeof(char)];
System.Buffer.BlockCopy(cipheredbytes, 0, chars, 0, cipheredbytes.Length);
string reversedtest = new string(chars);
### PEMREADING ###
/* Convert PEM into AsymmetricKeyParameter */
private AsymmetricKeyParameter readPublicKey(string path_to_key)
{
RsaKeyParameters asmkeypar;
using(var reader = File.OpenText(path_to_key))
asmkeypar = (RsaKeyParameters) new PemReader(reader).ReadObject();
return asmkeypar;
}
/* Convert PEM into AsymmetricKeyParameter */
private AsymmetricKeyParameter readPrivKey(string path_to_key)
{
AsymmetricCipherKeyPair asmkeypar;
using (var reader = File.OpenText(path_to_key))
asmkeypar = (AsymmetricCipherKeyPair)new PemReader(reader).ReadObject();
return (RsaKeyParameters) asmkeypar.Private;
}
【问题讨论】:
标签: c# encryption openssl rsa bouncycastle