Data type conversions for RSA keys: By valid string to PublicKey or Privatekey

Source: Internet
Author: User
Tags key string

Given the RSA public and private key of the Base64 encoding, the following two snippet codes can convert the string type to PublicKey and Privatekey types, followed by a complete test program.

The conversion code is as follows:

 public  static  PublicKey Getpublickey (String key) throws   Exception {              byte  [] keybytes;  Keybytes = (new   Base64decoder ()). Decodebuffer (             key);  X509encodedkeyspec KeySpec = new               Keyfactory keyfactory = keyfactory.getinstance ("RSA"              PublicKey publickey = Keyfactory.generatepublic (keySpec);  return         PublicKey;  }
 public  static  Privatekey            Getprivatekey (String key) throws   Exception {             byte  new   Base64decoder ()).            Decodebuffer (key); Pkcs8encodedkeyspec keySpec  = new   = keyfactory.getinstance ("RSA" );            Privatekey privatekey  = Keyfactory.generateprivate (KEYSPEC);       return   Privatekey; }

Note: Instead of tapping a string of letters to use as a key string, you need to generate a public key string and a private key string with strict code.

The complete program is as follows:

The program contains three parts for key conversion, encryption, and signing.

1 PackagePack1;2 3 ImportJava.security.Key;4 Importjava.security.KeyFactory;5 ImportJava.security.KeyPair;6 ImportJava.security.KeyPairGenerator;7 ImportJava.security.PrivateKey;8 ImportJava.security.PublicKey;9 Importjava.security.Signature;Ten ImportJava.security.interfaces.RSAPrivateKey; One ImportJava.security.interfaces.RSAPublicKey; A ImportJava.security.spec.PKCS8EncodedKeySpec; - ImportJava.security.spec.X509EncodedKeySpec; -  the ImportJavax.crypto.Cipher; -  - Importorg.apache.commons.codec.binary.Base64; -  + ImportSun.misc.BASE64Decoder; - ImportSun.misc.BASE64Encoder; +   A   at  Public classrsatest{ -      Public Static FinalString key_algorithm= "RSA"; -      Public Static FinalString signature_algorithm= "Md5withrsa"; -     Private Static Final intkey_size=1024; -     Private Static FinalString public_key= "Rsapublickey"; -     Private Static FinalString private_key= "Rsaprivatekey"; in      Public StaticString STR_PUBK = "migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqcqpvovsfxcwbbw8ckmcgwqnpsyuzf8rpapfb7lgsnvo44jhm/ Xxzdyzoytdfnmtbiukvi9pzisyp6rg+09gbui6ugwbz5dwbdbmqv5mpdof5dcqkb2bbr5ypfurpenypuz+pbfbg41d+bc+rwrixelwky7y9cad /mtjyhydj8ouwidaqab "; -      Public StaticString Str_prik = "miicdwibadanbgkqhkig9w0baqefaascamewggjdageaaogbako++ i9j9dzaftbxwowkdco2mxi7mxxe8a8vvssaydwjjgmez/hhmplohi1182a1si4pwl0/mizknqud7t2bu4jpqbafnknyemeyq/ Kw904xl0jcqhyfuvni99re8q3kltp6keugdjv34el6vbgjcqvarltj1xop8y0nifj2pw5tagmbaaecgyaggb8illmwxcelhjf6n1l0iwrh7fuhiuieoz6k0p6 rashsgwiynrmxfecbtx8zdaog0qawni7rn40ygpr5gs1fwdakhmnhkgqit6ww0vmd4hraaeyp78iy8blhlvblri2ncpihdh5+ l96v7d47zzi3zsozcj89s1es/k7/n4peeqjbapetggjy+lbocxqmhgyzuzdmgcs1un1ze2pt+xncvl2b+t8fxwjh3trrr8woy5uvtpik1hm/ ijt0t5qwqeh8yk0cqqc0tcv3d/bdb7boe9qzufdqkusptdpwagmx2ovpxjdq3sls9oa5+ fgnyey0ogyqtjde0b4irzld1o0ohlqpsumfakeah5fivqezdru2/psysr4yoadcdldt+h/jgrvefhqq/6eyujjkwp15ttfhqx3pie9/s6iet/ xyhyajaxmevxamlqjbaksdhvqjf9kajzkdesa7vyj/ Cocxuquwscmnhbcr5agfxge4e45utuoie1ekgcd6am6lwhx3rr6xdfdpb9je8bkcqb0spevgfoqkmk5i8xket9eeyp0fi8nv6eouck96exbzs4jv2saoqj9oj Egptprohbhivvumnqtbup10yjg59+8= "; to       /** + * Use Getpublickey to get the public key, return type PublicKey -        * @paramKey key string (base64 encoded) the        * @throwsException *        */ $        Public StaticPublicKey Getpublickey (String key)throwsException {Panax Notoginseng             byte[] keybytes; -Keybytes = (NewBase64decoder ()). Decodebuffer (key); theX509encodedkeyspec KeySpec =NewX509encodedkeyspec (keybytes); +Keyfactory keyfactory = keyfactory.getinstance ("RSA"); APublicKey PublicKey =keyfactory.generatepublic (keySpec); the             returnPublicKey; +       } -       /** $ * Get the private key $        * @paramKey key string (base64 encoded) -        * @throwsException -        */ the        Public StaticPrivatekey Getprivatekey (String key)throwsException { -             byte[] keybytes;WuyiKeybytes = (NewBase64decoder ()). Decodebuffer (key); thePkcs8encodedkeyspec KeySpec =NewPkcs8encodedkeyspec (keybytes); -Keyfactory keyfactory = keyfactory.getinstance ("RSA"); WuPrivatekey Privatekey =keyfactory.generateprivate (keySpec); -             returnPrivatekey; About       } $  -       //*************************** signature and verification ******************************* -        Public Static byte[] Sign (byte[] data)throwsexception{ -Privatekey Prik =Getprivatekey (Str_prik); ASignature sig =signature.getinstance (Signature_algorithm);  + sig.initsign (Prik); the sig.update (data); -           returnsig.sign (); $       } the        the        Public Static BooleanVerifybyte[] Data,byte[] sign)throwsexception{ thePublicKey PUBK =Getpublickey (STR_PUBK); theSignature sig =signature.getinstance (signature_algorithm); - sig.initverify (PUBK); in sig.update (data); the           returnsig.verify (sign); the       } About        the       //************************ Encryption and decryption ************************** the        Public Static byte[] Encrypt (byte[] bt_plaintext)throwsexception{ thePublicKey PublicKey =Getpublickey (STR_PUBK); +Cipher Cipher = cipher.getinstance ("RSA"); - Cipher.init (Cipher.encrypt_mode, publickey); the         byte[] bt_encrypted =cipher.dofinal (bt_plaintext);Bayi         returnbt_encrypted; the       } the        -        Public Static byte[] Decrypt (byte[] bt_encrypted)throwsexception{ -Privatekey Privatekey =Getprivatekey (Str_prik); theCipher Cipher = cipher.getinstance ("RSA"); the Cipher.init (Cipher.decrypt_mode, privatekey); the         byte[] bt_original =cipher.dofinal (bt_encrypted); the         returnbt_original; -       } the       //********************main functions: Cryptographic decryption and signature verification ********************* the        Public Static voidMain (string[] args)throwsException { theString Str_plaintext = "This is a piece of plaintext used to test the key conversion";94System.err.println ("Clear text:" +str_plaintext); the             byte[] Bt_cipher =Encrypt (str_plaintext.getbytes ()); theSYSTEM.OUT.PRINTLN ("After encryption:" +base64.encodebase64string (Bt_cipher)); the             98             byte[] bt_original =decrypt (bt_cipher); AboutString str_original =NewString (bt_original); -System.out.println ("Decryption Result:" +str_original);101             102String str= "Signed content";103System.err.println ("\ n Original:" +str);104             byte[] signature=Sign (Str.getbytes ()); theSYSTEM.OUT.PRINTLN ("Generate Signature:" +base64.encodebase64string (signature));106             Booleanstatus=Verify (Str.getbytes (), signature);107SYSTEM.OUT.PRINTLN ("Verify Condition:" +status);108       }109   the}

Once in Baidu know to seek this problem, has not been able to solve very well. Today coding test success, to share, technology is limited, the shortcomings of the point.

Data type conversions for RSA keys: from a valid string to PublicKey or Privatekey

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.