2015-04-02 96 views
0

我想在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; 
    } 

回答

1

您正在使用基本RSA算法。這也被稱爲原始或教科書RSA。基本上它執行模冪運算,但它不會執行填充或不填充。所以你所得到的是明文+零值已經放在值的前面,因爲無填充似乎沒有發生。

最後,你應該執行字符編碼來代替System.Buffer.BlockCopy,後者可能會弄得一團糟了它,因爲它必須在.NET中的Unicode編碼的字符串操作。

我可以在加密上引用你的this question,它試圖列出原始/教科書RSA上所有可能的攻擊。有很多,你的代碼安全的可能性大約爲零。