"Encrypt and Decrypt" C # How to read a PEM key file

Source: Internet
Author: User
Tags begin rsa private key modulus

1. First step using OpenSSL to convert Pem key to der key//e:\01doc\bin>openssl.exe rsa-in rsakeydec.pem-outform der-out pri.der
2, call the following program directly read der converted to C # required XML key, and then ciphertext decryption
3. OpenSSL
http://download.csdn.net/download/jiayanhui2877/4089521

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.IO;usingSystem.Security.Cryptography;usingSystem.ComponentModel;usingSystem.Runtime.InteropServices;/*refer:http://q.cnblogs.com/q/70822/http://blog.chinaunix.net/uid-26729093-id-4449165.html*/Namespace Consoleapplication1{class Program {Private Static int getintegersize(BinaryReader Binr) {byteBT =0;byteLowbyte =0x00;byteHighbyte =0x00;intCount =0; BT = Binr. ReadByte ();if(BT! =0x02)//expect integer                return 0; BT = Binr. ReadByte ();if(BT = =0x81) Count = Binr. ReadByte ();//Data size in next byte            Else                if(BT = =0x82) {Highbyte = Binr. ReadByte ();//Data size in next 2 bytesLowbyte = Binr. ReadByte ();byte[] Modint = {lowbyte, highbyte,0x00,0x00}; Count = Bitconverter.toint32 (Modint,0); }Else{count = BT;//We already have the data size} while(Binr. ReadByte () = =0x00)            {//remove High order zeros in dataCount-=1; } binr. Basestream.seek (-1, seekorigin.current);//last ReadByte wasn ' t a removed zero, so back up a byte            returnCount }//e:\01doc\010 Technical Document \openssl-1.0.2a\openssl_srcandlib\win32lib\bin>openssl.exe R        //sa-in rsakeydec.txt-outform der-out pri.der        //writing RSA Key         Public StaticRSACryptoServiceProviderDecodersaprivatekey(stringPrikey) {//var Privkey = convert.frombase64string (Prikey);            byte[] modulus, E, D, P, Q, DP, DQ, IQ;//---------Set up stream to decode the ASN.1 encoded RSA private key------            //memorystream mem = new MemoryStream (privkey);            //binaryreader binr = new BinaryReader (MEM);            stringPath =@ "D:\\project\\consoleapplication1\\li_pri.der"; FileStream fs =NewFileStream (path, filemode.open,fileaccess.read); BinaryReader Binr =NewBinaryReader (FS);//wrap Memory Stream with BinaryReader for easy reading            byteBT =0;ushortTwobytes =0;intElems =0;Try{twobytes = Binr. ReadUInt16 ();if(Twobytes = =0x8130)//data read as little endian order (actual data order for Sequence)Binr. ReadByte ();//advance 1 byte                Else if(Twobytes = =0x8230) Binr. ReadInt16 ();//advance 2 bytes                Else                    return NULL; Twobytes = Binr. ReadUInt16 ();if(Twobytes! =0x0102)//version Number                    return NULL; BT = Binr. ReadByte ();if(BT! =0x00)return NULL;//------All private key is an Integer sequences----Elems = Getintegersize (BINR); modulus = Binr.                Readbytes (Elems);                Elems = Getintegersize (BINR); E = Binr.                Readbytes (Elems);                Elems = Getintegersize (BINR); D = Binr.                Readbytes (Elems);                Elems = Getintegersize (BINR); P = Binr.                Readbytes (Elems);                Elems = Getintegersize (BINR); Q = Binr.                Readbytes (Elems);                Elems = Getintegersize (BINR); DP = Binr.                Readbytes (Elems);                Elems = Getintegersize (BINR); DQ = Binr.                Readbytes (Elems);                Elems = Getintegersize (BINR); IQ = Binr. Readbytes (Elems);//-------Create RSACryptoServiceProvider instance and initialize with public key-----RSACryptoServiceProvider RSA =NewRSACryptoServiceProvider (); RSAParameters Rsaparams =NewRSAParameters ();                Rsaparams.modulus = modulus;                Rsaparams.exponent = E;                RSAPARAMS.D = D;                RSAPARAMS.P = P;                RSAPARAMS.Q = Q;                RSAPARAMS.DP = DP;                RSAPARAMS.DQ = DQ;                Rsaparams.inverseq = IQ; Rsa. ImportParameters (Rsaparams);returnRSA; }Catch(Exception e) {Console.WriteLine (e.message + e.stacktrace);return NULL; }finally{Binr.            Close (); }        }/************************************************************************/        / * Your is PEM key, need to convert to C # RSA provider recognized key. First, take out the useless characters in the head and tail, and then use the following method to convert: * /        /************************************************************************/         Public Static void Privatekeydecfun()        {stringPrikey =@ "-----BEGIN RSA PRIVATE KEY-----MIICWWIBAAKBGQCF1A4LQYIPBQEUCZ9KKSFASQZKEFCBMGSM21SAKB5BO0SY07GD Cprojhf2xnqrv0cm7+lie3pbufsarui2wahzhaibplbl9z4fsfon5hsg6segbb17 Svke3zn/75goesqiqtyw4gujgzrbovvz+te                Tnn+nhhbquqbkhnigpfvapqidaqab Aogag0oms5kaf3lujn9bu+/enxab908dhg4oxjwrg2ie5muhzlnxhu+iqu7sd9dt Tbnqkfhiipwl9fwp/iw1v90cmuqgj0zhsxhaz7vak/ryqltyeiicil8mqwvnbaan LIOFQ2WBL7SYS3N71B4MLVVTYSAG0KRSJIPH5LV Gnbvzjgecqqdcawe4xnf7shwo NFLJRG29SOKNIUHYKTDGCV9FVAM9U50EK882WVFMSJP+TK+1CXJMRSNLOI40BXKC u ABA1JOTAKEAUFQ9FMZHFBFF3E6N57WLIAJ5C1MEYHATT6QDAF49OZJBGZH1PEPN Jdgnezfvy7u5bmp7/updislcfues5ekb2qjaf84qime /ozqedz7si/e9labllerb Taz17nlh4geqg6hwhfwt3vv6ykskbrplle5nbpqwelxx0wsposvcipflrqjapaff NQ+6j Z+eddxukgxopjbq4ujnjmc42ooft3kzzht66+ocp3m66bos+vdrxy0t5ghn 2fcj9ro8t+xbrdxasqjaarhpcg6te0f+lmuthtep1u8orf+       aqvqdhbq8myk+/pf/         lrzkfhkqtsj89oywdlsh3leykowsr9mafxsvhz9bsa==-----END RSA PRIVATE KEY-----" ; Prikey = Prikey.replace ("-----BEGIN RSA PRIVATE KEY-----","")                . Replace ("-----END RSA PRIVATE KEY-----",""); RSACryptoServiceProvider Rsaprovider = Decodersaprivatekey (Prikey);//rsacryptoserviceprovider Rsaprovider = Decodersaprivatekey ();            //rsaprovider.fromxmlstring ();String Privatekey = rsaprovider.toxmlstring (true);//The private key of the RSA algorithm is exported to the string Privatekey, and the parameter is true to export the private keyConsole.WriteLine (Privatekey);/************************************************************************/             /* The results of the program run as follows: * <rsakeyvalue><modulus>n9wuc0moqqanlamfzcrh2rem5bbqgzhrdntumpg+qttlgnoxg3ka6crxds Tuk1dhdo/pyhn6qvbbgq7otlmh2yqim6s25fc+bun6deyuoorbigwde0rynt2tf++rqbleiklwfuifcy M6waL1Wfk3k5z fjrxwalkgsotsidxvwqu=</modulus><exponent>aqab</exponent><p>3amhuf5x E0h1jp35Y6xtvbK cjyliwcrqxnffx72pvbudbjppnslxzrct/rzptql4zeujztoung8sgrmgwtstrq== </p><q>ufq9fmzhfbff3e6n57wlia J5c1meyhatt6qdaf49ozjbgzh1pepnjdgnezfvy7u5bmp7/updi Slcfues5ekb2q==</q><dp>f84qime/ozqedz7si/e9 LABLLERBTAZ17NLH4GEQG6HWHFWT3VV6YKSKB Rplle5nbpqwelxx0wsposvcipflrq==</dp><dq>paffnq+6jz+eddxuk Gxopjbq4ujnjmc42ooft3kz zht66+ocp3m66bos+vdrxy0t5ghn2fcj9ro8t+xbrdxasq==</dq><inverseq>arhpcg6t                E0f+lmuth Tep1u8orf+aqvqdhbq8myk+/pf/lrzkfhkqtsj89oywdlsh3leykowsr9mafxsvhz9bsa==</inverse Q><d>g0oms5kaF3LUJN9BU+/ENXAB908DHG4OXJWRG2IE5MUHZLNXHU+IQU7SD9DTTBNQKFHIIPWL9FW P/iw1v90cmuqgj0zhsxhaz7vak/ryqltyeiicil                  8MQWVNBAANLIOFQ2WBL7SYS3N71B4MLVVTYSAG0KR sjiph5lvgnbvzjge=</d></rsakeyvalue> Please press any key to continue ... */            /************************************************************************/} Public Static void PrivateKeyDecFun1() {RSACryptoServiceProvider Rsaprovider = Decodersaprivatekey (NULL); String Privatekey = rsaprovider.toxmlstring (true);//The private key of the RSA algorithm is exported to the string Privatekey, and the parameter is true to export the private keyConsole.WriteLine (Privatekey); }Static voidMain (string[] args) {privatekeydecfun (); PrivateKeyDecFun1 ();return; }    }}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Encrypt and Decrypt" C # How to read a PEM key file

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.