1. 程式人生 > >Java加密技術(八)——數字證書

Java加密技術(八)——數字證書

keystore 表示 encode png 代碼 簽名 更新 rsa加密 turn

原文:http://snowolf.iteye.com/blog/391931

請大家在閱讀本篇內容時先閱讀 Java加密技術(四),預先了解RSA加密算法。技術分享

在構建Java代碼實現前,我們需要完成證書的制作。
1.生成keyStroe文件
在命令行下執行以下命令:

Shell代碼 技術分享
  1. 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代碼 技術分享
  1. 輸入keystore密碼:
  2. 再次輸入新密碼:
  3. 您的名字與姓氏是什麽?
  4. [Unknown]: www.zlex.org
  5. 您的組織單位名稱是什麽?
  6. [Unknown]: zlex
  7. 您的組織名稱是什麽?
  8. [Unknown]: zlex
  9. 您所在的城市或區域名稱是什麽?
  10. [Unknown]: BJ
  11. 您所在的州或省份名稱是什麽?
  12. [Unknown]: BJ
  13. 該單位的兩字母國家代碼是什麽
  14. [Unknown]: CN
  15. CN=www.zlex.org, OU=zlex, O=zlex, L=BJ, ST=BJ, C=CN 正確嗎?
  16. [否]: Y
  17. 輸入<tomcat>的主密碼
  18. (如果和 keystore 密碼相同,按回車):
  19. 再次輸入新密碼:


這時,在D盤下會生成一個zlex.keystore的文件。

2.生成自簽名證書
光有keyStore文件是不夠的,還需要證書文件,證書才是直接提供給外界使用的公鑰憑證。
導出證書:

Shell代碼 技術分享
  1. keytool -export -keystore d:\zlex.keystore -alias www.zlex.org -file d:\zlex.cer -rfc



其中
-export指定為導出操作
-keystore指定keystore文件
-alias指定導出keystore文件中的別名
-file指向導出路徑
-rfc以文本格式輸出,也就是以BASE64編碼輸出
這裏的密碼是 123456

控制臺輸出:

Console代碼 技術分享
  1. 輸入keystore密碼:
  2. 保存在文件中的認證 <d:\zlex.cer>



當然,使用方是需要導入證書的!
可以通過自簽名證書完成CAS單點登錄系統的構建!技術分享

Ok,準備工作完成,開始Java實現!

通過java代碼實現如下:Coder類見 Java加密技術(一)

