2011-01-11 14 views
9

Sto giocando con crittografia/decodifica RSA e certificati. Qui in particolare, cerco di cifrare con la chiave pubblica di un certificato, e poi, quando si cerca di decifrare con la chiave privata corrispondente a tale certificato, si ottiene un errore:"System.Security.Cryptography.CryptographicException: Bad Key." per RSACryptoServiceProvider.Decrypt()

System.Security.Cryptography.CryptographicException: Bad Key. 

    at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) 
    at System.Security.Cryptography.RSACryptoServiceProvider.DecryptKey(SafeKeyHandle pKeyContext, Byte[] pbEncryptedKey, Int3 
2 cbEncryptedKey, Boolean fOAEP, ObjectHandleOnStack ohRetDecryptedKey) 
    at System.Security.Cryptography.RSACryptoServiceProvider.Decrypt(Byte[] rgb, Boolean fOAEP) 

Codice è:

private void TestCertificates2() 
{ 
    ////////////////////////////////////////////////////// 
    // SENDER CODE 
    ////////////////////////////////////////////////////// 

    // get certificate 
    var certSender = new X509Certificate2(@"C:\Test.cer"); 

    // encrypt with public key 
    var providerSender = (RSACryptoServiceProvider)certSender.PublicKey.Key; 
    var plainSender = Encoding.Default.GetBytes("this is plain text"); 
    var cipher = providerSender.Encrypt(plainSender, false); 

    ////////////////////////////////////////////////////// 
    // RECEIVER CODE 
    ////////////////////////////////////////////////////// 

    // get certificate 
    var store = new X509Store("MY", StoreLocation.LocalMachine); 
    store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); 
    var certReceiver = store.Certificates.Find(X509FindType.FindBySubjectName, "Test Subject", false)[0]; 

    // decrypt with private key 
    var providerReceiver = (RSACryptoServiceProvider)certReceiver.PrivateKey; 
    var plainReceiver = providerReceiver.Decrypt(cipher, false); 

    // check they are same 
    if (plainSender.Equals(plainReceiver)) 
    { 
     Console.WriteLine("Same!"); 
    } 
} 

Per riferimento, il certificato è stato realizzato e installato tramite

makecert.exe Test.cer -n "CN=Test Subject" -sr LocalMachine -ss My 

qualcuno può individuare quello che sto facendo di sbagliato? Grazie in anticipo!

+0

Nota a margine: dovresti davvero usare fOAEP = true. – CodesInChaos

risposta

7

Ok, trovato ciò che il problema è: serve a dire makecert 1) questo è il tipo chiave del soggetto del certificato è di "scambio" 2) per contrassegnare la chiave privata come esportabile

chiamata in modo makecert sembra

makecert.exe Test.cer -r -n "CN=Test Subject" -sr LocalMachine -ss My -sky Exchange -pe 
+0

l'aggiunta di "-sky Exchange" alla chiamata da riga di comando di makecert.exe ha risolto il mio problema. Questo contrassegna la chiave in modo che possa essere utilizzata anche per la crittografia/decrittografia. – Roboblob