系统之间在进行交互的时候,我们经常会用到数字证书,数字证书可以帮我们验证身份等,下面我们就来看一下在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); } } 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419编写测试工具类,使用我们刚才生成的密钥库和证书文件进行测试:
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))); } } 123456789101112131415161718192021222324252627282930 123456789101112131415161718192021222324252627282930执行结果: 验证证书:true 签名:dCzoEcjXQgBrTsYxZ6I94zuwgg/GkCmT0q8HjYan4p7hOlfCoFqxXd1/alFjyqfiJmr20ET6aBw/cxECmcJ4m7JqssQ3Pw/aNyVNDTQznFLILxiX9ytSrOAGF7Z55OvpZ6rhm/YS7bAH17PegWrbtiuReBIv/Kbsw2Z4nDbJ2UhIwoUHYy0j+8RES4eQ7LwQtE6EabUmSuyJOzivbkg8onvpcQqCg3Wtd7jqS7pBiYggeR5jHWcCTSMpBtDr/X1/71brFl6zsyBhnAi4EU8lyfqeNtrgbCCaBfDBTf0hVWnv6kRg38fK0OtGFTRCI55Lbz3cEzYpOZi5f1AZpvrMBQ== 验签:true 加密:dCzoEcjXQgBrTsYxZ6I94zuwgg/GkCmT0q8HjYan4p7hOlfCoFqxXd1/alFjyqfiJmr20ET6aBw/cxECmcJ4m7JqssQ3Pw/aNyVNDTQznFLILxiX9ytSrOAGF7Z55OvpZ6rhm/YS7bAH17PegWrbtiuReBIv/Kbsw2Z4nDbJ2UhIwoUHYy0j+8RES4eQ7LwQtE6EabUmSuyJOzivbkg8onvpcQqCg3Wtd7jqS7pBiYggeR5jHWcCTSMpBtDr/X1/71brFl6zsyBhnAi4EU8lyfqeNtrgbCCaBfDBTf0hVWnv6kRg38fK0OtGFTRCI55Lbz3cEzYpOZi5f1AZpvrMBQ== 解密:jianggujin