Java加密技术(九)

关键字: ssl

Java加密技术(八)中,我们模拟了一个基于 RSA非对称加密网络的安全通信。现在我们深度了解一下现有的安全网络通信——SSL。
我们需要构建一个由CA机构签发的有效证书,这里我们使用上文中生成的自签名证书 zlex.cer
这里,我们将证书导入到我们的密钥库。

Shell代码
  1. keytool-import-aliaswww.zlex.org-filed:/zlex.cer-keystored:/zlex.keystore


其中
-import表示 导入
-alias指定别名,这里是 www.zlex.org
-file指定算法,这里是 d:/zlex.cer
-keystore指定存储位置,这里是 d:/zlex.keystore
在这里我使用的密码为 654321

控制台输出:
Console代码
  1. 输入keystore密码:
  2. 再次输入新密码:
  3. 所有者:CN=www.zlex.org,OU=zlex,O=zlex,L=BJ,ST=BJ,C=CN
  4. 签发人:CN=www.zlex.org,OU=zlex,O=zlex,L=BJ,ST=BJ,C=CN
  5. 序列号:4a1e48df
  6. 有效期:ThuMay2816:18:39CST2009至WedAug2616:18:39CST2009
  7. 证书指纹:
  8. MD5:19:CA:E6:36:E2:DF:AD:96:31:97:2F:A9:AD:FC:37:6A
  9. SHA1:49:88:30:59:29:45:F1:69:CA:97:A9:6D:8A:CF:08:D2:C3:D5:C0:C4
  10. 签名算法名称:SHA1withRSA
  11. 版本:3
  12. 信任这个认证?[否]:y
  13. 认证已添加至keystore中


OK,最复杂的准备工作已经完成。
接下来我们将域名 www.zlex.org定位到本机上。打开 C:\Windows\System32\drivers\etc\hosts文件,将 www.zlex.org绑定在本机上。在文件末尾追加 127.0.0.1 www.zlex.org。现在通过地址栏访问 http://www.zlex.org,或者通过 ping命令,如果能够定位到本机,域名映射就搞定了。
现在,配置tomcat。先将 zlex.keystore拷贝到tomcat的conf目录下,然后配置 server.xml。将如下内容加入配置文件
Xml代码
  1. <Connector
  2. SSLEnabled="true"
  3. URIEncoding="UTF-8"
  4. clientAuth="false"
  5. keystoreFile="conf/zlex.keystore"
  6. keystorePass="123456"
  7. maxThreads="150"
  8. port="443"
  9. protocol="HTTP/1.1"
  10. scheme="https"
  11. secure="true"
  12. sslProtocol="TLS"/>

注意 clientAuth="false"测试阶段,置为 false,正式使用时建议使用 true。现在启动tomcat,访问 https://www.zlex.org/
显然,证书未能通过认证,这个时候你可以选择安装证书(上文中的 zlex.cer文件就是证书),作为 受信任的根证书颁发机构导入,再次重启浏览器(IE,其他浏览器对于域名www.zlex.org不支持本地方式访问),访问 https://www.zlex.org/,你会看到地址栏中会有个小锁 ,就说明安装成功。所有的浏览器联网操作已经在 RSA加密解密系统的保护之下了。但似乎我们感受不到。
这个时候很多人开始怀疑,如果我们要手工做一个这样的https的访问是不是需要把浏览器的这些个功能都实现呢?不需要!

