Java uses P12 certificate signing, verification, encryption, decryption

Source: Internet
Author: User
Tags aliases decrypt stringbuffer

Required Jar:bouncycastle.jar

Configuration file Cert.properties

CERT_PATH=E://TEST.P12
cert_pwd=123456

The Certutil.java code is as follows

Package test.test;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.InputStream;
Import Java.security.KeyStore;
Import Java.security.PrivateKey;
Import Java.security.PublicKey;
Import java.security.Security;
Import Java.security.Signature;
Import Java.security.cert.Certificate;
Import Java.security.cert.X509Certificate;
Import java.util.Enumeration;
Import Java.util.Iterator;
Import Java.util.LinkedHashMap;
Import Java.util.Map;

Import java.util.Properties;

Import Javax.crypto.Cipher;
Import Org.apache.log4j.Logger;

Import Org.bouncycastle.jce.provider.BouncyCastleProvider;
 /** * Class Name: CertUtil * Description: P12 certificate Tool type * Version: V1.0 * Modify April 3, 2017 morning 09:06:37 * copyright.
    * * Public class CertUtil {private static Logger Logger = Logger.getlogger (Certutil.class);

    private static KeyStore KeyStore;
    private static String Cert_path;
    private static String cert_pwd;
    Private final static String Key_store_type = "PKCS12"; static {Properties PRop = new Properties (); try {prop.load (Thread.CurrentThread (). Getcontextclassloader (). getResourceAsStream ("Test/test/cert.properties"
        ));
        catch (Exception e) {logger.error ("fail to read cert.properties ...");
        } Cert_path = Prop.getproperty ("Cert_path");

        Cert_pwd = Prop.getproperty ("Cert_pwd");
            if (KeyStore = = null) {try {KeyStore = Initkeystore ();
            catch (Exception e) {logger.error ("fail to init keystore ..."); }}/** * method: Getprivatekey * Description: Get private key * @return/public static Privatekey ge 
    Tprivatekey () throws Exception {return (Privatekey) Keystore.getkey (Getalias (), CertUtil.CERT_PWD.toCharArray ()); /** * Method: Getpublickey * Description: Get the Public key * @return * * * publickey Getpublickey ()
    Throws Exception {return getcertificate (). Getpublickey ();

  }  /** * Method: Getalias * Description: Get the first alias * @return/public static String Getalias () throws Exception {
        enumeration<string> aliases = keystore.aliases ();
        if (aliases.hasmoreelements ()) {return aliases.nextelement ();
    return null; /** * Method: Initkeystore * Description: Get KeyStore * @return * * * public static KeyStore Initkeystore () throw
        S Exception {security.addprovider (New Bouncycastleprovider ());
        KeyStore ks = keystore.getinstance (Certutil.key_store_type);
        Absolute path InputStream is = new FileInputStream (new File (Certutil.cert_path));
        Relative path//inputstream is = Thread.CurrentThread (). Getcontextclassloader (). getResourceAsStream (Certutil.cert_path);
        Ks.load (IS, CertUtil.CERT_PWD.toCharArray ());
        Is.close ();
    return KS; /** * Method: GetCertificate * Description: Obtain certificate * @return/public static certificate GetcertifiCate () throws Exception {return keystore.getcertificate (Getalias ());
     /** * Method: Getcipher * Description: Get cipher * @param ispublic whether public key mode * @param mode encryption/decryption * @return
        */public static Cipher Getcipher (boolean ispublic, int mode) throws Exception {Cipher Cipher = null;
            if (ispublic) {PublicKey PublicKey = Getpublickey ();  
            cipher = Cipher.getinstance (Publickey.getalgorithm ());
        Cipher.init (mode, publickey); 
            }else{Privatekey Privatekey = Getprivatekey ();  
            cipher = Cipher.getinstance (Privatekey.getalgorithm ());  
        Cipher.init (mode, privatekey);
    return cipher; /** * Method: Bytestostrhex * Description: Array converted to 16 String * @param bytes Source array * @return string/Publ
        IC Static final String bytestostrhex (byte[] bytes) {stringbuffer sb = new StringBuffer (bytes.length);
        String stemp; for (inti = 0; i < bytes.length;
            i++) {stemp = integer.tohexstring (0xFF & Bytes[i]);
            if (Stemp.length () < 2) sb.append (0);
        Sb.append (Stemp.touppercase ());
    return sb.tostring ();
    /** * Method: Hexstrtobytes * Description: Restore 16 to byte array * @param str 16 String * @return byte[] * *
        private static final byte[] Hexstrtobytes (String str) {byte[] bytes;
        bytes = new Byte[str.length ()/2]; for (int i = 0; i < bytes.length i++) {bytes[i] = (byte) integer.parseint (str.substring (2 * I, 2 * i + 2)
        , 16);
    return bytes; }/*========================================== Signature ================================================*//** * method : Sign * Description: Digitally sign and convert into * @param requestmap source data * @return/public static String sign (Map<strin G, string> Requestmap) throws Exception {//concatenation of request Parameters success string: Value1value2valuE3 ...
        StringBuffer sourcedata = new StringBuffer (); For (iterator<map.entry<string, string>> iter = Requestmap.entryset (). iterator (); Iter.hasnext ();)
            {map.entry<string, string> Entry = Iter.next ();
        Sourcedata.append (Entry.getvalue ());
        } byte[] bytes = sign (sourcedata.tostring (). GetBytes ());
    Return Bytestostrhex (bytes); /** * Method: Sign * Description: Digital signature * @param bytedata Source byte * @return/public static byte[] Sign
        (byte[] bytedata) throws Exception {Privatekey Privatekey = Getprivatekey ();
        X509Certificate x509certificate= (X509Certificate) getcertificate ();
        Signature Signature = signature.getinstance (X509certificate.getsigalgname ());
        Signature.initsign (Privatekey);
        Signature.update (Bytedata);
    return Signature.sign ();
  /** * Method: Verify * Description: In-process conversion and verification * @param SIGNSTR Signature String * @param requestmap source data   * @return */public static Boolean verify (String signstr, map<string, string> requestmap) throws Excepti

        On {byte[] SignData = hexstrtobytes (SIGNSTR);
        StringBuffer sourcedata = new StringBuffer (); For (iterator<map.entry<string, string>> iter = Requestmap.entryset (). iterator (); Iter.hasnext ();)
            {map.entry<string, string> Entry = Iter.next ();
        Sourcedata.append (Entry.getvalue ());
    Return Verify (Sourcedata.tostring (). GetBytes (), signdata); 
     /** * Method: Verify * Description: Certificate contains public key checksum signature * @param sourcedata source byte * @param signdata signature byte * @return */public static Boolean verify (Byte[] sourcedata,byte[] signdata) throws Exception {X509Certificate x5
        09Certificate = (x509certificate) getcertificate ();
        Signature Signature = signature.getinstance (X509certificate.getsigalgname ());
        Signature.initverify (X509Certificate); Signature.updaTe (SourceData);
    Return signature.verify (SignData); 
     /*========================================== Encryption =======================================*//** * Method: Encrypt * Description: Encrypt and convert into * @param requestmap source data * @param ispubencrypt whether to use public key encryption * @return * Tic string Encrypt (map<string, string> Requestmap, Boolean ispubencrypt) throws Exception {//concatenation of request parameters Success String: V
        Alue1value2value3 ...
        StringBuffer sourcedata = new StringBuffer (); For (iterator<map.entry<string, string>> iter = Requestmap.entryset (). iterator (); Iter.hasnext ();)
            {map.entry<string, string> Entry = Iter.next ();
        Sourcedata.append (Entry.getvalue ());
        } byte[] EncryptData = Encrypt (Sourcedata.tostring (). GetBytes (), ispubencrypt);
    Return Bytestostrhex (encryptdata); /** * Method: Encrypt * Description: Encryption * @param encryptdata to encrypt bytes * @param ispubencrypt whether to use public key encryption * @return */public static byte[] Encrypt (byte[] encryptdata, Boolean ispubencrypt) throws Exception {Cip
        Her cipher = Getcipher (Ispubencrypt, Cipher.encrypt_mode);
    Return cipher.dofinal (encryptdata);  /** * Method: Decrypt * Description: Convert into and decrypt * @param decryptstr encrypted String * @param ispubdecrypt whether to use public key decryption * @return */public static string decrypt (String decryptstr, Boolean ispubdecrypt) throws Exception {byte
        [] Decryptdata = Hexstrtobytes (DECRYPTSTR);
    return new String (Decrypt (Decryptdata, ispubdecrypt)); /** * Method: Decrypt * Description: Decrypt * @param decryptdata encrypted byte * @param ispubdecrypt whether to use public key decryption * @ret
        URN */public static byte[] Decrypt (byte[] Decryptdata, Boolean ispubdecrypt) throws Exception {
        Cipher Cipher = Getcipher (Ispubdecrypt, Cipher.decrypt_mode);

    Return cipher.dofinal (Decryptdata); public static void Main (string[] args) throws Exception {map<string, string> requestmap = new linkedhashmap<> ();
        Requestmap.put ("Batchno", "17005846899643554");
        Requestmap.put ("Amount", "100005");
        Requestmap.put ("Uapcode", "152516");

        SYSTEM.OUT.PRINTLN ("Request data:" + requestmap.tostring ());
        String signstr = certutil.sign (Requestmap);
        SYSTEM.OUT.PRINTLN ("Signature data:" + signstr);

        System.out.println ("Verification Result:" + certutil.verify (SIGNSTR, Requestmap));
        String priencryptstr = Certutil.encrypt (Requestmap, false);
        SYSTEM.OUT.PRINTLN ("Private key Encryption" + PRIENCRYPTSTR);

        SYSTEM.OUT.PRINTLN ("Public key decryption" + Certutil.decrypt (Priencryptstr, true));
        String pubencryptstr = Certutil.encrypt (Requestmap, true);
        SYSTEM.OUT.PRINTLN ("Public key Encryption" + PUBENCRYPTSTR);


    SYSTEM.OUT.PRINTLN ("Private key Decryption" + Certutil.decrypt (Pubencryptstr, false));
 }
}

The

results are as follows

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.