我想在C#中使用OpenSSL生成的密鑰對和Bouncy Castle實現字符串加密 - 解密。C#使用OpenSSL密鑰和充氣城堡實現RSA
OpenSSL授予我密鑰對,我在兩個文件中分開。現在我使用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;
}