Java代碼 技術分享
  1. import java.io.FileInputStream;
  2. import java.security.KeyStore;
  3. import java.security.PrivateKey;
  4. import java.security.PublicKey;
  5. import java.security.Signature;
  6. import java.security.cert.Certificate;
  7. import java.security.cert.CertificateFactory;
  8. import java.security.cert.X509Certificate;
  9. import java.util.Date;
  10. import javax.crypto.Cipher;
  11. /**
  12. * 證書組件
  13. *
  14. * @author 梁棟
  15. * @version 1.0
  16. * @since 1.0
  17. */
  18. public abstract class CertificateCoder extends Coder {
  19. /**
  20. * Java密鑰庫(Java Key Store,JKS)KEY_STORE
  21. */
  22. public static final String KEY_STORE = "JKS";
  23. public static final String X509 = "X.509";
  24. /**
  25. * 由KeyStore獲得私鑰
  26. *
  27. * @param keyStorePath
  28. * @param alias
  29. * @param password
  30. * @return
  31. * @throws Exception
  32. */
  33. private static PrivateKey getPrivateKey(String keyStorePath, String alias,
  34. String password) throws Exception {
  35. KeyStore ks = getKeyStore(keyStorePath, password);
  36. PrivateKey key = (PrivateKey) ks.getKey(alias, password.toCharArray());
  37. return key;
  38. }
  39. /**
  40. * 由Certificate獲得公鑰
  41. *
  42. * @param certificatePath
  43. * @return
  44. * @throws Exception
  45. */
  46. private static PublicKey getPublicKey(String certificatePath)
  47. throws Exception {
  48. Certificate certificate = getCertificate(certificatePath);
  49. PublicKey key = certificate.getPublicKey();
  50. return key;
  51. }
  52. /**
  53. * 獲得Certificate
  54. *
  55. * @param certificatePath
  56. * @return
  57. * @throws Exception
  58. */
  59. private static Certificate getCertificate(String certificatePath)
  60. throws Exception {
  61. CertificateFactory certificateFactory = CertificateFactory
  62. .getInstance(X509);
  63. FileInputStream in = new FileInputStream(certificatePath);
  64. Certificate certificate = certificateFactory.generateCertificate(in);
  65. in.close();
  66. return certificate;
  67. }
  68. /**
  69. * 獲得Certificate
  70. *
  71. * @param keyStorePath
  72. * @param alias
  73. * @param password
  74. * @return
  75. * @throws Exception
  76. */
  77. private static Certificate getCertificate(String keyStorePath,
  78. String alias, String password) throws Exception {
  79. KeyStore ks = getKeyStore(keyStorePath, password);
  80. Certificate certificate = ks.getCertificate(alias);
  81. return certificate;
  82. }
  83. /**
  84. * 獲得KeyStore
  85. *
  86. * @param keyStorePath
  87. * @param password
  88. * @return
  89. * @throws Exception
  90. */
  91. private static KeyStore getKeyStore(String keyStorePath, String password)
  92. throws Exception {
  93. FileInputStream is = new FileInputStream(keyStorePath);
  94. KeyStore ks = KeyStore.getInstance(KEY_STORE);
  95. ks.load(is, password.toCharArray());
  96. is.close();
  97. return ks;
  98. }
  99. /**
  100. * 私鑰加密
  101. *
  102. * @param data
  103. * @param keyStorePath
  104. * @param alias
  105. * @param password
  106. * @return
  107. * @throws Exception
  108. */
  109. public static byte[] encryptByPrivateKey(byte[] data, String keyStorePath,
  110. String alias, String password) throws Exception {
  111. // 取得私鑰
  112. PrivateKey privateKey = getPrivateKey(keyStorePath, alias, password);
  113. // 對數據加密
  114. Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
  115. cipher.init(Cipher.ENCRYPT_MODE, privateKey);
  116. return cipher.doFinal(data);
  117. }
  118. /**
  119. * 私鑰解密
  120. *
  121. * @param data
  122. * @param keyStorePath
  123. * @param alias
  124. * @param password
  125. * @return
  126. * @throws Exception
  127. */
  128. public static byte[] decryptByPrivateKey(byte[] data, String keyStorePath,
  129. String alias, String password) throws Exception {
  130. // 取得私鑰
  131. PrivateKey privateKey = getPrivateKey(keyStorePath, alias, password);
  132. // 對數據加密
  133. Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
  134. cipher.init(Cipher.DECRYPT_MODE, privateKey);
  135. return cipher.doFinal(data);
  136. }
  137. /**
  138. * 公鑰加密
  139. *
  140. * @param data
  141. * @param certificatePath
  142. * @return
  143. * @throws Exception
  144. */
  145. public static byte[] encryptByPublicKey(byte[] data, String certificatePath)
  146. throws Exception {
  147. // 取得公鑰
  148. PublicKey publicKey = getPublicKey(certificatePath);
  149. // 對數據加密
  150. Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
  151. cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  152. return cipher.doFinal(data);
  153. }
  154. /**
  155. * 公鑰解密
  156. *
  157. * @param data
  158. * @param certificatePath
  159. * @return
  160. * @throws Exception
  161. */
  162. public static byte[] decryptByPublicKey(byte[] data, String certificatePath)
  163. throws Exception {
  164. // 取得公鑰
  165. PublicKey publicKey = getPublicKey(certificatePath);
  166. // 對數據加密
  167. Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
  168. cipher.init(Cipher.DECRYPT_MODE, publicKey);
  169. return cipher.doFinal(data);
  170. }
  171. /**
  172. * 驗證Certificate
  173. *
  174. * @param certificatePath
  175. * @return
  176. */
  177. public static boolean verifyCertificate(String certificatePath) {
  178. return verifyCertificate(new Date(), certificatePath);
  179. }
  180. /**
  181. * 驗證Certificate是否過期或無效
  182. *
  183. * @param date
  184. * @param certificatePath
  185. * @return
  186. */
  187. public static boolean verifyCertificate(Date date, String certificatePath) {
  188. boolean status = true;
  189. try {
  190. // 取得證書
  191. Certificate certificate = getCertificate(certificatePath);
  192. // 驗證證書是否過期或無效
  193. status = verifyCertificate(date, certificate);
  194. } catch (Exception e) {
  195. status = false;
  196. }
  197. return status;
  198. }
  199. /**
  200. * 驗證證書是否過期或無效
  201. *
  202. * @param date
  203. * @param certificate
  204. * @return
  205. */
  206. private static boolean verifyCertificate(Date date, Certificate certificate) {
  207. boolean status = true;
  208. try {
  209. X509Certificate x509Certificate = (X509Certificate) certificate;
  210. x509Certificate.checkValidity(date);
  211. } catch (Exception e) {
  212. status = false;
  213. }
  214. return status;
  215. }
  216. /**
  217. * 簽名
  218. *
  219. * @param keyStorePath
  220. * @param alias
  221. * @param password
  222. *
  223. * @return
  224. * @throws Exception
  225. */
  226. public static String sign(byte[] sign, String keyStorePath, String alias,
  227. String password) throws Exception {
  228. // 獲得證書
  229. X509Certificate x509Certificate = (X509Certificate) getCertificate(
  230. keyStorePath, alias, password);
  231. // 獲取私鑰
  232. KeyStore ks = getKeyStore(keyStorePath, password);
  233. // 取得私鑰
  234. PrivateKey privateKey = (PrivateKey) ks.getKey(alias, password
  235. .toCharArray());
  236. // 構建簽名
  237. Signature signature = Signature.getInstance(x509Certificate
  238. .getSigAlgName());
  239. signature.initSign(privateKey);
  240. signature.update(sign);
  241. return encryptBASE64(signature.sign());
  242. }
  243. /**
  244. * 驗證簽名
  245. *
  246. * @param data
  247. * @param sign
  248. * @param certificatePath
  249. * @return
  250. * @throws Exception
  251. */
  252. public static boolean verify(byte[] data, String sign,
  253. String certificatePath) throws Exception {
  254. // 獲得證書
  255. X509Certificate x509Certificate = (X509Certificate) getCertificate(certificatePath);
  256. // 獲得公鑰
  257. PublicKey publicKey = x509Certificate.getPublicKey();
  258. // 構建簽名
  259. Signature signature = Signature.getInstance(x509Certificate
  260. .getSigAlgName());
  261. signature.initVerify(publicKey);
  262. signature.update(data);
  263. return signature.verify(decryptBASE64(sign));
  264. }
  265. /**
  266. * 驗證Certificate
  267. *
  268. * @param keyStorePath
  269. * @param alias
  270. * @param password
  271. * @return
  272. */
  273. public static boolean verifyCertificate(Date date, String keyStorePath,
  274. String alias, String password) {
  275. boolean status = true;
  276. try {
  277. Certificate certificate = getCertificate(keyStorePath, alias,
  278. password);
  279. status = verifyCertificate(date, certificate);
  280. } catch (Exception e) {
  281. status = false;
  282. }
  283. return status;
  284. }
  285. /**
  286. * 驗證Certificate
  287. *
  288. * @param keyStorePath
  289. * @param alias
  290. * @param password
  291. * @return
  292. */
  293. public static boolean verifyCertificate(String keyStorePath, String alias,
  294. String password) {
  295. return verifyCertificate(new Date(), keyStorePath, alias, password);
  296. }
  297. }



