javax.crypto加密

一、制作证书

1.生成keyStroe文件
在命令行下执行以下命令:





Java代码 复制代码 收藏代码
1.keytool -genkey -validity 1 -alias www.tzz-sf.com -keyalg RSA -keystore d:\tzz-sf.keystore 


其中

-genkey    表示生成密钥
-validity     指定证书有效期,这里是1天
-alias         指定别名,这里是www.tzz-sf.com

-keyalg      指定算法,这里是RSA
-keystore   指定存储位置,这里是d:\tzz-sf.keystore

根据命令行提示输入:



Java代码 复制代码 收藏代码
1.输入keystore密码: 
2.Keystore 密码太短 -至少必须为6个字符 
3.输入keystore密码: 
4.再次输入新密码: 
5.您的名字与姓氏是什么? 
6.  [Unknown]:  tzz 
7.您的组织单位名称是什么? 
8.  [Unknown]:  www.tzz-sf.com 
9.您的组织名称是什么? 
10.  [Unknown]:  tzz-sf 
11.您所在的城市或区域名称是什么? 
12.  [Unknown]:  sz 
13.您所在的州或省份名称是什么? 
14.  [Unknown]:  sz 
15.该单位的两字母国家代码是什么 
16.  [Unknown]:  cn 
17.CN=tzz, OU=www.tzz-sf.com, O=tzz-sf, L=sz, ST=sz, C=cn 正确吗? 
18.  [否]:  y 
19.输入<www.tzz-sf.com>的主密码 


在这里我使用的密码为 123456789




2.生成自签名证书
光有keyStore文件是不够的,还需要证书文件,证书才是直接提供给外界使用的公钥凭证。



Java代码 复制代码 收藏代码
1.keytool -export -keystore d:\tzz-sf.keystore -alias www.tzz-sf.com -file d:\tzz-sf.cer -rfc 


其中

-export      指定为导出操作
-keystore  指定keystore文件
-alias        指定导出keystore文件中的别名
-file           指向导出路径
-rfc            以文本格式输出,也就是以BASE64编码输出
这里的密码是 123456789




当然,使用方是需要导入证书的!
可以通过自签名证书完成CAS单点登录系统的构建!




Java代码 复制代码 收藏代码
1.import java.io.IOException; 
2. 
3.import sun.misc.BASE64Decoder; 
4.import sun.misc.BASE64Encoder; 
5. 
6.public class Coder { 
7. 
8.    public static String encryptBASE64(byte[] key) {   
9.        return (new BASE64Encoder()).encodeBuffer(key);   
10.    } 
11.     
12.    public static byte[] decryptBASE64(String key) throws IOException {   
13.        return new BASE64Decoder().decodeBuffer(key); 
14.    } 
15.} 






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


测试:





Java代码 复制代码 收藏代码
1.package cn.tzz.java.crypto.certificate; 
2. 
3.import static org.junit.Assert.*; 
4. 
5.import org.junit.Test; 
6. 
7./**
8. * 测试--Java加密技术——数字证书
9. * 
10. */ 
11.public class CertificateCryptUtilTest { 
12.    private String password = "123456789"; 
13.    private String alias = "www.tzz-sf.com"; 
14.    //生成证书 
15.    //keytool -genkey -validity 1 -alias www.tzz-sf.com -keyalg RSA -keystore d:\tzz-sf.keystore 
16.    //keytool -export -keystore d:\tzz-sf.keystore -alias www.tzz-sf.com -file d:\tzz-sf.cer -rfc 
17.    private String keyStorePath = "d:/tzz-sf.keystore"; 
18.    private String certificatePath = "d:/tzz-sf.cer"; 
19. 
20.    /**公钥加密——私钥解密*/ 
21.    @Test 
22.    public void test() throws Exception { 
23.        String inputStr = "加密字符123456Abc"; 
24.        byte[] data = inputStr.getBytes(); 
25.        byte[] encrypt = CertificateCryptUtil.encryptByPublicKey(data, certificatePath); 
26. 
27.        byte[] decrypt = CertificateCryptUtil.decryptByPrivateKey(encrypt, keyStorePath, alias, password); 
28.        String outputStr = new String(decrypt); 
29.        System.err.println("加密前: " + inputStr + "-----" + "解密后: " + outputStr); 
30.        // 验证数据一致 
31.        assertArrayEquals(data, decrypt); 
32.        // 验证证书有效 
33.        assertTrue(CertificateCryptUtil.verifyCertificate(certificatePath)); 
34.    } 
35. 
36.    /**私钥加密——公钥解密*/ 
37.    @Test 
38.    public void testSign() throws Exception { 
39.        String inputStr = "加密字符123456Abc"; 
40.        byte[] data = inputStr.getBytes(); 
41.        byte[] encodedData = CertificateCryptUtil.encryptByPrivateKey(data, keyStorePath, alias, password); 
42. 
43.        byte[] decodedData = CertificateCryptUtil.decryptByPublicKey(encodedData, certificatePath); 
44. 
45.        String outputStr = new String(decodedData); 
46.        System.err.println("加密前: " + inputStr + "----" + "解密后: " + outputStr); 
47.        assertEquals(inputStr, outputStr); 
48. 
49.        // 产生签名 
50.        String sign = CertificateCryptUtil.sign(encodedData, keyStorePath, alias, password); 
51.        System.err.println("签名:\r" + sign); 
52.        // 验证签名 
53.        boolean status = CertificateCryptUtil.verify(encodedData, sign, certificatePath); 
54.        System.err.println("状态:\r" + status); 
55.        assertTrue(status); 
56. 
57.    } 
58.} 

猜你喜欢

转载自weitao1026.iteye.com/blog/2266315