Generate an RSA public key with Java Keytool (with code validation)

Source: Internet
Author: User
Tags base64 string format asymmetric encryption

The use of Keytool
The Keytool program is provided by the JDK to generate and view certificates and keys. The KeyStore is a key container that can hold multiple key and related information.
Each key is referenced by an alias aliases. You can export the key in KeyStore to a certificate file. cer. Obviously, the. cer generated with Keytool
is a certificate that is not signed by the CA.

Add a key

Keytool-genkey-alias acosta-keyalg rsa-keysize 1024-keystore acosta.keystore

View all key in KeyStore

Keytool-list-keystore Acosta.keystore

View one of the records specified in KeyStore

Keytool-list-v-alias Acosta-keystore Acosta.keystore

Export key from KeyStore to certificate file

Keytool-list-v-alias acosta-keystore acosta.keystore  -export-file acosta.cer

Using Java Code Validation

The code is as follows
Rsautil.java
Package Com.cn.costa.testdemo.RSA;
Import Java.io.ByteArrayOutputStream;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Java.security.Key;
Import Java.security.KeyFactory;
Import Java.security.KeyPair;
Import Java.security.KeyPairGenerator;
Import Java.security.KeyStore;
Import Java.security.PrivateKey;
Import Java.security.PublicKey;
Import Java.security.Signature;
Import Java.security.cert.Certificate;
Import Java.security.cert.CertificateFactory;
Import Java.security.interfaces.RSAPrivateKey;
Import Java.security.interfaces.RSAPublicKey;
Import Java.security.spec.PKCS8EncodedKeySpec;
Import Java.security.spec.X509EncodedKeySpec;
Import Java.util.HashMap;

Import Java.util.Map;

