Digital certificate __java of JAVA encryption and decryption

Source: Internet
Author: User
Tags base64 decrypt pkcs12

When interacting between systems, we often use digital certificates, digital certificates can help us verify identities, and so on, let's take a look at how to use digital certificates in Java.
We first use the Keytool tool to generate the KeyStore and export the public key certificate.
First step: Generate Keystroe Files
Execute the following command:

Keytool-genkey-validity 36000-alias www.jianggujin.com-keyalg Rsa-keystore test.keystore

The command-related parameters are as follows:

After the input, we need to follow the prompts to complete the follow-up information input, which we use the password is: 123456

Step two: Export the public key certificate
Once the KeyStore is generated, we can export the public key file and execute the following command:

Keytool-export-keystore Test.keystore-alias Www.jianggujin.com-file TEST.CER-RFC

The command-related parameters are as follows:

The full operation process is as follows:

After these two steps, we have the KeyStore and the certificate file, and like the previous cryptographic decryption tool class, we'll write a tool class for manipulating digital certificates:

Package Com.jianggujin.codec;
Import Java.io.FileInputStream;
Import Java.io.InputStream;
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.cert.X509Certificate;

Import Java.util.Date;

Import Javax.crypto.Cipher; /** * Digital Certificate * * @author Jianggujin * */public class Hqcertificate {private static hqcertificate certificate = NE

   W hqcertificate ();
   public static Hqcertificate getinstance () {return certificate; Private Hqcertificate () {}/** * keystore * * @author Jianggujin * */public static EN
      Um hqkeystore {JCEKS ("JCEKS"), JKS ("JKS"), DKs ("DKs"), PKCS11 ("Pkcs11"), PKCS12 ("pkcs12");

      private String name;
      Private Hqkeystore (String name) {this.name = name;
       Public String GetName () {  return this.name;

   }/** * java KeyStore (Java key Store,jks) Key_store *//public final String Key_store = "JKS";

   Public final String X509 = "X.509"; /** * The private key is obtained from KeyStore * * @param keystorepath * @param alias * @param password * @return * @thr OWS Exception * * Private Privatekey Getprivatekey (string Keystorepath, String alias, char[] password, hqkeystore ke
      Ystore) throws Exception {KeyStore ks = Getkeystore (keystorepath, password, KeyStore);
      Privatekey key = (Privatekey) ks.getkey (alias, password);
   Return key; /** * Certificate access to public key * * @param certificatepath * @return * @throws Exception/Priva Te publickey getpublickey (String certificatepath) throws Exception {Certificate certificate = getcertificate (cer
      Tificatepath);
      PublicKey key = Certificate.getpublickey ();
   Return key; /** * Get certificate * * @param certiFicatepath * @return * @throws Exception/Private certificate getcertificate (String certificatepath) thro
      WS Exception {certificatefactory certificatefactory = certificatefactory.getinstance (X509);
      FileInputStream in = new FileInputStream (Certificatepath);
      Certificate Certificate = certificatefactory.generatecertificate (in);
      In.close ();
   return certificate;
    /** * Obtains certificate * * @param keystorepath * @param alias * @param password * @return * @throws Exception * * Private certificate GetCertificate (string Keystorepath, String alias, char[] password, hqkey
      Store KeyStore) throws Exception {KeyStore ks = Getkeystore (keystorepath, password, keyStore);
   Return GetCertificate (KS, alias); Private certificate GetCertificate (KeyStore KeyStore, String alias) throws Exception {certificate certific
      ate = Keystore.getcertificate (alias);
 return certificate;  /** * Access to KeyStore * * @param keystorepath * @param password * @return * @throws Exception
      */Public KeyStore Getkeystore (String keystorepath, char[] password, Hqkeystore KeyStore) throws Exception {
      KeyStore store = null;
      FileInputStream is = new FileInputStream (Keystorepath);
      Store = Getkeystore (is, password, keyStore);
      Is.close ();
   return store; Public KeyStore Getkeystore (InputStream in, char[] password, Hqkeystore KeyStore) throws Exception {Keysto
      Re ks = Keystore.getinstance (Keystore.getname ());
      Ks.load (in, password);
   return KS; /** * Private key encryption * @param data * @param keystorepath * @param alias * @param password * @re Turn * @throws Exception * * Public byte[] Encrypt (byte[] data, string Keystorepath, String alias, char[] Passwo Rd, Hqkeystore KeyStore) throws Exception {//Get private key privatekey Privatekey = GetprivatekEY (Keystorepath, alias, password, keyStore);

   Return Encrypt (data, privatekey);  Public byte[] Encrypt (byte[] data, Privatekey Privatekey) throws Exception {//encrypt data Cipher Cipher =
      Cipher.getinstance (Privatekey.getalgorithm ());
      Cipher.init (Cipher.encrypt_mode, Privatekey);
   return cipher.dofinal (data);
   /** * Public Key encryption * @param data * @param certificatepath * @return * @throws Exception * * Public byte[] Encrypt (byte[] data, String Certificatepath) throws Exception {//Obtain the key PublicKey PublicKey
      = Getpublickey (Certificatepath);

   Return Encrypt (data, publickey); Public byte[] Encrypt (byte[] data, PublicKey PublicKey) throws Exception {//encrypt data Cipher Cipher = C
      Ipher.getinstance (Publickey.getalgorithm ());
      Cipher.init (Cipher.encrypt_mode, PublicKey);

   return cipher.dofinal (data);
 /** * Private Key decryption * * @param data * @param keystorepath   * @param alias * @param password * @return * @throws Exception/public byte[] Decrypt (byte[) data,
      String Keystorepath, String alias, char[] password, Hqkeystore keyStore) throws Exception {//Get private key
      Privatekey Privatekey = Getprivatekey (Keystorepath, alias, password, keyStore);
   Return decrypt (data, privatekey);  Public byte[] Decrypt (byte[] data, Privatekey Privatekey) throws Exception {//encrypt data Cipher Cipher =
      Cipher.getinstance (Privatekey.getalgorithm ());
      Cipher.init (Cipher.decrypt_mode, Privatekey);
   return cipher.dofinal (data);
   /** * Public Key decryption * @param data * @param certificatepath * @return * @throws Exception * * Public byte[] Decrypt (byte[] data, String Certificatepath) throws Exception {//Obtain the key PublicKey PublicKey
      = Getpublickey (Certificatepath);
      Encrypt the data Cipher Cipher = Cipher.getinstance (Publickey.getalgorithm ()); CiphEr.init (Cipher.decrypt_mode, PublicKey);
   Return decrypt (data, publickey); Public byte[] Decrypt (byte[] data, PublicKey PublicKey) throws Exception {//encrypt data Cipher Cipher = C
      Ipher.getinstance (Publickey.getalgorithm ());
      Cipher.init (Cipher.decrypt_mode, PublicKey);

   return cipher.dofinal (data); /** * Verify Certificate * * @param certificatepath * * @return/public boolean verifycertificate
   (String Certificatepath)
   {return verifycertificate (new Date (), Certificatepath); /** * Verify certificate is expired or invalid * * @param date * @param certificatepath * @return/Public
      Boolean verifycertificate (date date, String Certificatepath) {Boolean status = True;
         try {//Obtain Certificate Certificate Certificate = getcertificate (Certificatepath);
      Verify that the certificate expires or is invalid status = verifycertificate (date, certificate);
  catch (Exception e) {       Status = FALSE;
   } return status; /** * Verify that the certificate expires or is not valid * @param date * @param certificate * @return/Private Boolean Veri
      Fycertificate (date date, certificate certificate) {Boolean status = True;
         try {x509certificate x509certificate = (x509certificate) certificate;
      X509certificate.checkvalidity (date);
      catch (Exception e) {status = FALSE;
   } return status; /** * Signature * * @param keystorepath * @param alias * @param password * * @return * @t Hrows Exception * * Public byte[] sign (byte[] data, string Keystorepath, String alias, char[] password, Hqkeystore k Eystore) throws Exception {//Obtain Certificate Certificate Certificate = getcertificate (Keystorepath, alias,
      password, keyStore);
      Get the private key Privatekey Privatekey = Getprivatekey (Keystorepath, alias, password, keyStore); Return SiGN (data, certificate, Privatekey);
      Public byte[] Sign (byte[] data, certificate certificate, Privatekey Privatekey) throws Exception {//Obtain certificate

      X509Certificate x509certificate = (x509certificate) certificate;
      Build signature Signature Signature = signature.getinstance (X509certificate.getsigalgname ());
      Signature.initsign (Privatekey);
      Signature.update (data);
   return Signature.sign (); /** * Verification Signature * * @param data * @param sign * @param certificatepath * @return * @throws E Xception */Public Boolean verify (byte[] data, byte[] sign, String Certificatepath) throws Exception {//

      Obtain a certificate Certificate Certificate = getcertificate (Certificatepath);
   Return verify (data, sign, certificate); public boolean verify (byte[] data, byte[] sign, certificate certificate) throws Exception {//Get certificate X
      509Certificate x509certificate = (x509certificate) certificate;
    Get the public key  PublicKey PublicKey = X509certificate.getpublickey ();
      Build signature Signature Signature = signature.getinstance (X509certificate.getsigalgname ());
      Signature.initverify (PublicKey);

      Signature.update (data);
   return signature.verify (sign);
    /** * Verify Certificate * * @param keystorepath * @param alias * @param password * @return 
   */Public Boolean verifycertificate (date date, string Keystorepath, String alias, char[] password, hqkeystore keyStore)
      {Boolean status = True;
         try {Certificate certificate = getcertificate (Keystorepath, alias, password, keyStore);
      Status = Verifycertificate (date, certificate);
      catch (Exception e) {status = FALSE;
   } return status;
    /** * Verify Certificate * * @param keystorepath * @param alias * @param password * @return */Public Boolean verifycertificate (string Keystorepath, String AliAs, char[] password, Hqkeystore keyStore) {return verifycertificate (new Date (), Keystorepath, alias, password, K
   Eystore); }
}

Write the Test tools class and test using the KeyStore and certificate file We just generated:

Import Org.junit.Test;
Import com.jianggujin.codec.HQBase64;
Import Com.jianggujin.codec.HQCertificate;

Import Com.jianggujin.codec.HQCertificate.HQKeyStore;
   public class Certificatetest {hqcertificate certificate = hqcertificate.getinstance ();

   HQBase64 base64 = Hqbase64.getinstance ();
   Private char[] Password = "123456". ToCharArray ();
   Private String alias = "www.jianggujin.com";
   Private String Certificatepath = "Test.cer";

   Private String Keystorepath = "Test.keystore";
      @Test public void Encode () throws Exception {byte[] data = "Jianggujin". GetBytes ();
      Hqkeystore KeyStore = Hqkeystore.jks;
      byte[] Signresult = certificate.sign (data, Keystorepath, alias, password, keyStore);
      SYSTEM.ERR.PRINTLN ("Certificate of Authentication:" + certificate.verifycertificate (Certificatepath));
      System.err.println ("Signature:" + base64.encodetostring (Signresult));
      System.err.println ("Check:" + certificate.verify (data, Signresult, Certificatepath)); byte[] result = certIficate.encrypt (data, Keystorepath, alias, password, hqkeystore.jks);
      SYSTEM.ERR.PRINTLN ("Encryption:" + base64.encodetostring (Signresult));
   System.err.println ("Decrypt:" + New String (Certificate.decrypt (result, Certificatepath)); }
}

Execution Results:
Verifying Certificate: True
Signature: dczoecjxqgbrtsyxz6i94zuwgg/gkcmt0q8hjyan4p7holfcofqxxd1/alfjyqfijmr20et6abw/ cxecmcj4m7jqssq3pw/anyvndtqznflilxix9ytsroagf7z55ovpz6rhm/ys7bah17pegwrbtiurebiv/kbsw2z4ndbj2uhiwouhyy0j+ 8res4eq7lwqte6eabumsuyjozivbkg8onvpcqqcg3wtd7jqs7pbiygger5jhwcctsmpbtdr/x1/ 71brfl6zsybhnai4eu8lyfqentrgbccabfdbtf0hvwnv6krg38fk0otgftrci55lbz3cezypozi5f1azpvrmbq==
Check: True
Encryption: dczoecjxqgbrtsyxz6i94zuwgg/gkcmt0q8hjyan4p7holfcofqxxd1/alfjyqfijmr20et6abw/cxecmcj4m7jqssq3pw/ anyvndtqznflilxix9ytsroagf7z55ovpz6rhm/ys7bah17pegwrbtiurebiv/kbsw2z4ndbj2uhiwouhyy0j+ 8res4eq7lwqte6eabumsuyjozivbkg8onvpcqqcg3wtd7jqs7pbiygger5jhwcctsmpbtdr/x1/ 71brfl6zsybhnai4eu8lyfqentrgbccabfdbtf0hvwnv6krg38fk0otgftrci55lbz3cezypozi5f1azpvrmbq==
Decryption: Jianggujin

Related Article

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.