JAVA加密解密之數位憑證__JAVA

來源:互聯網
上載者:User

系統之間在進行互動的時候,我們經常會用到數位憑證,數位憑證可以幫我們驗證身份等,下面我們就來看一下在java中如何使用數位憑證。
我們先使用keytool工具產生密鑰庫並匯出密鑰憑證。
第一步:產生keyStroe檔案
執行如下命令:

keytool -genkey -validity 36000 -alias www.jianggujin.com -keyalg RSA -keystore test.keystore

該命令相關參數如下:

輸入完後,我們需要按照提示完成後續資訊的輸入,這裡面我們使用的密碼為:123456

第二步:匯出密鑰憑證
產生完密鑰庫後,我們就可以匯出公開金鑰檔案了,執行如下命令:

keytool -export -keystore test.keystore -alias www.jianggujin.com -file test.cer -rfc

該命令相關參數如下:

完整操作過程如下:

經過這兩步後,我們就有了密鑰庫和認證檔案,和之前的加密解密工具類一樣,我們再來編寫一個用於運算元字認證的工具類:

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;/** * 數位憑證 *  * @author jianggujin * */public class HQCertificate{   private static HQCertificate certificate = new HQCertificate();   public static HQCertificate getInstance()   {      return certificate;   }   private HQCertificate()   {   }   /**    * 密鑰庫    *     * @author jianggujin    *    */   public static enum 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密鑰庫(Java Key Store,JKS)KEY_STORE    */   // public final String KEY_STORE = "JKS";   public final String X509 = "X.509";   /**    * 由KeyStore獲得私密金鑰    *     * @param keyStorePath    * @param alias    * @param password    * @return    * @throws Exception    */   private PrivateKey getPrivateKey(String keyStorePath, String alias, char[] password, HQKeyStore keyStore)         throws Exception   {      KeyStore ks = getKeyStore(keyStorePath, password, keyStore);      PrivateKey key = (PrivateKey) ks.getKey(alias, password);      return key;   }   /**    * 由Certificate獲得公開金鑰    *     * @param certificatePath    * @return    * @throws Exception    */   private PublicKey getPublicKey(String certificatePath) throws Exception   {      Certificate certificate = getCertificate(certificatePath);      PublicKey key = certificate.getPublicKey();      return key;   }   /**    * 獲得Certificate    *     * @param certificatePath    * @return    * @throws Exception    */   private Certificate getCertificate(String certificatePath) throws Exception   {      CertificateFactory certificateFactory = CertificateFactory.getInstance(X509);      FileInputStream in = new FileInputStream(certificatePath);      Certificate certificate = certificateFactory.generateCertificate(in);      in.close();      return certificate;   }   /**    * 獲得Certificate    *     * @param keyStorePath    * @param alias    * @param password    * @return    * @throws Exception    */   private Certificate getCertificate(String keyStorePath, String alias, char[] password, HQKeyStore keyStore)         throws Exception   {      KeyStore ks = getKeyStore(keyStorePath, password, keyStore);      return getCertificate(ks, alias);   }   private Certificate getCertificate(KeyStore keyStore, String alias) throws Exception   {      Certificate certificate = keyStore.getCertificate(alias);      return certificate;   }   /**    * 獲得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   {      KeyStore ks = KeyStore.getInstance(keyStore.getName());      ks.load(in, password);      return ks;   }   /**    * 私密金鑰加密    *     * @param data    * @param keyStorePath    * @param alias    * @param password    * @return    * @throws Exception    */   public byte[] encrypt(byte[] data, String keyStorePath, String alias, char[] password, HQKeyStore keyStore)         throws Exception   {      // 取得私密金鑰      PrivateKey privateKey = getPrivateKey(keyStorePath, alias, password, keyStore);      return encrypt(data, privateKey);   }   public byte[] encrypt(byte[] data, PrivateKey privateKey) throws Exception   {      // 對資料加密      Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());      cipher.init(Cipher.ENCRYPT_MODE, privateKey);      return cipher.doFinal(data);   }   /**    * 公開金鑰加密    *     * @param data    * @param certificatePath    * @return    * @throws Exception    */   public byte[] encrypt(byte[] data, String certificatePath) throws Exception   {      // 取得公開金鑰      PublicKey publicKey = getPublicKey(certificatePath);      return encrypt(data, publicKey);   }   public byte[] encrypt(byte[] data, PublicKey publicKey) throws Exception   {      // 對資料加密      Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());      cipher.init(Cipher.ENCRYPT_MODE, publicKey);      return cipher.doFinal(data);   }   /**    * 私密金鑰解密    *     * @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   {      // 取得私密金鑰      PrivateKey privateKey = getPrivateKey(keyStorePath, alias, password, keyStore);      return decrypt(data, privateKey);   }   public byte[] decrypt(byte[] data, PrivateKey privateKey) throws Exception   {      // 對資料加密      Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());      cipher.init(Cipher.DECRYPT_MODE, privateKey);      return cipher.doFinal(data);   }   /**    * 公開金鑰解密    *     * @param data    * @param certificatePath    * @return    * @throws Exception    */   public byte[] decrypt(byte[] data, String certificatePath) throws Exception   {      // 取得公開金鑰      PublicKey publicKey = getPublicKey(certificatePath);      // 對資料加密      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   {      // 對資料加密      Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());      cipher.init(Cipher.DECRYPT_MODE, publicKey);      return cipher.doFinal(data);   }   /**    * 驗證Certificate    *     * @param certificatePath    * @return    */   public boolean verifyCertificate(String certificatePath)   {      return verifyCertificate(new Date(), certificatePath);   }   /**    * 驗證Certificate是否到期或無效    *     * @param date    * @param certificatePath    * @return    */   public boolean verifyCertificate(Date date, String certificatePath)   {      boolean status = true;      try      {         // 取得認證         Certificate certificate = getCertificate(certificatePath);         // 驗證認證是否到期或無效         status = verifyCertificate(date, certificate);      }      catch (Exception e)      {         status = false;      }      return status;   }   /**    * 驗證認證是否到期或無效    *     * @param date    * @param certificate    * @return    */   private boolean verifyCertificate(Date date, Certificate certificate)   {      boolean status = true;      try      {         X509Certificate x509Certificate = (X509Certificate) certificate;         x509Certificate.checkValidity(date);      }      catch (Exception e)      {         status = false;      }      return status;   }   /**    * 簽名    *     * @param keyStorePath    * @param alias    * @param password    *     * @return    * @throws Exception    */   public byte[] sign(byte[] data, String keyStorePath, String alias, char[] password, HQKeyStore keyStore)         throws Exception   {      // 獲得認證      Certificate certificate = getCertificate(keyStorePath, alias, password, keyStore);      // 取得私密金鑰      PrivateKey privateKey = getPrivateKey(keyStorePath, alias, password, keyStore);      return sign(data, certificate, privateKey);   }   public byte[] sign(byte[] data, Certificate certificate, PrivateKey privateKey) throws Exception   {      // 獲得認證      X509Certificate x509Certificate = (X509Certificate) certificate;      // 構建簽名      Signature signature = Signature.getInstance(x509Certificate.getSigAlgName());      signature.initSign(privateKey);      signature.update(data);      return signature.sign();   }   /**    * 驗證簽名    *     * @param data    * @param sign    * @param certificatePath    * @return    * @throws Exception    */   public boolean verify(byte[] data, byte[] sign, String certificatePath) throws Exception   {      // 獲得認證      Certificate certificate = getCertificate(certificatePath);      return verify(data, sign, certificate);   }   public boolean verify(byte[] data, byte[] sign, Certificate certificate) throws Exception   {      // 獲得認證      X509Certificate x509Certificate = (X509Certificate) certificate;      // 獲得公開金鑰      PublicKey publicKey = x509Certificate.getPublicKey();      // 構建簽名      Signature signature = Signature.getInstance(x509Certificate.getSigAlgName());      signature.initVerify(publicKey);      signature.update(data);      return signature.verify(sign);   }   /**    * 驗證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;   }   /**    * 驗證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, keyStore);   }}

編寫測試載入器類,使用我們剛才產生的密鑰庫和認證檔案進行測試:

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.verifyCertificate(certificatePath));      System.err.println("簽名:" + base64.encodeToString(signResult));      System.err.println("驗簽:" + certificate.verify(data, signResult, certificatePath));      byte[] result = certificate.encrypt(data, keyStorePath, alias, password, HQKeyStore.JKS);      System.err.println("加密:" + base64.encodeToString(signResult));      System.err.println("解密:" + new String(certificate.decrypt(result, certificatePath)));   }}