接着上篇内容,给出如下代码实现:
Java代码
  1. importjava.io.FileInputStream;
  2. importjava.security.KeyStore;
  3. importjava.security.PrivateKey;
  4. importjava.security.PublicKey;
  5. importjava.security.Signature;
  6. importjava.security.cert.Certificate;
  7. importjava.security.cert.CertificateFactory;
  8. importjava.security.cert.X509Certificate;
  9. importjava.util.Date;
  10. importjavax.crypto.Cipher;
  11. importjavax.net.ssl.HttpsURLConnection;
  12. importjavax.net.ssl.KeyManagerFactory;
  13. importjavax.net.ssl.SSLContext;
  14. importjavax.net.ssl.SSLSocketFactory;
  15. importjavax.net.ssl.TrustManagerFactory;
  16. /**
  17. *证书组件
  18. *
  19. *@author梁栋
  20. *@version1.0
  21. *@since1.0
  22. */
  23. publicabstractclassCertificateCoderextendsCoder{
  24. /**
  25. *Java密钥库(JavaKeyStore,JKS)KEY_STORE
  26. */
  27. publicstaticfinalStringKEY_STORE="JKS";
  28. publicstaticfinalStringX509="X.509";
  29. publicstaticfinalStringSunX509="SunX509";
  30. publicstaticfinalStringSSL="SSL";
  31. /**
  32. *由KeyStore获得私钥
  33. *
  34. *@paramkeyStorePath
  35. *@paramalias
  36. *@parampassword
  37. *@return
  38. *@throwsException
  39. */
  40. privatestaticPrivateKeygetPrivateKey(StringkeyStorePath,Stringalias,
  41. Stringpassword)throwsException{
  42. KeyStoreks=getKeyStore(keyStorePath,password);
  43. PrivateKeykey=(PrivateKey)ks.getKey(alias,password.toCharArray());
  44. returnkey;
  45. }
  46. /**
  47. *由Certificate获得公钥
  48. *
  49. *@paramcertificatePath
  50. *@return
  51. *@throwsException
  52. */
  53. privatestaticPublicKeygetPublicKey(StringcertificatePath)
  54. throwsException{
  55. Certificatecertificate=getCertificate(certificatePath);
  56. PublicKeykey=certificate.getPublicKey();
  57. returnkey;
  58. }
  59. /**
  60. *获得Certificate
  61. *
  62. *@paramcertificatePath
  63. *@return
  64. *@throwsException
  65. */
  66. privatestaticCertificategetCertificate(StringcertificatePath)
  67. throwsException{
  68. CertificateFactorycertificateFactory=CertificateFactory
  69. .getInstance(X509);
  70. FileInputStreamin=newFileInputStream(certificatePath);
  71. Certificatecertificate=certificateFactory.generateCertificate(in);
  72. in.close();
  73. returncertificate;
  74. }
  75. /**
  76. *获得Certificate
  77. *
  78. *@paramkeyStorePath
  79. *@paramalias
  80. *@parampassword
  81. *@return
  82. *@throwsException
  83. */
  84. privatestaticCertificategetCertificate(StringkeyStorePath,
  85. Stringalias,Stringpassword)throwsException{
  86. KeyStoreks=getKeyStore(keyStorePath,password);
  87. Certificatecertificate=ks.getCertificate(alias);
  88. returncertificate;
  89. }
  90. /**
  91. *获得KeyStore
  92. *
  93. *@paramkeyStorePath
  94. *@parampassword
  95. *@return
  96. *@throwsException
  97. */
  98. privatestaticKeyStoregetKeyStore(StringkeyStorePath,Stringpassword)
  99. throwsException{
  100. FileInputStreamis=newFileInputStream(keyStorePath);
  101. KeyStoreks=KeyStore.getInstance(KEY_STORE);
  102. ks.load(is,password.toCharArray());
  103. is.close();
  104. returnks;
  105. }
  106. /**
  107. *私钥加密
  108. *
  109. *@paramdata
  110. *@paramkeyStorePath
  111. *@paramalias
  112. *@parampassword
  113. *@return
  114. *@throwsException
  115. */
  116. publicstaticbyte[]encryptByPrivateKey(byte[]data,StringkeyStorePath,
  117. Stringalias,Stringpassword)throwsException{
  118. //取得私钥
  119. PrivateKeyprivateKey=getPrivateKey(keyStorePath,alias,password);
  120. //对数据加密
  121. Ciphercipher=Cipher.getInstance(privateKey.getAlgorithm());
  122. cipher.init(Cipher.ENCRYPT_MODE,privateKey);
  123. returncipher.doFinal(data);
  124. }
  125. /**
  126. *私钥解密
  127. *
  128. *@paramdata
  129. *@paramkeyStorePath
  130. *@paramalias
  131. *@parampassword
  132. *@return
  133. *@throwsException
  134. */
  135. publicstaticbyte[]decryptByPrivateKey(byte[]data,StringkeyStorePath,
  136. Stringalias,Stringpassword)throwsException{
  137. //取得私钥
  138. PrivateKeyprivateKey=getPrivateKey(keyStorePath,alias,password);
  139. //对数据加密
  140. Ciphercipher=Cipher.getInstance(privateKey.getAlgorithm());
  141. cipher.init(Cipher.DECRYPT_MODE,privateKey);
  142. returncipher.doFinal(data);
  143. }
  144. /**
  145. *公钥加密
  146. *
  147. *@paramdata
  148. *@paramcertificatePath
  149. *@return
  150. *@throwsException
  151. */
  152. publicstaticbyte[]encryptByPublicKey(byte[]data,StringcertificatePath)
  153. throwsException{
  154. //取得公钥
  155. PublicKeypublicKey=getPublicKey(certificatePath);
  156. //对数据加密
  157. Ciphercipher=Cipher.getInstance(publicKey.getAlgorithm());
  158. cipher.init(Cipher.ENCRYPT_MODE,publicKey);
  159. returncipher.doFinal(data);
  160. }
  161. /**
  162. *公钥解密
  163. *
  164. *@paramdata
  165. *@paramcertificatePath
  166. *@return
  167. *@throwsException
  168. */
  169. publicstaticbyte[]decryptByPublicKey(byte[]data,StringcertificatePath)
  170. throwsException{
  171. //取得公钥
  172. PublicKeypublicKey=getPublicKey(certificatePath);
  173. //对数据加密
  174. Ciphercipher=Cipher.getInstance(publicKey.getAlgorithm());
  175. cipher.init(Cipher.DECRYPT_MODE,publicKey);
  176. returncipher.doFinal(data);
  177. }
  178. /**
  179. *验证Certificate
  180. *
  181. *@paramcertificatePath
  182. *@return
  183. */
  184. publicstaticbooleanverifyCertificate(StringcertificatePath){
  185. returnverifyCertificate(newDate(),certificatePath);
  186. }
  187. /**
  188. *验证Certificate是否过期或无效
  189. *
  190. *@paramdate
  191. *@paramcertificatePath
  192. *@return
  193. */
  194. publicstaticbooleanverifyCertificate(Datedate,StringcertificatePath){
  195. booleanstatus=true;
  196. try{
  197. //取得证书
  198. Certificatecertificate=getCertificate(certificatePath);
  199. //验证证书是否过期或无效
  200. status=verifyCertificate(date,certificate);
  201. }catch(Exceptione){
  202. status=false;
  203. }
  204. returnstatus;
  205. }
  206. /**
  207. *验证证书是否过期或无效
  208. *
  209. *@paramdate
  210. *@paramcertificate
  211. *@return
  212. */
  213. privatestaticbooleanverifyCertificate(Datedate,Certificatecertificate){
  214. booleanstatus=true;
  215. try{
  216. X509Certificatex509Certificate=(X509Certificate)certificate;
  217. x509Certificate.checkValidity(date);
  218. }catch(Exceptione){
  219. status=false;
  220. }
  221. returnstatus;
  222. }
  223. /**
  224. *签名
  225. *
  226. *@paramkeyStorePath
  227. *@paramalias
  228. *@parampassword
  229. *
  230. *@return
  231. *@throwsException
  232. */
  233. publicstaticStringsign(byte[]sign,StringkeyStorePath,Stringalias,
  234. Stringpassword)throwsException{
  235. //获得证书
  236. X509Certificatex509Certificate=(X509Certificate)getCertificate(
  237. keyStorePath,alias,password);
  238. //获取私钥
  239. KeyStoreks=getKeyStore(keyStorePath,password);
  240. //取得私钥
  241. PrivateKeyprivateKey=(PrivateKey)ks.getKey(alias,password
  242. .toCharArray());
  243. //构建签名
  244. Signaturesignature=Signature.getInstance(x509Certificate
  245. .getSigAlgName());
  246. signature.initSign(privateKey);
  247. signature.update(sign);
  248. returnencryptBASE64(signature.sign());
  249. }
  250. /**
  251. *验证签名
  252. *
  253. *@paramdata
  254. *@paramsign
  255. *@paramcertificatePath
  256. *@return
  257. *@throwsException
  258. */
  259. publicstaticbooleanverify(byte[]data,Stringsign,
  260. StringcertificatePath)throwsException{
  261. //获得证书
  262. X509Certificatex509Certificate=(X509Certificate)getCertificate(certificatePath);
  263. //获得公钥
  264. PublicKeypublicKey=x509Certificate.getPublicKey();
  265. //构建签名
  266. Signaturesignature=Signature.getInstance(x509Certificate
  267. .getSigAlgName());
  268. signature.initVerify(publicKey);
  269. signature.update(data);
  270. returnsignature.verify(decryptBASE64(sign));
  271. }
  272. /**
  273. *验证Certificate
  274. *
  275. *@paramkeyStorePath
  276. *@paramalias
  277. *@parampassword
  278. *@return
  279. */
  280. publicstaticbooleanverifyCertificate(Datedate,StringkeyStorePath,
  281. Stringalias,Stringpassword){
  282. booleanstatus=true;
  283. try{
  284. Certificatecertificate=getCertificate(keyStorePath,alias,
  285. password);
  286. status=verifyCertificate(date,certificate);
  287. }catch(Exceptione){
  288. status=false;
  289. }
  290. returnstatus;
  291. }
  292. /**
  293. *验证Certificate
  294. *
  295. *@paramkeyStorePath
  296. *@paramalias
  297. *@parampassword
  298. *@return
  299. */
  300. publicstaticbooleanverifyCertificate(StringkeyStorePath,Stringalias,
  301. Stringpassword){
  302. returnverifyCertificate(newDate(),keyStorePath,alias,password);
  303. }
  304. /**
  305. *获得SSLSocektFactory
  306. *
  307. *@parampassword
  308. *密码
  309. *@paramkeyStorePath
  310. *密钥库路径
  311. *
  312. *@paramtrustKeyStorePath
  313. *信任库路径
  314. *@return
  315. *@throwsException
  316. */
  317. privatestaticSSLSocketFactorygetSSLSocketFactory(Stringpassword,
  318. StringkeyStorePath,StringtrustKeyStorePath)throwsException{
  319. //初始化密钥库
  320. KeyManagerFactorykeyManagerFactory=KeyManagerFactory
  321. .getInstance(SunX509);
  322. KeyStorekeyStore=getKeyStore(keyStorePath,password);
  323. keyManagerFactory.init(keyStore,password.toCharArray());
  324. //初始化信任库
  325. TrustManagerFactorytrustManagerFactory=TrustManagerFactory
  326. .getInstance(SunX509);
  327. KeyStoretrustkeyStore=getKeyStore(trustKeyStorePath,password);
  328. trustManagerFactory.init(trustkeyStore);
  329. //初始化SSL上下文
  330. SSLContextctx=SSLContext.getInstance(SSL);
  331. ctx.init(keyManagerFactory.getKeyManagers(),trustManagerFactory
  332. .getTrustManagers(),null);
  333. SSLSocketFactorysf=ctx.getSocketFactory();
  334. returnsf;
  335. }
  336. /**
  337. *为HttpsURLConnection配置SSLSocketFactory
  338. *
  339. *@paramconn
  340. *HttpsURLConnection
  341. *@parampassword
  342. *密码
  343. *@paramkeyStorePath
  344. *密钥库路径
  345. *
  346. *@paramtrustKeyStorePath
  347. *信任库路径
  348. *@throwsException
  349. */
  350. publicstaticvoidconfigSSLSocketFactory(HttpsURLConnectionconn,
  351. Stringpassword,StringkeyStorePath,StringtrustKeyStorePath)
  352. throwsException{
  353. conn.setSSLSocketFactory(getSSLSocketFactory(password,keyStorePath,
  354. trustKeyStorePath));
  355. }
  356. }
分享到:
评论

你可能感兴趣的:(java,tomcat,.net,算法,Security)