再給出一個測試類:

Java代碼 技術分享
  1. import static org.junit.Assert.*;
  2. import org.junit.Test;
  3. /**
  4. *
  5. * @author 梁棟
  6. * @version 1.0
  7. * @since 1.0
  8. */
  9. public class CertificateCoderTest {
  10. private String password = "123456";
  11. private String alias = "www.zlex.org";
  12. private String certificatePath = "d:/zlex.cer";
  13. private String keyStorePath = "d:/zlex.keystore";
  14. @Test
  15. public void test() throws Exception {
  16. System.err.println("公鑰加密——私鑰解密");
  17. String inputStr = "Ceritifcate";
  18. byte[] data = inputStr.getBytes();
  19. byte[] encrypt = CertificateCoder.encryptByPublicKey(data,
  20. certificatePath);
  21. byte[] decrypt = CertificateCoder.decryptByPrivateKey(encrypt,
  22. keyStorePath, alias, password);
  23. String outputStr = new String(decrypt);
  24. System.err.println("加密前: " + inputStr + "\n\r" + "解密後: " + outputStr);
  25. // 驗證數據一致
  26. assertArrayEquals(data, decrypt);
  27. // 驗證證書有效
  28. assertTrue(CertificateCoder.verifyCertificate(certificatePath));
  29. }
  30. @Test
  31. public void testSign() throws Exception {
  32. System.err.println("私鑰加密——公鑰解密");
  33. String inputStr = "sign";
  34. byte[] data = inputStr.getBytes();
  35. byte[] encodedData = CertificateCoder.encryptByPrivateKey(data,
  36. keyStorePath, alias, password);
  37. byte[] decodedData = CertificateCoder.decryptByPublicKey(encodedData,
  38. certificatePath);
  39. String outputStr = new String(decodedData);
  40. System.err.println("加密前: " + inputStr + "\n\r" + "解密後: " + outputStr);
  41. assertEquals(inputStr, outputStr);
  42. System.err.println("私鑰簽名——公鑰驗證簽名");
  43. // 產生簽名
  44. String sign = CertificateCoder.sign(encodedData, keyStorePath, alias,
  45. password);
  46. System.err.println("簽名:\r" + sign);
  47. // 驗證簽名
  48. boolean status = CertificateCoder.verify(encodedData, sign,
  49. certificatePath);
  50. System.err.println("狀態:\r" + status);
  51. assertTrue(status);
  52. }
  53. }



