1 package com.ice.webos.util.security;
2
3 import java.security.Key;
4 import java.security.KeyFactory;
5 import java.security.KeyPair;
6 import java.security.KeyPairGenerator;
7 import java.security.PublicKey;
8 import java.security.spec.PKCS8EncodedKeySpec;
9 import java.security.spec.X509EncodedKeySpec;
10 import java.util.HashMap;
11 import java.util.Map;
12
13 import javax.crypto.Cipher;
14 import javax.crypto.KeyAgreement;
15 import javax.crypto.SecretKey;
16 import javax.crypto.interfaces.DHPrivateKey;
17 import javax.crypto.interfaces.DHPublicKey;
18 import javax.crypto.spec.DHParameterSpec;
19
20 /**
21 * DH Diffie-Hellman算法(D-H算法),密鑰一致協議。<br>
22 * 是由公開密鑰密碼體制的奠基人Diffie和Hellman所提出的一種思想。<br>
23 * 簡單的說就是允許兩名用戶在公開媒體上交換信息以生成"一致"的、可以共享的密鑰。<br>
24 * 換句話說,就是由甲方產出一對密鑰(公鑰、私鑰),乙方依照甲方公鑰產生乙方密鑰對(公鑰、私鑰)。<br>
25 * 以此為基線,作為數據傳輸保密基礎,同時雙方使用同一種對稱加密算法構建本地密鑰(SecretKey)對數據加密。<br>
26 * 這樣,在互通了本地密鑰(SecretKey)算法后,甲乙雙方公開自己的公鑰,使用對方的公鑰和剛才產生的私鑰加密數據,同時可以使用對方的公鑰和自己的私鑰對數據解密。<br>
27 * 不單單是甲乙雙方兩方,可以擴展為多方共享數據通訊,這樣就完成了網絡交互數據的安全通訊!該算法源於中國的同余定理——中國餘數定理。
28 * <ul>
29 * <li>甲方構建密鑰對兒,將公鑰公布給乙方,將私鑰保留;雙方約定數據加密算法;乙方通過甲方公鑰構建密鑰對兒,將公鑰公布給甲方,將私鑰保留。</li>
30 * <li>甲方使用私鑰、乙方公鑰、約定數據加密算法構建本地密鑰,然后通過本地密鑰加密數據,發送給乙方加密后的數據;乙方使用私鑰、甲方公鑰、約定數據加密算法構建本地密鑰,然后通過本地密鑰對數據解密。</li>
31 * <li>乙方使用私鑰、甲方公鑰、約定數據加密算法構建本地密鑰,然后通過本地密鑰加密數據,發送給甲方加密后的數據;甲方使用私鑰、乙方公鑰、約定數據加密算法構建本地密鑰,然后通過本地密鑰對數據解密。</li>
32 * </ul>
33 *
34 * @author Ice_Liu
35 *
36 */
37 public class DHCryptUtil {
38 public static final String ALGORITHM = "DH";
39
40 /**
41 * 默認密鑰字節數
42 *
43 * <pre>
44 *
45 * DH
46 * Default Keysize 1024
47 * Keysize must be a multiple of 64, ranging from 512 to 1024 (inclusive).
48 * </pre>
49 */
50 private static final int KEY_SIZE = 1024;
51
52 /**
53 * DH 加密下需要一種對稱加密算法對數據加密,這里我們使用DES,也可以使用其他對稱加密算法。
54 */
55 public static final String SECRET_ALGORITHM = "DES";
56 private static final String PUBLIC_KEY = "DHPublicKey";
57 private static final String PRIVATE_KEY = "DHPrivateKey";
58
59 /**
60 * 初始化甲方密鑰
61 *
62 * @return
63 * @throws Exception
64 */
65 public static Map<String, Object> initKey() throws Exception {
66 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
67 keyPairGenerator.initialize(KEY_SIZE);
68
69 KeyPair keyPair = keyPairGenerator.generateKeyPair();
70
71 // 甲方公鑰
72 DHPublicKey publicKey = (DHPublicKey) keyPair.getPublic();
73
74 // 甲方私鑰
75 DHPrivateKey privateKey = (DHPrivateKey) keyPair.getPrivate();
76
77 Map<String, Object> keyMap = new HashMap<String, Object>(2);
78
79 keyMap.put(PUBLIC_KEY, publicKey);
80 keyMap.put(PRIVATE_KEY, privateKey);
81 return keyMap;
82 }
83
84 /**
85 * 初始化乙方密鑰
86 *
87 * @param key
88 * 甲方公鑰
89 * @return
90 * @throws Exception
91 */
92 public static Map<String, Object> initKey(String key) throws Exception {
93 // 解析甲方公鑰
94 byte[] keyBytes = CryptUtil.decryptBASE64(key);
95 X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
96 KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
97 PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
98
99 // 由甲方公鑰構建乙方密鑰
100 DHParameterSpec dhParamSpec = ((DHPublicKey) pubKey).getParams();
101
102 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyFactory.getAlgorithm());
103 keyPairGenerator.initialize(dhParamSpec);
104
105 KeyPair keyPair = keyPairGenerator.generateKeyPair();
106
107 // 乙方公鑰
108 DHPublicKey publicKey = (DHPublicKey) keyPair.getPublic();
109
110 // 乙方私鑰
111 DHPrivateKey privateKey = (DHPrivateKey) keyPair.getPrivate();
112
113 Map<String, Object> keyMap = new HashMap<String, Object>(2);
114
115 keyMap.put(PUBLIC_KEY, publicKey);
116 keyMap.put(PRIVATE_KEY, privateKey);
117
118 return keyMap;
119 }
120
121 /**
122 * 加密<br>
123 *
124 * @param data
125 * 待加密數據
126 * @param publicKey
127 * 甲方公鑰
128 * @param privateKey
129 * 乙方私鑰
130 * @return
131 * @throws Exception
132 */
133 public static byte[] encrypt(byte[] data, String publicKey, String privateKey) throws Exception {
134
135 // 生成本地密鑰
136 SecretKey secretKey = getSecretKey(publicKey, privateKey);
137
138 // 數據加密
139 Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
140 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
141
142 return cipher.doFinal(data);
143 }
144
145 /**
146 * 解密<br>
147 *
148 * @param data
149 * 待解密數據
150 * @param publicKey
151 * 乙方公鑰
152 * @param privateKey
153 * 乙方私鑰
154 * @return
155 * @throws Exception
156 */
157 public static byte[] decrypt(byte[] data, String publicKey, String privateKey) throws Exception {
158
159 // 生成本地密鑰
160 SecretKey secretKey = getSecretKey(publicKey, privateKey);
161 // 數據解密
162 Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
163 cipher.init(Cipher.DECRYPT_MODE, secretKey);
164
165 return cipher.doFinal(data);
166 }
167
168 /**
169 * 構建密鑰
170 *
171 * @param publicKey
172 * 公鑰
173 * @param privateKey
174 * 私鑰
175 * @return
176 * @throws Exception
177 */
178 private static SecretKey getSecretKey(String publicKey, String privateKey) throws Exception {
179 // 初始化公鑰
180 byte[] pubKeyBytes = CryptUtil.decryptBASE64(publicKey);
181
182 KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
183 X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKeyBytes);
184 PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
185
186 // 初始化私鑰
187 byte[] priKeyBytes = CryptUtil.decryptBASE64(privateKey);
188
189 PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKeyBytes);
190 Key priKey = keyFactory.generatePrivate(pkcs8KeySpec);
191
192 KeyAgreement keyAgree = KeyAgreement.getInstance(keyFactory.getAlgorithm());
193 keyAgree.init(priKey);
194 keyAgree.doPhase(pubKey, true);
195
196 // 生成本地密鑰
197 SecretKey secretKey = keyAgree.generateSecret(SECRET_ALGORITHM);
198
199 return secretKey;
200 }
201
202 /**
203 * 取得私鑰
204 *
205 * @param keyMap
206 * @return
207 * @throws Exception
208 */
209 public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {
210 Key key = (Key) keyMap.get(PRIVATE_KEY);
211
212 return CryptUtil.encryptBASE64(key.getEncoded());
213 }
214
215 /**
216 * 取得公鑰
217 *
218 * @param keyMap
219 * @return
220 * @throws Exception
221 */
222 public static String getPublicKey(Map<String, Object> keyMap) throws Exception {
223 Key key = (Key) keyMap.get(PUBLIC_KEY);
224
225 return CryptUtil.encryptBASE64(key.getEncoded());
226 }
227
228 public static void main(String[] args) {
229 try {
230 RSACryptUtil.main(args);
231 System.out.println("**************************************");
232 System.out.println("DH加密算法");
233 // 生成甲方密鑰對兒
234 Map<String, Object> aKeyMap = DHCryptUtil.initKey();
235 String aPublicKey = DHCryptUtil.getPublicKey(aKeyMap);
236 String aPrivateKey = DHCryptUtil.getPrivateKey(aKeyMap);
237
238 System.out.println("甲方公鑰:\r" + aPublicKey);
239 System.out.println("甲方私鑰:\r" + aPrivateKey);
240
241 // 由甲方公鑰產生乙方本地密鑰對兒
242 Map<String, Object> bKeyMap = DHCryptUtil.initKey(aPublicKey);
243 String bPublicKey = DHCryptUtil.getPublicKey(bKeyMap);
244 String bPrivateKey = DHCryptUtil.getPrivateKey(bKeyMap);
245
246 System.out.println("乙方公鑰:\r" + bPublicKey);
247 System.out.println("乙方私鑰:\r" + bPrivateKey);
248
249 String aInput = "abc ";
250 System.out.println("原文: " + aInput);
251
252 // 由甲方公鑰,乙方私鑰構建密文
253 byte[] aCode = DHCryptUtil.encrypt(aInput.getBytes(), aPublicKey, bPrivateKey);
254
255 // 由乙方公鑰,甲方私鑰解密
256 byte[] aDecode = DHCryptUtil.decrypt(aCode, bPublicKey, aPrivateKey);
257 String aOutput = (new String(aDecode));
258
259 System.out.println("解密: " + aOutput);
260
261 System.out.println(" ===============反過來加密解密================== ");
262 String bInput = "def ";
263 System.out.println("原文: " + bInput);
264
265 // 由乙方公鑰,甲方私鑰構建密文
266 byte[] bCode = DHCryptUtil.encrypt(bInput.getBytes(), bPublicKey, aPrivateKey);
267
268 // 由甲方公鑰,乙方私鑰解密
269 byte[] bDecode = DHCryptUtil.decrypt(bCode, aPublicKey, bPrivateKey);
270 String bOutput = (new String(bDecode));
271
272 System.out.println("解密: " + bOutput);
273 } catch (Exception e) {
274 // TODO Auto-generated catch block
275 e.printStackTrace();
276 }
277
278 }
279 }