cryptography - Certificate Encryption/Decryption Errors on C# -
cryptography - Certificate Encryption/Decryption Errors on C# -
the next command utilize create keystore called myalias.p12 , export certificate called myalias2.cer.
java keytool key , certificate management utility. allows users manage own public/private key pairs , 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 = (rsacryptoserviceprovider)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 perform encryption operations. but, found errors on line 46, (performing decryption):
a first chance exception of type 'system.nullreferenceexception' occurred in certtest.exe thread '' (0xcc8) has exited code 0 (0x0). @ certtest.program.decrypt(string data) in d:\vsworkspace\certtest\certtest\program.cs:line 46 @ certtest.program.main(string[] args) in d:\vsworkspace\certtest\certtest\program.cs:line 29
anyone have idea? because don't know how solve problem. much!
the nullreferenceexception you're getting because privatekey null. because .cer files includes single .x509 certificate, includes public key.
in case means can encrypt info using certificate. in order decrypt you'll need private key.
you can access private key using .p12 (or .pfx) file. pkcs#12 file includes (in general) both private key (password protected) , certificate(s).
there several x509certificate[2] constructor take password , automatically decrypt private key. 1 time loaded .p12 file code receive valid (non-null) rsacryptoserviceprovider instance , you'll able decrypt data.
btw should not encrypt string (or data) way using rsa :-) more details read http://pages.infinit.net/ctech/20031101-0151.html
c# cryptography certificate rsa public-key-encryption
Comments
Post a Comment