控制臺輸出:

Console代碼 技術分享
  1. 公鑰加密——私鑰解密
  2. 加密前: Ceritificate
  3. 解密後: Ceritificate
  4. 私鑰加密——公鑰解密
  5. 加密前: sign
  6. 解密後: sign
  7. 私鑰簽名——公鑰驗證簽名
  8. 簽名:
  9. pqBn5m6PJlfOjH0A6U2o2mUmBsfgyEY1NWCbiyA/I5Gc3gaVNVIdj/zkGNZRqTjhf3+J9a9z9EI7
  10. 6F2eWYd7punHx5oh6hfNgcKbVb52EfItl4QEN+djbXiPynn07+Lbg1NOjULnpEd6ZhLP1YwrEAuM
  11. OfvX0e7/wplxLbySaKQ=
  12. 狀態:
  13. true



由此完成了證書驗證體系!技術分享

同樣,我們可以對代碼做簽名——代碼簽名!技術分享
通過工具JarSigner可以完成代碼簽名。
這裏我們對tools.jar做代碼簽名,命令如下:

Shell代碼 技術分享
  1. jarsigner -storetype jks -keystore zlex.keystore -verbose tools.jar www.zlex.org


控制臺輸出:

Console代碼 技術分享
  1. 輸入密鑰庫的口令短語:
  2. 正在更新: META-INF/WWW_ZLEX.SF
  3. 正在更新: META-INF/WWW_ZLEX.RSA
  4. 正在簽名: org/zlex/security/Security.class
  5. 正在簽名: org/zlex/tool/Main$1.class
  6. 正在簽名: org/zlex/tool/Main$2.class
  7. 正在簽名: org/zlex/tool/Main.class
  8. 警告:
  9. 簽名者證書將在六個月內過期。



此時,我們可以對簽名後的jar做驗證!技術分享
驗證tools.jar,命令如下:

Shell代碼 技術分享
  1. jarsigner -verify -verbose -certs tools.jar


控制臺輸出:

Console代碼 技術分享
  1. 402 Sat Jun 20 16:25:14 CST 2009 META-INF/MANIFEST.MF
  2. 532 Sat Jun 20 16:25:14 CST 2009 META-INF/WWW_ZLEX.SF
  3. 889 Sat Jun 20 16:25:14 CST 2009 META-INF/WWW_ZLEX.RSA
  4. sm 590 Wed Dec 10 13:03:42 CST 2008 org/zlex/security/Security.class
  5. X.509, CN=www.zlex.org, OU=zlex, O=zlex, L=BJ, ST=BJ, C=CN
  6. [證書將在 09-9-18 下午3:27 到期]
  7. sm 705 Tue Dec 16 18:00:56 CST 2008 org/zlex/tool/Main$1.class
  8. X.509, CN=www.zlex.org, OU=zlex, O=zlex, L=BJ, ST=BJ, C=CN
  9. [證書將在 09-9-18 下午3:27 到期]
  10. sm 779 Tue Dec 16 18:00:56 CST 2008 org/zlex/tool/Main$2.class
  11. X.509, CN=www.zlex.org, OU=zlex, O=zlex, L=BJ, ST=BJ, C=CN
  12. [證書將在 09-9-18 下午3:27 到期]
  13. sm 12672 Tue Dec 16 18:00:56 CST 2008 org/zlex/tool/Main.class
  14. X.509, CN=www.zlex.org, OU=zlex, O=zlex, L=BJ, ST=BJ, C=CN
  15. [證書將在 09-9-18 下午3:27 到期]
  16. s = 已驗證簽名
  17. m = 在清單中列出條目
  18. k = 在密鑰庫中至少找到了一個證書
  19. i = 在身份作用域內至少找到了一個證書
  20. jar 已驗證。
  21. 警告:
  22. 此 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加密技術(八)——數字證書