开发者

Certificate Encryption/Decryption Errors on C#

The following command is use to make a keystore called myalias.p12 and export a certificate called myalias2.cer.

Java Keytool is a key and certificate management utility. It allows users to manage their own public/private key pairs and certificates.

E:\>keytool -genkeypair -keyalg RSA -keysize 2048 -sigalg SHA1withRSA -validity 36000 -alias myalias2 -keystore myalias.p12 -storetype pkcs12 -dname "cn=www.myalias.com, ou=myalias2, o=myalias2, l=tp, st=tp, c=tw" -storepass 123456 -keypass 123456

E:\>keytool -export -alias myalias2 -keystore myalias.p12 -storetype pkcs12 -rfc -file myalias2.cer -storepass 123456

Encryption:

string input="hello";            
X509Certificate2 myCertificate = GetCertFromCerFile("e:\\myalias2.cer");
RSACryptoServiceProvider provider1 = (RSACryptoServic开发者_JAVA百科eProvider)myCertificate.PublicKey.Key;
byte[] buffer1 = Encoding.UTF8.GetBytes(input);
byte[] result = provider1.Encrypt(buffer1, false);
string data= Convert.ToBase64String(result); 

Decryption:

44.  RSACryptoServiceProvider provider2 = (RSACryptoServiceProvider)myCertificate.PrivateKey;
45.  byte[] buffer2 = Convert.FromBase64String(data);
46.  byte[] result2 = provider2.Decrypt(buffer2, false); // <-- error here
47.  String decryptedMessage = Encoding.UTF8.GetString(result2);

It can normally perform the encryption operations. But, I found some errors on Line 46, (performing the decryption):

A first chance exception of type 'System.NullReferenceException' occurred in CertTest.exe The thread '' (0xcc8) has exited with code 0 (0x0). at CertTest.Program.Decrypt(String data) in D:\vsworkspace\CertTest\CertTest\Program.cs:line 46 at CertTest.Program.Main(String[] args) in D:\vsworkspace\CertTest\CertTest\Program.cs:line 29

Anyone have Idea? Because I don't know how to solve this problem. Thanks very much!


The NullReferenceException you're getting is because PrivateKey is null. This is because .cer files only includes a single .X509 certificate, which only includes the public key.

In this case that means you can only encrypt data using the certificate. In order to decrypt it you'll need the private key.

You can get access to the private key using the .p12 (or .pfx) file. This PKCS#12 file includes (in general) both the private key (password protected) and the certificate(s).

There are several X509Certificate[2] constructor that will accept a password and automatically decrypt the private key. Once loaded from the .p12 file your code will receive a valid (non-null) RSACryptoServiceProvider instance and you'll be able to decrypt the data.

BTW you should not encrypt string (or data) this way using RSA :-) For more details read http://pages.infinit.net/ctech/20031101-0151.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