執行結果:
驗證認證:true
簽名:dCzoEcjXQgBrTsYxZ6I94zuwgg/GkCmT0q8HjYan4p7hOlfCoFqxXd1/alFjyqfiJmr20ET6aBw/cxECmcJ4m7JqssQ3Pw/aNyVNDTQznFLILxiX9ytSrOAGF7Z55OvpZ6rhm/YS7bAH17PegWrbtiuReBIv/Kbsw2Z4nDbJ2UhIwoUHYy0j+8RES4eQ7LwQtE6EabUmSuyJOzivbkg8onvpcQqCg3Wtd7jqS7pBiYggeR5jHWcCTSMpBtDr/X1/71brFl6zsyBhnAi4EU8lyfqeNtrgbCCaBfDBTf0hVWnv6kRg38fK0OtGFTRCI55Lbz3cEzYpOZi5f1AZpvrMBQ==
驗簽:true
加密:dCzoEcjXQgBrTsYxZ6I94zuwgg/GkCmT0q8HjYan4p7hOlfCoFqxXd1/alFjyqfiJmr20ET6aBw/cxECmcJ4m7JqssQ3Pw/aNyVNDTQznFLILxiX9ytSrOAGF7Z55OvpZ6rhm/YS7bAH17PegWrbtiuReBIv/Kbsw2Z4nDbJ2UhIwoUHYy0j+8RES4eQ7LwQtE6EabUmSuyJOzivbkg8onvpcQqCg3Wtd7jqS7pBiYggeR5jHWcCTSMpBtDr/X1/71brFl6zsyBhnAi4EU8lyfqeNtrgbCCaBfDBTf0hVWnv6kRg38fK0OtGFTRCI55Lbz3cEzYpOZi5f1AZpvrMBQ==
解密:jianggujin

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.