Import Javax.crypto.Cipher; /** * <p> * RSA public/private key/Signature Toolkit * </p> * <p> * * </p> * <p> * The key in string format is BASE64 in the case of special instructions Code Format <br/> * Because the speed of asymmetric encryption is extremely slow, the general file does not use it to encrypt, but uses symmetric encryption,<br/> * Asymmetric encryption algorithm can be used to encrypt the symmetric key encryption, so that the security of the key to ensure the security of the data * </p&
 Gt * * @author WEchart * @date 2016-4-26 * @version 1.0/public class Rsautils {public static final String key_algorithm = "RSA                   ";      Cryptographic algorithm RSA public static final String signature_algorithm = "Md5withrsa";            Signature Algorithm private static final String Public_key = "Rsapublickey";          Gets the key private static final String Private_key = "Rsaprivatekey";                   Gets the key private static final int max_encrypt_block = 117;                   RSA maximum encrypted plaintext size private static final int max_decrypt_block = 128; RSA maximum decryption Text size/** * <p> * Generate key pair (public and private) * </p> * @return * @throws excep tion */public static map<string, Object> Genkeypair () throws Exception {Keypairgenerator Keypairg
        En = Keypairgenerator.getinstance (key_algorithm);
        Keypairgen.initialize (1024);
        KeyPair KeyPair = Keypairgen.generatekeypair (); Rsapublickey PublicKey = (rsapublickey) keypAir.getpublic ();
        Rsaprivatekey Privatekey = (rsaprivatekey) keypair.getprivate ();
        map<string, object> keymap = new hashmap<string, object> (2);
        Keymap.put (Public_key, PublicKey);
        Keymap.put (Private_key, Privatekey);
    return keymap; /** * <p> * Generate digital signatures for information with private key * </p> * @param data encrypted @param Privateke Y private key (BASE64 encoding) * * @return * @throws Exception/public static String sign (byte[) data, String p
        Rivatekey) throws Exception {byte[] keybytes = Base64utils.decode (Privatekey);
        Pkcs8encodedkeyspec Pkcs8keyspec = new Pkcs8encodedkeyspec (keybytes);
        Keyfactory keyfactory = keyfactory.getinstance (key_algorithm);
        Privatekey Privatek = keyfactory.generateprivate (Pkcs8keyspec);
        Signature Signature = signature.getinstance (signature_algorithm);
        Signature.initsign (Privatek);
        Signature.update (data); Return BaSe64utils.encode (Signature.sign ()); /** * <p> * Verify Digital signature * </p> * @param data encrypted @param publickey public key (BA SE64 code) * @param sign Digital Signature * * @return * @throws Exception */public static Boolean Verify (byte[] data, string publickey, String sign) throws Exception {byte[] keybytes = base64utils.de
        Code (PUBLICKEY);
        X509encodedkeyspec Keyspec = new X509encodedkeyspec (keybytes);
        Keyfactory keyfactory = keyfactory.getinstance (key_algorithm);
        PublicKey Publick = Keyfactory.generatepublic (Keyspec);
        Signature Signature = signature.getinstance (signature_algorithm);
        Signature.initverify (Publick);
        Signature.update (data);
    Return signature.verify (Base64utils.decode (sign)); /** *//** * <P> * Private key decryption * </p> * * @param encrypteddata Encrypted data * @param PR
    Ivatekey private key (BASE64 encoding) * @return * @throws Exception */public static byte[] Decryptbyprivatekey (byte[] EncryptedData, String Privatekey)
        Throws Exception {byte[] keybytes = Base64utils.decode (Privatekey);
        Pkcs8encodedkeyspec Pkcs8keyspec = new Pkcs8encodedkeyspec (keybytes);
        Keyfactory keyfactory = keyfactory.getinstance (key_algorithm);
        Key Privatek = keyfactory.generateprivate (Pkcs8keyspec);
        Cipher Cipher = cipher.getinstance (Keyfactory.getalgorithm ());
        Cipher.init (Cipher.decrypt_mode, Privatek);
        int inputlen = Encrypteddata.length;
        Bytearrayoutputstream out = new Bytearrayoutputstream ();
        int offSet = 0;
        Byte[] Cache;
        int i = 0;
                Decrypting data fragment while (Inputlen-offset > 0) {if (Inputlen-offset > Max_decrypt_block) {
            Cache = Cipher.dofinal (EncryptedData, OffSet, Max_decrypt_block); else {cache = cipher.dofinal (EncryptedData, OFFSET, Inputlen-offset);
            } out.write (cache, 0, cache.length);
            i++;
        OffSet = i * max_decrypt_block;
        } byte[] Decrypteddata = Out.tobytearray ();
        Out.close ();
    return decrypteddata; /** *//** * <p> * Public Key decryption * </p> * * @param encrypteddata Encrypted data * @param PU Blickey Public key (BASE64 encoding) * @return * @throws Exception * * (* * * (* *) Decryptbypublickey (byte[) en
        Crypteddata, String PublicKey) throws Exception {byte[] keybytes = Base64utils.decode (PublicKey);
        X509encodedkeyspec X509keyspec = new X509encodedkeyspec (keybytes);
        Keyfactory keyfactory = keyfactory.getinstance (key_algorithm);
        Key Publick = Keyfactory.generatepublic (X509keyspec);
        Cipher Cipher = cipher.getinstance (Keyfactory.getalgorithm ());
        Cipher.init (Cipher.decrypt_mode, Publick);
  int inputlen = Encrypteddata.length;      Bytearrayoutputstream out = new Bytearrayoutputstream ();
        int offSet = 0;
        Byte[] Cache;
        int i = 0;
                Decrypting data fragment while (Inputlen-offset > 0) {if (Inputlen-offset > Max_decrypt_block) {
            Cache = Cipher.dofinal (EncryptedData, OffSet, Max_decrypt_block);
            else {cache = cipher.dofinal (EncryptedData, OffSet, Inputlen-offset);
            } out.write (cache, 0, cache.length);
            i++;
        OffSet = i * max_decrypt_block;
        } byte[] Decrypteddata = Out.tobytearray ();
        Out.close ();
    return decrypteddata; /** *//** * <p> * Public key Encryption * </p> * * @param data source @param publickey public key ( BASE64 code) * @return * @throws Exception/public static byte[] Encryptbypublickey (byte[) data, String PublicKey) throws Exception {byte[] keybytes = Base64utils.decoDe (PublicKey);
        X509encodedkeyspec X509keyspec = new X509encodedkeyspec (keybytes);
        Keyfactory keyfactory = keyfactory.getinstance (key_algorithm);
        Key Publick = Keyfactory.generatepublic (X509keyspec);
        Encrypt the data Cipher Cipher = Cipher.getinstance (Keyfactory.getalgorithm ());
        Cipher.init (Cipher.encrypt_mode, Publick);
        int inputlen = Data.length;
        Bytearrayoutputstream out = new Bytearrayoutputstream ();
        int offSet = 0;
        Byte[] Cache;
        int i = 0;
                Data fragment encryption while (Inputlen-offset > 0) {if (Inputlen-offset > Max_encrypt_block) {
            Cache = cipher.dofinal (data, OffSet, Max_encrypt_block);
            else {cache = cipher.dofinal (data, OffSet, Inputlen-offset);
            } out.write (cache, 0, cache.length);
            i++;
        OffSet = i * max_encrypt_block;
 } byte[] EncryptedData = Out.tobytearray ();       Out.close ();
    return EncryptedData; /** * <p> * Private key encryption * </p> * @param data source * @param privatekey private key (BASE6 4 code) * @return * @throws Exception/public static byte[] Encryptbyprivatekey (byte[] data, String priv
        Atekey) throws Exception {byte[] keybytes = Base64utils.decode (Privatekey);
        Pkcs8encodedkeyspec Pkcs8keyspec = new Pkcs8encodedkeyspec (keybytes);
        Keyfactory keyfactory = keyfactory.getinstance (key_algorithm);
        Key Privatek = keyfactory.generateprivate (Pkcs8keyspec);
        Cipher Cipher = cipher.getinstance (Keyfactory.getalgorithm ());
        Cipher.init (Cipher.encrypt_mode, Privatek);
        int inputlen = Data.length;
        Bytearrayoutputstream out = new Bytearrayoutputstream ();
        int offSet = 0;
        Byte[] Cache;
        int i = 0; Data fragment encryption while (Inputlen-offset > 0) {if (Inputlen-offset > MAx_encrypt_block) {cache = cipher.dofinal (data, OffSet, Max_encrypt_block);
            else {cache = cipher.dofinal (data, OffSet, Inputlen-offset);
            } out.write (cache, 0, cache.length);
            i++;
        OffSet = i * max_encrypt_block;
        } byte[] EncryptedData = Out.tobytearray ();
        Out.close ();
    return EncryptedData; /** * <p> * Get private key * </p> * * @param keymap Key pair * @return * @throws E
        Xception */public static String Getprivatekey (map<string, object> keymap) throws Exception {
        Key key = (key) keymap.get (Private_key);
    Return Base64utils.encode (key.getencoded ()); /** * <p> * Get public key * </p> * * @param keymap Key pair * @return * @throws E Xception */public static String Getpublickey (map<string, object> keymap) throWS Exception {Key key = (key) keymap.get (Public_key);
    Return Base64utils.encode (key.getencoded ()); public static PublicKey Loadpublickeybyfile (String filepath) throws Exception {try {//pass certificate, obtained
           Take the public key certificatefactory CF = Certificatefactory.getinstance ("X.509");
           Certificate C = cf.generatecertificate (new FileInputStream (filepath));
           PublicKey PublicKey = C.getpublickey ();
       return publickey;  
       catch (IOException e) {throw new Exception ("Public key data stream read error");  
       catch (NullPointerException e) {throw new Exception ("The public key input stream is empty"); } public static Privatekey Loadprivatekeybyfile (string filepath, string alias, string password) throws Exceptio
           n {try {KeyStore ks= keystore.getinstance ("JKS");              

           Ks.load (New FileInputStream (filepath), Password.tochararray ()); Privatekey Privatekey = (privatekey) Ks.getkeY (alias, Password.tochararray ());
       return privatekey;
       catch (IOException e) {throw new Exception ("Private key Data read error");
       catch (NullPointerException e) {throw new Exception ("The private key input stream is empty");
        } public static void Main (string[] args) {String Serveralias = ' ";

        String Clientalias = "Acosta";
        String Serverpassword = "";

String Clientpassword = "Acosta";
String Serverprivatekey = "D:\\server.keystore";  

        String Serverpublickey = "D:\\server.cer";
        String Clientprivatekey = "E:\\testcer\\rsatest04\\acosta.keystore";  
String Clientpublickey = "E:\\testcer\\rsatest04\\acosta.cer";
String serverpublicstring = "";
        String serverprivatestring = "";
        String clientpublicstring = "";


        String clientprivatestring = ""; String orgstring = "{\ ret\": \ "0\", \ "expiretime\": \ "2015/10/28 23:59:59\", \ "rettxt\": \ "Ok\", \ "token\": \ " 69296128a59798e2d423d3b1a9f766f4\ "}";
        String encryptstring = "";

String decryptstring = "";
        Rsapublickey srvpubkey = null;
Rsapublickey cltpubkey = null;
        Rsaprivatekey srvprikey = null;

        Rsaprivatekey cltprikey = null; try{//1-Client public key Cltpubkey = (Rsapublickey) rsautils.loadpublickeybyfile (clientpublic

            Key); 2-Client private key Cltprikey = (Rsaprivatekey) rsautils.loadprivatekeybyfile (Clientprivatekey, Clientalias, ClientPass

Word);
3-service-side public key//Srvpubkey = (Rsapublickey) rsautils.loadpublickeybyfile (Serverpublickey); //4-server-side private key//Srvprikey = (Rsaprivatekey) rsautils.loadprivatekeybyfile (serverprivatekey

            , Serveralias, Serverpassword);
            System.out.println ("\nclientpublicstring:\n" +base64utils.encode (cltpubkey.getencoded ()) + "\ n"); System.out.println ("\nclientprivatestring:\n" +base64utils.encode (Cltprikey.getencOded ()) + "\ n");
System.out.println ("\nserverpublicstring:\n" +base64utils.encode (srvpubkey.getencoded ()) + "\ n");         
        System.out.println ("\nserverprivatestring:\n" +base64utils.encode (srvprikey.getencoded ()) + "\ n");
        }catch (Exception e) {e.printstacktrace ();
}//System.out.println ("\n=============================== Step-1: Client private key Encryption-server-side public key decryption \ n");          Client private key Encryption-service-side public key decryption//try{//byte[] data = Orgstring.getbytes ();////            
byte[] Encodeddata = Rsautils.encryptbyprivatekey (data, Base64utils.encode (cltprikey.getencoded ()));            
encryptstring = new String (encodeddata); byte[] Decodeddata = Rsautils.decryptbypublickey (Encodeddata, Base64utils.encode (srvpubkey.getenc
Oded ()));
decryptstring = new String (decodeddata);
System.out.println ("orginalstring:" +orgstring); System.out.println ("EncrypString: "+encryptstring); 
System.out.println ("decryptstring:" +decryptstring); }catch (Exception e) {//System.err.println ("Step-1 decryption failed!");///////SYSTEM.OUT.PRINTLN
("\n=============================== Step-2: Service-side private key encryption-client public key decryption \ n");          
Service-side private key encryption-client public key decryption//try{///////byte[] data = Orgstring.getbytes ();//            
byte[] Encodeddata = Rsautils.encryptbyprivatekey (data, Base64utils.encode (srvprikey.getencoded ()));        
encryptstring = new String (encodeddata); byte[] Decodeddata = Rsautils.decryptbypublickey (Encodeddata, Base64utils.encode (cltpubkey.getenc
Oded ()));
decryptstring = new String (decodeddata);
System.out.println ("orginalstring:" +orgstring);
System.out.println ("encrypstring:" +encryptstring); 
System.out.println ("decryptstring:" +decryptstring); }catch (Exception E{//System.err.println ("Step-2 decryption failed!");//} System.out.println ("\n==============================

        = Step-3: Client private key Encryption-client public key decryption \ n ");
        String orgString2 = "";

            Client private key Encryption-client public key decryption try{byte[] data = Orgstring.getbytes ();            
            byte[] Encodeddata = Rsautils.encryptbyprivatekey (data, Base64utils.encode (cltprikey.getencoded ()));            

            encryptstring = new String (encodeddata);
            byte[] Decodeddata = Rsautils.decryptbypublickey (Encodeddata, Base64utils.encode (cltpubkey.getencoded ()));

            decryptstring = new String (decodeddata);
            System.out.println ("orginalstring:" +orgstring);
            System.out.println ("encrypstring:" +encryptstring); 
        System.out.println ("decryptstring:" +decryptstring);
        }catch (Exception e) {System.err.println ("Step-3 decryption failed!"); }////SYSTEM.OUT.PRINTLN ("\n=============================== step-4: Server-side private key Encryption-server-side public key decryption \ n ");          
Service-side private key encryption-service-side public key decryption//try{////byte[] data = Orgstring.getbytes ();//            
byte[] Encodeddata = Rsautils.encryptbyprivatekey (data, Base64utils.encode (srvprikey.getencoded ()));        
encryptstring = new String (encodeddata); byte[] Decodeddata = Rsautils.decryptbypublickey (Encodeddata, Base64utils.encode (srvpubkey.getenc
Oded ()));
decryptstring = new String (decodeddata);
System.out.println ("orginalstring:" +orgstring);
System.out.println ("encrypstring:" +encryptstring); 
System.out.println ("decryptstring:" +decryptstring);
 }catch (Exception e) {//System.err.println ("Step-4 decryption failed!");//}///}
base64utils
Package Com.cn.costa.testdemo.RSA;

Import java.

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.