Java加密技術(八)——數字證書
原文:http://snowolf.iteye.com/blog/391931
請大家在閱讀本篇內容時先閱讀 Java加密技術(四),預先了解RSA加密算法。
在構建Java代碼實現前,我們需要完成證書的制作。
1.生成keyStroe文件
在命令行下執行以下命令:
- keytool -genkey -validity 36000 -alias www.zlex.org -keyalg RSA -keystore d:\zlex.keystore
其中
-genkey表示生成密鑰
-validity指定證書有效期,這裏是36000天
-alias指定別名,這裏是www.zlex.org
-keyalg指定算法,這裏是RSA
-keystore指定存儲位置,這裏是d:\zlex.keystore
在這裏我使用的密碼為 123456
控制臺輸出: Console代碼
- 輸入keystore密碼:
- 再次輸入新密碼:
- 您的名字與姓氏是什麽?
- [Unknown]: www.zlex.org
- 您的組織單位名稱是什麽?
- [Unknown]: zlex
- 您的組織名稱是什麽?
- [Unknown]: zlex
- 您所在的城市或區域名稱是什麽?
- [Unknown]: BJ
- 您所在的州或省份名稱是什麽?
- [Unknown]: BJ
- 該單位的兩字母國家代碼是什麽
- [Unknown]: CN
- CN=www.zlex.org, OU=zlex, O=zlex, L=BJ, ST=BJ, C=CN 正確嗎?
- [否]: Y
- 輸入<tomcat>的主密碼
- (如果和 keystore 密碼相同,按回車):
- 再次輸入新密碼:
這時,在D盤下會生成一個zlex.keystore的文件。
2.生成自簽名證書
光有keyStore文件是不夠的,還需要證書文件,證書才是直接提供給外界使用的公鑰憑證。
導出證書:
- keytool -export -keystore d:\zlex.keystore -alias www.zlex.org -file d:\zlex.cer -rfc
其中
-export指定為導出操作
-keystore指定keystore文件
-alias指定導出keystore文件中的別名
-file指向導出路徑
-rfc以文本格式輸出,也就是以BASE64編碼輸出
這裏的密碼是 123456
控制臺輸出:
- 輸入keystore密碼:
- 保存在文件中的認證 <d:\zlex.cer>
當然,使用方是需要導入證書的!
可以通過自簽名證書完成CAS單點登錄系統的構建!
Ok,準備工作完成,開始Java實現!
通過java代碼實現如下:Coder類見 Java加密技術(一)
- import java.io.FileInputStream;
- 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 梁棟
- * @version 1.0
- * @since 1.0
- */
- public abstract class CertificateCoder extends Coder {
- /**
- * Java密鑰庫(Java Key Store,JKS)KEY_STORE
- */
- public static final String KEY_STORE = "JKS";
- public static final String X509 = "X.509";
- /**
- * 由KeyStore獲得私鑰
- *
- * @param keyStorePath
- * @param alias
- * @param password
- * @return
- * @throws Exception
- */
- private static PrivateKey getPrivateKey(String keyStorePath, String alias,
- String password) throws Exception {
- KeyStore ks = getKeyStore(keyStorePath, password);
- PrivateKey key = (PrivateKey) ks.getKey(alias, password.toCharArray());
- return key;
- }
- /**
- * 由Certificate獲得公鑰
- *
- * @param certificatePath
- * @return
- * @throws Exception
- */
- private static PublicKey getPublicKey(String certificatePath)
- throws Exception {
- Certificate certificate = getCertificate(certificatePath);
- PublicKey key = certificate.getPublicKey();
- return key;
- }
- /**
- * 獲得Certificate
- *
- * @param certificatePath
- * @return
- * @throws Exception
- */
- private static 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 static Certificate getCertificate(String keyStorePath,
- String alias, String password) throws Exception {
- KeyStore ks = getKeyStore(keyStorePath, password);
- Certificate certificate = ks.getCertificate(alias);
- return certificate;
- }
- /**
- * 獲得KeyStore
- *
- * @param keyStorePath
- * @param password
- * @return
- * @throws Exception
- */
- private static KeyStore getKeyStore(String keyStorePath, String password)
- throws Exception {
- FileInputStream is = new FileInputStream(keyStorePath);
- KeyStore ks = KeyStore.getInstance(KEY_STORE);
- ks.load(is, password.toCharArray());
- is.close();
- return ks;
- }
- /**
- * 私鑰加密
- *
- * @param data
- * @param keyStorePath
- * @param alias
- * @param password
- * @return
- * @throws Exception
- */
- public static byte[] encryptByPrivateKey(byte[] data, String keyStorePath,
- String alias, String password) throws Exception {
- // 取得私鑰
- PrivateKey privateKey = getPrivateKey(keyStorePath, alias, password);
- // 對數據加密
- Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
- cipher.init(Cipher.ENCRYPT_MODE, privateKey);
- return cipher.doFinal(data);
- }
- /**
- * 私鑰解密
- *
- * @param data
- * @param keyStorePath
- * @param alias
- * @param password
- * @return
- * @throws Exception
- */
- public static byte[] decryptByPrivateKey(byte[] data, String keyStorePath,
- String alias, String password) throws Exception {
- // 取得私鑰
- PrivateKey privateKey = getPrivateKey(keyStorePath, alias, password);
- // 對數據加密
- Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
- cipher.init(Cipher.DECRYPT_MODE, privateKey);
- return cipher.doFinal(data);
- }
- /**
- * 公鑰加密
- *
- * @param data
- * @param certificatePath
- * @return
- * @throws Exception
- */
- public static byte[] encryptByPublicKey(byte[] data, String certificatePath)
- throws Exception {
- // 取得公鑰
- PublicKey publicKey = getPublicKey(certificatePath);
- // 對數據加密
- Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
- cipher.init(Cipher.ENCRYPT_MODE, publicKey);
- return cipher.doFinal(data);
- }
- /**
- * 公鑰解密
- *
- * @param data
- * @param certificatePath
- * @return
- * @throws Exception
- */
- public static byte[] decryptByPublicKey(byte[] data, String certificatePath)
- throws Exception {
- // 取得公鑰
- PublicKey publicKey = getPublicKey(certificatePath);
- // 對數據加密
- Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
- cipher.init(Cipher.DECRYPT_MODE, publicKey);
- return cipher.doFinal(data);
- }
- /**
- * 驗證Certificate
- *
- * @param certificatePath
- * @return
- */
- public static boolean verifyCertificate(String certificatePath) {
- return verifyCertificate(new Date(), certificatePath);
- }
- /**
- * 驗證Certificate是否過期或無效
- *
- * @param date
- * @param certificatePath
- * @return
- */
- public static 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 static 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 static String sign(byte[] sign, String keyStorePath, String alias,
- String password) throws Exception {
- // 獲得證書
- X509Certificate x509Certificate = (X509Certificate) getCertificate(
- keyStorePath, alias, password);
- // 獲取私鑰
- KeyStore ks = getKeyStore(keyStorePath, password);
- // 取得私鑰
- PrivateKey privateKey = (PrivateKey) ks.getKey(alias, password
- .toCharArray());
- // 構建簽名
- Signature signature = Signature.getInstance(x509Certificate
- .getSigAlgName());
- signature.initSign(privateKey);
- signature.update(sign);
- return encryptBASE64(signature.sign());
- }
- /**
- * 驗證簽名
- *
- * @param data
- * @param sign
- * @param certificatePath
- * @return
- * @throws Exception
- */
- public static boolean verify(byte[] data, String sign,
- String certificatePath) throws Exception {
- // 獲得證書
- X509Certificate x509Certificate = (X509Certificate) getCertificate(certificatePath);
- // 獲得公鑰
- PublicKey publicKey = x509Certificate.getPublicKey();
- // 構建簽名
- Signature signature = Signature.getInstance(x509Certificate
- .getSigAlgName());
- signature.initVerify(publicKey);
- signature.update(data);
- return signature.verify(decryptBASE64(sign));
- }
- /**
- * 驗證Certificate
- *
- * @param keyStorePath
- * @param alias
- * @param password
- * @return
- */
- public static boolean verifyCertificate(Date date, String keyStorePath,
- String alias, String password) {
- boolean status = true;
- try {
- Certificate certificate = getCertificate(keyStorePath, alias,
- password);
- status = verifyCertificate(date, certificate);
- } catch (Exception e) {
- status = false;
- }
- return status;
- }
- /**
- * 驗證Certificate
- *
- * @param keyStorePath
- * @param alias
- * @param password
- * @return
- */
- public static boolean verifyCertificate(String keyStorePath, String alias,
- String password) {
- return verifyCertificate(new Date(), keyStorePath, alias, password);
- }
- }
再給出一個測試類:
- import static org.junit.Assert.*;
- import org.junit.Test;
- /**
- *
- * @author 梁棟
- * @version 1.0
- * @since 1.0
- */
- public class CertificateCoderTest {
- private String password = "123456";
- private String alias = "www.zlex.org";
- private String certificatePath = "d:/zlex.cer";
- private String keyStorePath = "d:/zlex.keystore";
- @Test
- public void test() throws Exception {
- System.err.println("公鑰加密——私鑰解密");
- String inputStr = "Ceritifcate";
- byte[] data = inputStr.getBytes();
- byte[] encrypt = CertificateCoder.encryptByPublicKey(data,
- certificatePath);
- byte[] decrypt = CertificateCoder.decryptByPrivateKey(encrypt,
- keyStorePath, alias, password);
- String outputStr = new String(decrypt);
- System.err.println("加密前: " + inputStr + "\n\r" + "解密後: " + outputStr);
- // 驗證數據一致
- assertArrayEquals(data, decrypt);
- // 驗證證書有效
- assertTrue(CertificateCoder.verifyCertificate(certificatePath));
- }
- @Test
- public void testSign() throws Exception {
- System.err.println("私鑰加密——公鑰解密");
- String inputStr = "sign";
- byte[] data = inputStr.getBytes();
- byte[] encodedData = CertificateCoder.encryptByPrivateKey(data,
- keyStorePath, alias, password);
- byte[] decodedData = CertificateCoder.decryptByPublicKey(encodedData,
- certificatePath);
- String outputStr = new String(decodedData);
- System.err.println("加密前: " + inputStr + "\n\r" + "解密後: " + outputStr);
- assertEquals(inputStr, outputStr);
- System.err.println("私鑰簽名——公鑰驗證簽名");
- // 產生簽名
- String sign = CertificateCoder.sign(encodedData, keyStorePath, alias,
- password);
- System.err.println("簽名:\r" + sign);
- // 驗證簽名
- boolean status = CertificateCoder.verify(encodedData, sign,
- certificatePath);
- System.err.println("狀態:\r" + status);
- assertTrue(status);
- }
- }
控制臺輸出:
- 公鑰加密——私鑰解密
- 加密前: Ceritificate
- 解密後: Ceritificate
- 私鑰加密——公鑰解密
- 加密前: sign
- 解密後: sign
- 私鑰簽名——公鑰驗證簽名
- 簽名:
- pqBn5m6PJlfOjH0A6U2o2mUmBsfgyEY1NWCbiyA/I5Gc3gaVNVIdj/zkGNZRqTjhf3+J9a9z9EI7
- 6F2eWYd7punHx5oh6hfNgcKbVb52EfItl4QEN+djbXiPynn07+Lbg1NOjULnpEd6ZhLP1YwrEAuM
- OfvX0e7/wplxLbySaKQ=
- 狀態:
- true
由此完成了證書驗證體系!
同樣,我們可以對代碼做簽名——代碼簽名!
通過工具JarSigner可以完成代碼簽名。
這裏我們對tools.jar做代碼簽名,命令如下:
- jarsigner -storetype jks -keystore zlex.keystore -verbose tools.jar www.zlex.org
控制臺輸出:
- 輸入密鑰庫的口令短語:
- 正在更新: META-INF/WWW_ZLEX.SF
- 正在更新: META-INF/WWW_ZLEX.RSA
- 正在簽名: org/zlex/security/Security.class
- 正在簽名: org/zlex/tool/Main$1.class
- 正在簽名: org/zlex/tool/Main$2.class
- 正在簽名: org/zlex/tool/Main.class
- 警告:
- 簽名者證書將在六個月內過期。
此時,我們可以對簽名後的jar做驗證!
驗證tools.jar,命令如下:
- jarsigner -verify -verbose -certs tools.jar
控制臺輸出:
- 402 Sat Jun 20 16:25:14 CST 2009 META-INF/MANIFEST.MF
- 532 Sat Jun 20 16:25:14 CST 2009 META-INF/WWW_ZLEX.SF
- 889 Sat Jun 20 16:25:14 CST 2009 META-INF/WWW_ZLEX.RSA
- sm 590 Wed Dec 10 13:03:42 CST 2008 org/zlex/security/Security.class
- X.509, CN=www.zlex.org, OU=zlex, O=zlex, L=BJ, ST=BJ, C=CN
- [證書將在 09-9-18 下午3:27 到期]
- sm 705 Tue Dec 16 18:00:56 CST 2008 org/zlex/tool/Main$1.class
- X.509, CN=www.zlex.org, OU=zlex, O=zlex, L=BJ, ST=BJ, C=CN
- [證書將在 09-9-18 下午3:27 到期]
- sm 779 Tue Dec 16 18:00:56 CST 2008 org/zlex/tool/Main$2.class
- X.509, CN=www.zlex.org, OU=zlex, O=zlex, L=BJ, ST=BJ, C=CN
- [證書將在 09-9-18 下午3:27 到期]
- sm 12672 Tue Dec 16 18:00:56 CST 2008 org/zlex/tool/Main.class
- X.509, CN=www.zlex.org, OU=zlex, O=zlex, L=BJ, ST=BJ, C=CN
- [證書將在 09-9-18 下午3:27 到期]
- s = 已驗證簽名
- m = 在清單中列出條目
- k = 在密鑰庫中至少找到了一個證書
- i = 在身份作用域內至少找到了一個證書
- jar 已驗證。
- 警告:
- 此 jar 包含簽名者證書將在六個月內過期的條目。
代碼簽名認證的用途主要是對發布的軟件做驗證,支持 Sun Java .jar (Java Applet) 文件(J2SE)和 J2ME MIDlet Suite 文件。
相關鏈接:
Java加密技術(一)——BASE64與單向加密算法MD5&SHA&MAC
Java加密技術(二)——對稱加密DES&AES
Java加密技術(三)——PBE算法
Java加密技術(四)——非對稱加密算法RSA
Java加密技術(五)——非對稱加密算法的由來
Java加密技術(六)——數字簽名算法DSA
Java加密技術(七)——非對稱加密算法最高ECC
Java加密技術(八)——數字證書
Java加密技術(九)——初探SSL
Java加密技術(十)——單向認證
Java加密技術(十一)——雙向認證
Java加密技術(十二)——*.PFX(*.p12)&個人信息交換文件
Java加密技術(八)——數字證書