1 packagecom.jetsum.util;2
3 importjava.io.FileInputStream;4 importjava.io.FileNotFoundException;5 importjava.io.IOException;6 importjava.security.InvalidAlgorithmParameterException;7 importjava.security.InvalidKeyException;8 importjava.security.Key;9 importjava.security.KeyFactory;10 importjava.security.KeyPair;11 importjava.security.KeyPairGenerator;12 importjava.security.KeyStore;13 importjava.security.KeyStoreException;14 importjava.security.MessageDigest;15 importjava.security.NoSuchAlgorithmException;16 importjava.security.PrivateKey;17 importjava.security.PublicKey;18 importjava.security.SecureRandom;19 importjava.security.Signature;20 importjava.security.SignatureException;21 importjava.security.UnrecoverableKeyException;22 importjava.security.cert.Certificate;23 importjava.security.cert.CertificateException;24 importjava.security.cert.CertificateFactory;25 importjava.security.cert.X509Certificate;26 importjava.security.interfaces.RSAPrivateKey;27 importjava.security.interfaces.RSAPublicKey;28 importjava.security.spec.AlgorithmParameterSpec;29 importjava.security.spec.InvalidKeySpecException;30 importjava.security.spec.PKCS8EncodedKeySpec;31 importjava.security.spec.X509EncodedKeySpec;32 importjava.util.Date;33 importjava.util.HashMap;34 importjava.util.Map;35 importjava.util.Random;36
37 importjavax.crypto.BadPaddingException;38 importjavax.crypto.Cipher;39 importjavax.crypto.IllegalBlockSizeException;40 importjavax.crypto.KeyAgreement;41 importjavax.crypto.KeyGenerator;42 importjavax.crypto.Mac;43 importjavax.crypto.NoSuchPaddingException;44 importjavax.crypto.SecretKey;45 importjavax.crypto.SecretKeyFactory;46 importjavax.crypto.interfaces.DHPrivateKey;47 importjavax.crypto.interfaces.DHPublicKey;48 importjavax.crypto.spec.DHParameterSpec;49 importjavax.crypto.spec.IvParameterSpec;50 importjavax.crypto.spec.PBEKeySpec;51 importjavax.crypto.spec.PBEParameterSpec;52 importjavax.crypto.spec.SecretKeySpec;53
54 public classCipherUtil {55
56 /**
57 * MD5算法58 */
59 private static final String ALGORITHM_MD5 = "MD5";60 /**
61 * SHA算法62 */
63 private static final String ALGORITHM_SHA = "SHA";64 /**
65 * HMAC算法66 */
67 private static final String ALGORITHM_MAC = "HmacMD5";68 /**
69 * DES算法70 */
71 private static final String ALGORITHM_DES = "DES";72 /**
73 * PBE算法74 */
75 private static final String ALGORITHM_PBE = "PBEWITHMD5andDES";76
77 /**
78 * AESkey79 */
80 private static final String KEY_AES = "AES";81
82 /**
83 * AES算法84 */
85 private static final String ALGORITHM_AES = "AES/CBC/PKCS5Padding";86
87 /**
88 * RSA算法89 */
90 private static final String KEY_ALGORITHM = "RSA";91
92 /**
93 * 数字签名94 */
95 private static final String SIGNATURE_ALGORITHM = "MD5withRSA";96
97 /**
98 * 公钥99 */
100 private static final String RSAPUBLIC_KEY = "RSAPublicKey";101
102 /**
103 * 私钥104 */
105 private static final String RSAPRIVATE_KEY = "RSAPrivateKey";106
107 /**
108 * D-H算法109 */
110 private static final String ALGORITHM_DH = "DH";111
112 /**
113 * 默认密钥字节数114 *115 *
116 * DH117 * Default Keysize 1024118 * Keysize must be a multiple of 64, ranging from 512 to 1024 (inclusive).119 *120 */
121 private static final int DH_KEY_SIZE = 1024;122
123 /**
124 * DH加密下需要一种对称加密算法对数据加密,这里我们使用DES,也可以使用其他对称加密算法。125 */
126 private static final String SECRET_ALGORITHM = "DES";127
128 /**
129 * DH公钥130 */
131 private static final String DHPUBLIC_KEY = "DHPublicKey";132
133 /**
134 * DH私钥135 */
136 private static final String DHPRIVATE_KEY = "DHPrivateKey";137
138 /**
139 * Java密钥库(Java Key Store,JKS)KEY_STORE140 */
141 private static final String KEY_STORE = "JKS";142
143 private static final String X509 = "X.509";144
145 /**
146 * 信息摘要算法147 *@paramalgorithm 算法类型148 *@paramdata 要加密的字符串149 *@return返回加密后的摘要信息150 */
151 private staticString encryptEncode(String algorithm, String data) {152 try{153 MessageDigest md =MessageDigest.getInstance(algorithm);154 returnTranscodeUtil.byteArrayToHexStr(md.digest(data.getBytes()));155 } catch(NoSuchAlgorithmException ex) {156 ex.printStackTrace();157 }158 return null;159 }160
161 /**
162 * 使用MD5加密163 *@paramdata 要加密的字符串164 *@return返回加密后的信息165 */
166 public staticString MD5Encode(String data) {167 returnencryptEncode(ALGORITHM_MD5, data);168 }169
170 /**
171 * 使用SHA加密172 *@paramdata 要加密的字符串173 *@return返回加密后的信息174 */
175 public staticString SHAEncode(String data) {176 returnencryptEncode(ALGORITHM_SHA, data);177 }178
179 /**
180 * 生成HMAC密钥181 *@return返回密钥信息182 */
183 public staticString generateMACKey() {184 try{185 KeyGenerator keyGenerator =KeyGenerator.getInstance(ALGORITHM_MAC);186 SecretKey secretKey =keyGenerator.generateKey();187 returnTranscodeUtil.byteArrayToBase64Str(secretKey.getEncoded());188 } catch(NoSuchAlgorithmException e) {189 e.printStackTrace();190 }191 return null;192 }193
194 /**
195 * 使用HMAC加密196 *@paramdata 要加密的字符串197 *@paramkey 密钥198 *@return返回加密后的信息199 */
200 public staticString HMACEncode(String data, String key) {201 Key k =toKey(key,ALGORITHM_MAC);202 try{203 Mac mac =Mac.getInstance(k.getAlgorithm());204 mac.init(k);205 returnTranscodeUtil.byteArrayToBase64Str(mac.doFinal(data.getBytes()));206 } catch(NoSuchAlgorithmException e) {207 e.printStackTrace();208 } catch(InvalidKeyException e) {209 e.printStackTrace();210 }211 return null;212 }213
214 /**
215 * 将base64编码后的密钥字符串转换成密钥对象216 *@paramkey 密钥字符串217 *@paramalgorithm 加密算法218 *@return返回密钥对象219 */
220 private staticKey toKey(String key,String algorithm) {221 SecretKey secretKey = newSecretKeySpec(TranscodeUtil.base64StrToByteArray(key), algorithm);222 returnsecretKey;223 }224
225 /**
226 * 生成DES密钥227 *@paramseed 密钥种子228 *@return返回base64编码的密钥字符串229 */
230 public staticString generateDESKey(String seed) {231 try{232 KeyGenerator kg =KeyGenerator.getInstance(ALGORITHM_DES);233 kg.init(newSecureRandom(seed.getBytes()));234 SecretKey secretKey =kg.generateKey();235 returnTranscodeUtil.byteArrayToBase64Str(secretKey.getEncoded());236 } catch(NoSuchAlgorithmException e) {237 e.printStackTrace();238 }239 return null;240 }241
242 /**
243 * DES加密244 *@paramdata 要加密的数据245 *@paramkey 密钥246 *@return返回加密后的数据(经过base64编码)247 */
248 public staticString DESEncrypt(String data,String key) {249 returnDESCipher(data,key,Cipher.ENCRYPT_MODE);250 }251
252 /**
253 * DES解密254 *@paramdata 要解密的数据255 *@paramkey 密钥256 *@return返回解密后的数据257 */
258 public staticString DESDecrypt(String data, String key) {259 returnDESCipher(data,key,Cipher.DECRYPT_MODE);260 }261
262 /**
263 * DES的加密解密264 *@paramdata 要加密或解密的数据265 *@paramkey 密钥266 *@parammode 加密或解密模式267 *@return返回加密或解密的数据268 */
269 private static String DESCipher(String data, String key, intmode) {270 try{271 Key k =toKey(key,ALGORITHM_DES);272 Cipher cipher =Cipher.getInstance(ALGORITHM_DES);273 cipher.init(mode, k);274 return mode == Cipher.DECRYPT_MODE?newString(cipher.doFinal(TranscodeUtil.base64StrToByteArray(data))):TranscodeUtil.byteArrayToBase64Str(cipher.doFinal(data.getBytes()));275 } catch(Exception e) {276 e.printStackTrace();277 }278 return null;279 }280
281 /**
282 * 生成盐283 *@return返回base64编码后的盐信息284 */
285 public staticString generatePBESalt() {286 byte[] salt = new byte[8];287 Random random = newRandom();288 random.nextBytes(salt);289 returnTranscodeUtil.byteArrayToBase64Str(salt);290 }291
292 /**
293 * PBE(Password-based encryption基于密码加密)加密294 *@paramdata 要加密的数据295 *@parampassword 密码296 *@paramsalt 盐297 *@return返回加密后的数据(经过base64编码)298 */
299 public staticString PBEEncrypt(String data,String password,String salt) {300 returnPBECipher( data, password, salt, Cipher.ENCRYPT_MODE);301 }302
303 /**
304 * PBE(Password-based encryption基于密码加密)解密305 *@paramdata 要解密的数据306 *@parampassword 密码307 *@paramsalt 盐308 *@return返回解密后的数据309 */
310 public staticString PBEDecrypt(String data,String password,String salt) {311 returnPBECipher( data, password, salt, Cipher.DECRYPT_MODE);312 }313
314 /**
315 * PBE加密解密316 *@paramdata 要加密解密的信息317 *@parampassword 密码318 *@paramsalt 盐319 *@parammode 加密或解密模式320 *@return返回加密解密后的数据321 */
322 private static String PBECipher(String data,String password,String salt,intmode) {323 try{324 Key secretKey =toPBEKey(password);325 PBEParameterSpec paramSpec = new PBEParameterSpec(TranscodeUtil.base64StrToByteArray(salt), 100);326 Cipher cipher =Cipher.getInstance(ALGORITHM_PBE);327 cipher.init(mode, secretKey, paramSpec);328 return mode == Cipher.DECRYPT_MODE?newString(cipher.doFinal(TranscodeUtil.base64StrToByteArray(data))):TranscodeUtil.byteArrayToBase64Str(cipher.doFinal(data.getBytes()));329 } catch(NoSuchAlgorithmException e) {330 e.printStackTrace();331 } catch(NoSuchPaddingException e) {332 e.printStackTrace();333 } catch(InvalidKeyException e) {334 e.printStackTrace();335 } catch(InvalidAlgorithmParameterException e) {336 e.printStackTrace();337 } catch(IllegalBlockSizeException e) {338 e.printStackTrace();339 } catch(BadPaddingException e) {340 e.printStackTrace();341 }342 return null;343 }344
345 /**
346 * 生成PBEkey347 *@parampassword 使用的密码348 *@return返回生成的PBEkey349 */
350 private staticKey toPBEKey(String password) {351 PBEKeySpec keySpec = newPBEKeySpec(password.toCharArray());352 try{353 SecretKeyFactory keyFactory =SecretKeyFactory.getInstance(ALGORITHM_PBE);354 SecretKey secretKey =keyFactory.generateSecret(keySpec);355 returnsecretKey;356 } catch(NoSuchAlgorithmException e) {357 e.printStackTrace();358 } catch(InvalidKeySpecException e) {359 e.printStackTrace();360 }361 return null;362 }363
364 /**
365 * 生成AESkey366 *@paramkeySize key的位数367 *@paramseed 随机种子368 *@return返回base64编码后的key信息369 */
370 public static String generateAESKey(intkeySize,String seed) {371 try{372 KeyGenerator kgen =KeyGenerator.getInstance(KEY_AES);373 kgen.init(keySize,newSecureRandom(seed.getBytes()));374 SecretKey key =kgen.generateKey();375 returnTranscodeUtil.byteArrayToBase64Str(key.getEncoded());376 } catch(NoSuchAlgorithmException e) {377 e.printStackTrace();378 }379 return null;380 }381
382 /**
383 * AES加密384 *@paramdata 要加密的数据385 *@paramkey 密钥386 *@paramalgorithmParameter 算法参数387 *@return返回加密数据388 */
389 public staticString AESEncrypt(String data,String key,String algorithmParameter) {390 returnAESCipher(data, key, algorithmParameter,Cipher.ENCRYPT_MODE);391 }392
393 /**
394 * AES解密395 *@paramdata 要解密的数据396 *@paramkey 密钥397 *@paramalgorithmParameter 算法参数398 *@return返回解密数据399 */
400 public staticString AESDecrypt(String data,String key,String algorithmParameter) {401 returnAESCipher(data, key, algorithmParameter,Cipher.DECRYPT_MODE);402 }403
404 /**
405 * 实现AES加密解密406 *@paramdata 要加密或解密的数据407 *@paramkey 密钥408 *@paramalgorithmParameter 算法参数409 *@parammode 加密或解密410 *@return返回加密或解密的数据411 */
412 private static String AESCipher(String data, String key, String algorithmParameter,intmode) {413 try{414 Key k =toKey(key,KEY_AES);415 AlgorithmParameterSpec paramSpec = newIvParameterSpec(algorithmParameter.getBytes());416 Cipher ecipher =Cipher.getInstance(ALGORITHM_AES);417 ecipher.init(mode, k, paramSpec);418 return mode==Cipher.DECRYPT_MODE?newString(ecipher.doFinal(TranscodeUtil.base64StrToByteArray(data))):TranscodeUtil.byteArrayToBase64Str(ecipher.doFinal(data.getBytes()));419 } catch(NoSuchAlgorithmException e) {420 e.printStackTrace();421 } catch(NoSuchPaddingException e) {422 e.printStackTrace();423 } catch(InvalidKeyException e) {424 e.printStackTrace();425 } catch(InvalidAlgorithmParameterException e) {426 e.printStackTrace();427 } catch(IllegalBlockSizeException e) {428 e.printStackTrace();429 } catch(BadPaddingException e) {430 e.printStackTrace();431 }432 return null;433 }434
435 /**
436 * 数字签名437 *@paramdata 要签名的密文438 *@paramprivateKey 私钥439 *@return返回签名信息440 */
441 public staticString RSASign(String data, String privateKey) {442 try{443 //解密由base64编码的私钥
444 byte[] keyBytes =TranscodeUtil.base64StrToByteArray(privateKey);445 //构造PKCS8EncodedKeySpec对象
446 PKCS8EncodedKeySpec pkcs8KeySpec = newPKCS8EncodedKeySpec(keyBytes);447 //KEY_ALGORITHM 指定的加密算法
448 KeyFactory keyFactory =KeyFactory.getInstance(KEY_ALGORITHM);449 //取私钥匙对象
450 PrivateKey priKey =keyFactory.generatePrivate(pkcs8KeySpec);451 //用私钥对信息生成数字签名
452 Signature signature =Signature.getInstance(SIGNATURE_ALGORITHM);453 signature.initSign(priKey);454 signature.update(TranscodeUtil.base64StrToByteArray(data));455 returnTranscodeUtil.byteArrayToBase64Str(signature.sign());456 } catch(NoSuchAlgorithmException e) {457 e.printStackTrace();458 } catch(InvalidKeySpecException e) {459 e.printStackTrace();460 } catch(InvalidKeyException e) {461 e.printStackTrace();462 } catch(SignatureException e) {463 e.printStackTrace();464 }465 return null;466 }467
468 /**
469 * 验证签名470 *@paramdata 要验证的密文471 *@parampublicKey 公钥472 *@paramsign 签名信息473 *@return返回验证成功状态474 */
475 public static booleanRSAVerify(String data, String publicKey, String sign) {476 try{477 //解密由base64编码的公钥
478 byte[] keyBytes =TranscodeUtil.base64StrToByteArray(publicKey);479 //构造X509EncodedKeySpec对象
480 X509EncodedKeySpec keySpec = newX509EncodedKeySpec(keyBytes);481 //KEY_ALGORITHM 指定的加密算法
482 Signature signature;483 KeyFactory keyFactory =KeyFactory.getInstance(KEY_ALGORITHM);484 //取公钥匙对象
485 PublicKey pubKey =keyFactory.generatePublic(keySpec);486 signature =Signature.getInstance(SIGNATURE_ALGORITHM);487 signature.initVerify(pubKey);488 signature.update(TranscodeUtil.base64StrToByteArray(data));489 //验证签名是否正常
490 returnsignature.verify(TranscodeUtil.base64StrToByteArray(sign));491 } catch(NoSuchAlgorithmException e) {492 e.printStackTrace();493 } catch(InvalidKeySpecException e) {494 e.printStackTrace();495 } catch(InvalidKeyException e) {496 e.printStackTrace();497 } catch(SignatureException e) {498 e.printStackTrace();499 }500 return false;501 }502
503 /**
504 * 私钥解密505 *@paramdata 要解密的字符串506 *@paramkey 私钥507 *@return返回解密后的字符串508 */
509 public staticString RSADecryptByPrivateKey(String data, String key) {510 try{511 //对密钥解密
512 byte[] keyBytes =TranscodeUtil.base64StrToByteArray(key);513 //取得私钥
514 PKCS8EncodedKeySpec pkcs8KeySpec = newPKCS8EncodedKeySpec(keyBytes);515 KeyFactory keyFactory =KeyFactory.getInstance(KEY_ALGORITHM);516 Key privateKey =keyFactory.generatePrivate(pkcs8KeySpec);517 //对数据解密
518 Cipher cipher =Cipher.getInstance(keyFactory.getAlgorithm());519 cipher.init(Cipher.DECRYPT_MODE, privateKey);520 return newString(cipher.doFinal(TranscodeUtil.base64StrToByteArray(data)));521 } catch(NoSuchAlgorithmException e) {522 e.printStackTrace();523 } catch(InvalidKeySpecException e) {524 e.printStackTrace();525 } catch(NoSuchPaddingException e) {526 e.printStackTrace();527 } catch(InvalidKeyException e) {528 e.printStackTrace();529 } catch(IllegalBlockSizeException e) {530 e.printStackTrace();531 } catch(BadPaddingException e) {532 e.printStackTrace();533 }534 return null;535 }536
537 /**
538 * 公钥解密539 *@paramdata 要解密的数据540 *@paramkey 公钥541 *@return返回解密后的数据542 */
543 public staticString RSADecryptByPublicKey(String data, String key) {544 try{545 //对密钥解密
546 byte[] keyBytes =TranscodeUtil.base64StrToByteArray(key);547 //取得公钥
548 X509EncodedKeySpec x509KeySpec = newX509EncodedKeySpec(keyBytes);549 KeyFactory keyFactory =KeyFactory.getInstance(KEY_ALGORITHM);550 Key publicKey =keyFactory.generatePublic(x509KeySpec);551 //对数据解密
552 Cipher cipher =Cipher.getInstance(keyFactory.getAlgorithm());553 cipher.init(Cipher.DECRYPT_MODE, publicKey);554 return newString(cipher.doFinal(TranscodeUtil.base64StrToByteArray(data)));555 } catch(NoSuchAlgorithmException e) {556 e.printStackTrace();557 } catch(IllegalBlockSizeException e) {558 e.printStackTrace();559 } catch(BadPaddingException e) {560 e.printStackTrace();561 } catch(InvalidKeySpecException e) {562 e.printStackTrace();563 } catch(InvalidKeyException e) {564 e.printStackTrace();565 } catch(NoSuchPaddingException e) {566 e.printStackTrace();567 }568 return null;569 }570
571 /**
572 * 公钥加密573 *@paramdata 要加密的数据574 *@paramkey 公钥575 *@return返回加密的数据576 */
577 public staticString RSAEncryptByPublicKey(String data, String key) {578 try{579 //对公钥解密
580 byte[] keyBytes =TranscodeUtil.base64StrToByteArray(key);581 //取得公钥
582 X509EncodedKeySpec x509KeySpec = newX509EncodedKeySpec(keyBytes);583 KeyFactory keyFactory =KeyFactory.getInstance(KEY_ALGORITHM);584 Key publicKey =keyFactory.generatePublic(x509KeySpec);585 //对数据加密
586 Cipher cipher =Cipher.getInstance(keyFactory.getAlgorithm());587 cipher.init(Cipher.ENCRYPT_MODE, publicKey);588 returnTranscodeUtil.byteArrayToBase64Str(cipher.doFinal(data.getBytes()));589 } catch(NoSuchAlgorithmException e) {590 e.printStackTrace();591 } catch(InvalidKeySpecException e) {592 e.printStackTrace();593 } catch(NoSuchPaddingException e) {594 e.printStackTrace();595 } catch(InvalidKeyException e) {596 e.printStackTrace();597 } catch(IllegalBlockSizeException e) {598 e.printStackTrace();599 } catch(BadPaddingException e) {600 e.printStackTrace();601 }602 return null;603 }604
605 /**
606 * 私钥加密607 *@paramdata 要加密的数据608 *@paramkey 私钥609 *@return返回加密后的数据610 */
611 public staticString RSAEncryptByPrivateKey(String data, String key) {612 try{613 //对密钥解密
614 byte[] keyBytes =TranscodeUtil.base64StrToByteArray(key);615 //取得私钥
616 PKCS8EncodedKeySpec pkcs8KeySpec = newPKCS8EncodedKeySpec(keyBytes);617 KeyFactory keyFactory =KeyFactory.getInstance(KEY_ALGORITHM);618 Key privateKey =keyFactory.generatePrivate(pkcs8KeySpec);619 //对数据加密
620 Cipher cipher =Cipher.getInstance(keyFactory.getAlgorithm());621 cipher.init(Cipher.ENCRYPT_MODE, privateKey);622 returnTranscodeUtil.byteArrayToBase64Str(cipher.doFinal(data.getBytes()));623 } catch(NoSuchAlgorithmException e) {624 e.printStackTrace();625 } catch(InvalidKeyException e) {626 e.printStackTrace();627 } catch(InvalidKeySpecException e) {628 e.printStackTrace();629 } catch(NoSuchPaddingException e) {630 e.printStackTrace();631 } catch(IllegalBlockSizeException e) {632 e.printStackTrace();633 } catch(BadPaddingException e) {634 e.printStackTrace();635 }636 return null;637 }638
639 /**
640 * 获得私钥641 *@paramkeyMap 密钥对642 *@return返回经过base64编码的私钥643 */
644 public static String getRSAPrivateKey(MapkeyMap) {645 Key key =(Key) keyMap.get(RSAPRIVATE_KEY);646 returnTranscodeUtil.byteArrayToBase64Str(key.getEncoded());647 }648
649 /**
650 * 获得公钥(base64编码)651 *@paramkeyMap 密钥对652 *@return返回经过base64编码的公钥653 */
654 public static String getRSAPublicKey(MapkeyMap) {655 Key key =(Key) keyMap.get(RSAPUBLIC_KEY);656 returnTranscodeUtil.byteArrayToBase64Str(key.getEncoded());657 }658
659 /**
660 * 初始化密钥对661 *@return返回密钥对662 */
663 public static MapinitRSAKey() {664 Map keyMap = new HashMap(2);665 try{666 KeyPairGenerator keyPairGen =KeyPairGenerator667 .getInstance(KEY_ALGORITHM);668 keyPairGen.initialize(1024);669 KeyPair keyPair =keyPairGen.generateKeyPair();670 //公钥
671 RSAPublicKey publicKey =(RSAPublicKey) keyPair.getPublic();672 //私钥
673 RSAPrivateKey privateKey =(RSAPrivateKey) keyPair.getPrivate();674 keyMap.put(RSAPUBLIC_KEY, publicKey);675 keyMap.put(RSAPRIVATE_KEY, privateKey);676 } catch(NoSuchAlgorithmException e) {677 e.printStackTrace();678 }679 returnkeyMap;680 }681
682 /**
683 * 初始化甲方密钥对684 *@return返回甲方密钥对685 */
686 public static MapinitDHKey() {687 try{688 KeyPairGenerator keyPairGenerator =KeyPairGenerator.getInstance(ALGORITHM_DH);689 keyPairGenerator.initialize(DH_KEY_SIZE);690 KeyPair keyPair =keyPairGenerator.generateKeyPair();691 //甲方公钥
692 DHPublicKey publicKey =(DHPublicKey) keyPair.getPublic();693 //甲方私钥
694 DHPrivateKey privateKey =(DHPrivateKey) keyPair.getPrivate();695 Map keyMap = new HashMap(2);696 keyMap.put(DHPUBLIC_KEY, publicKey);697 keyMap.put(DHPRIVATE_KEY, privateKey);698 returnkeyMap;699 } catch(NoSuchAlgorithmException e) {700 e.printStackTrace();701 }702 return null;703 }704
705 /**
706 * 使用甲方公钥初始化乙方密钥对707 *@paramkey 甲方公钥708 *@return返回乙方密钥对709 */
710 public static MapinitDHKey(String key) {711 try{712 //解析甲方公钥
713 byte[] keyBytes =TranscodeUtil.base64StrToByteArray(key);714 X509EncodedKeySpec x509KeySpec = newX509EncodedKeySpec(keyBytes);715 KeyFactory keyFactory =KeyFactory.getInstance(ALGORITHM_DH);716 PublicKey pubKey =keyFactory.generatePublic(x509KeySpec);717 //由甲方公钥构建乙方密钥
718 DHParameterSpec dhParamSpec =((DHPublicKey) pubKey).getParams();719 KeyPairGenerator keyPairGenerator =KeyPairGenerator.getInstance(keyFactory.getAlgorithm());720 keyPairGenerator.initialize(dhParamSpec);721 KeyPair keyPair =keyPairGenerator.generateKeyPair();722 //乙方公钥
723 DHPublicKey publicKey =(DHPublicKey) keyPair.getPublic();724 //乙方私钥
725 DHPrivateKey privateKey =(DHPrivateKey) keyPair.getPrivate();726 Map keyMap = new HashMap(2);727 keyMap.put(DHPUBLIC_KEY, publicKey);728 keyMap.put(DHPRIVATE_KEY, privateKey);729 returnkeyMap;730 } catch(NoSuchAlgorithmException e) {731 e.printStackTrace();732 } catch(InvalidKeySpecException e) {733 e.printStackTrace();734 } catch(InvalidAlgorithmParameterException e) {735 e.printStackTrace();736 }737 return null;738 }739
740 /**
741 * DH加密742 *@paramdata 要加密的数据743 *@parampublicKey 甲方或乙方公钥744 *@paramprivateKey 甲方或乙方私钥745 *@return加密结果746 */
747 public staticString DHEncrypt(String data, String publicKey,String privateKey) {748 try{749 //生成本地密钥
750 SecretKey secretKey =getDHSecretKey(publicKey, privateKey);751 //数据加密
752 Cipher cipher =Cipher.getInstance(secretKey.getAlgorithm());753 cipher.init(Cipher.ENCRYPT_MODE, secretKey);754 returnTranscodeUtil.byteArrayToBase64Str(cipher.doFinal(data.getBytes()));755 } catch(NoSuchAlgorithmException e) {756 e.printStackTrace();757 } catch(NoSuchPaddingException e) {758 e.printStackTrace();759 } catch(InvalidKeyException e) {760 e.printStackTrace();761 } catch(IllegalBlockSizeException e) {762 e.printStackTrace();763 } catch(BadPaddingException e) {764 e.printStackTrace();765 }766 return null;767 }768
769 /**
770 * DH解密771 *@paramdata 要解密的数据772 *@parampublicKey 公钥773 *@paramprivateKey 私钥774 *@return返回解密结果775 */
776 public staticString DHDecrypt(String data, String publicKey,String privateKey) {777 try{778 //生成本地密钥
779 SecretKey secretKey =getDHSecretKey(publicKey, privateKey);780 //数据解密
781 Cipher cipher =Cipher.getInstance(secretKey.getAlgorithm());782 cipher.init(Cipher.DECRYPT_MODE, secretKey);783 return newString(cipher.doFinal(TranscodeUtil.base64StrToByteArray(data)));784 } catch(NoSuchAlgorithmException e) {785 e.printStackTrace();786 } catch(NoSuchPaddingException e) {787 e.printStackTrace();788 } catch(InvalidKeyException e) {789 e.printStackTrace();790 } catch(IllegalBlockSizeException e) {791 e.printStackTrace();792 } catch(BadPaddingException e) {793 e.printStackTrace();794 }795 return null;796 }797
798 /**
799 * 生成本地密钥800 *@parampublicKey 公钥801 *@paramprivateKey 私钥802 *@return返回本地密钥803 */
804 private staticSecretKey getDHSecretKey(String publicKey, String privateKey) {805 try{806 //初始化公钥
807 byte[] pubKeyBytes =TranscodeUtil.base64StrToByteArray(publicKey);808 KeyFactory keyFactory =KeyFactory.getInstance(ALGORITHM_DH);809 X509EncodedKeySpec x509KeySpec = newX509EncodedKeySpec(pubKeyBytes);810 PublicKey pubKey =keyFactory.generatePublic(x509KeySpec);811 //初始化私钥
812 byte[] priKeyBytes =TranscodeUtil.base64StrToByteArray(privateKey);813 PKCS8EncodedKeySpec pkcs8KeySpec = newPKCS8EncodedKeySpec(priKeyBytes);814 Key priKey =keyFactory.generatePrivate(pkcs8KeySpec);815 KeyAgreement keyAgree =KeyAgreement.getInstance(keyFactory.getAlgorithm());816 keyAgree.init(priKey);817 keyAgree.doPhase(pubKey, true);818 //生成本地密钥
819 SecretKey secretKey =keyAgree.generateSecret(SECRET_ALGORITHM);820 returnsecretKey;821 } catch(NoSuchAlgorithmException e) {822 e.printStackTrace();823 } catch(InvalidKeySpecException e) {824 e.printStackTrace();825 } catch(InvalidKeyException e) {826 e.printStackTrace();827 }828 return null;829 }830
831 /**
832 * 获取私钥833 *@paramkeyMap 密钥对834 *@return返回base64编码的私钥835 */
836 public static String getDHPrivateKey(MapkeyMap) {837 Key key =(Key) keyMap.get(DHPRIVATE_KEY);838 returnTranscodeUtil.byteArrayToBase64Str(key.getEncoded());839 }840
841 /**
842 * 获取公钥843 *@paramkeyMap 密钥对844 *@return返回base64编码的公钥845 */
846 public static String getDHPublicKey(MapkeyMap) {847 Key key =(Key) keyMap.get(DHPUBLIC_KEY);848 returnTranscodeUtil.byteArrayToBase64Str(key.getEncoded());849 }850
851 /**
852 * 获取私钥853 *@paramkeyStorePath keystore文件路径854 *@paramalias 别名855 *@parampassword 密码856 *@return返回私钥857 */
858 private staticPrivateKey getKeyStorePrivateKey(String keyStorePath, String alias,String password) {859 try{860 KeyStore ks =getKeyStore(keyStorePath, password);861 PrivateKey key =(PrivateKey) ks.getKey(alias, password.toCharArray());862 returnkey;863 } catch(UnrecoverableKeyException e) {864 e.printStackTrace();865 } catch(KeyStoreException e) {866 e.printStackTrace();867 } catch(NoSuchAlgorithmException e) {868 e.printStackTrace();869 }870 return null;871 }872
873 /**
874 * 获取公钥875 *@paramcertificatePath 证书文件路径876 *@return返回公钥877 */
878 private staticPublicKey getCertificatePublicKey(String certificatePath) {879 try{880 Certificate certificate =getCertificate(certificatePath);881 PublicKey key =certificate.getPublicKey();882 returnkey;883 } catch(Exception e) {884 e.printStackTrace();885 }886 return null;887 }888
889 /**
890 * 加载证书文件891 *@paramcertificatePath 证书文件路径892 *@return返回证书893 */
894 private staticCertificate getCertificate(String certificatePath) {895 try{896 CertificateFactory certificateFactory =CertificateFactory.getInstance(X509);897 FileInputStream in = newFileInputStream(certificatePath);898 Certificate certificate =certificateFactory.generateCertificate(in);899 in.close();900 returncertificate;901 } catch(CertificateException e) {902 e.printStackTrace();903 } catch(FileNotFoundException e) {904 e.printStackTrace();905 } catch(IOException e) {906 e.printStackTrace();907 }908 return null;909 }910
911 /**
912 * 获取证书913 *@paramkeyStorePath keystore文件路径914 *@paramalias 别名915 *@parampassword 密码916 *@return返回证书917 */
918 private staticCertificate getCertificate(String keyStorePath,String alias, String password) {919 try{920 KeyStore ks =getKeyStore(keyStorePath, password);921 Certificate certificate =ks.getCertificate(alias);922 returncertificate;923 } catch(KeyStoreException e) {924 e.printStackTrace();925 }926 return null;927 }928
929 /**
930 * 加载KeyStore文件931 *@paramkeyStorePath keystore文件地址932 *@parampassword keystore密码933 *@return返回KeyStore934 */
935 private staticKeyStore getKeyStore(String keyStorePath, String password) {936 try{937 FileInputStream is = newFileInputStream(keyStorePath);938 KeyStore ks =KeyStore.getInstance(KEY_STORE);939 ks.load(is, password.toCharArray());940 is.close();941 returnks;942 } catch(FileNotFoundException e) {943 e.printStackTrace();944 } catch(KeyStoreException e) {945 e.printStackTrace();946 } catch(NoSuchAlgorithmException e) {947 e.printStackTrace();948 } catch(CertificateException e) {949 e.printStackTrace();950 } catch(IOException e) {951 e.printStackTrace();952 }953 return null;954 }955
956 /**
957 * 加密数据958 *@paramdata 要加密的数据959 *@paramkeyStorePath keystore路径960 *@paramalias 别名961 *@parampassword 密码962 *@return返回加密后的数据963 */
964 public staticString encryptByPrivateKey(String data, String keyStorePath,965 String alias, String password) {966 try{967 //取得私钥
968 PrivateKey privateKey =getKeyStorePrivateKey(keyStorePath, alias, password);969 //对数据加密
970 Cipher cipher =Cipher.getInstance(privateKey.getAlgorithm());971 cipher.init(Cipher.ENCRYPT_MODE, privateKey);972 returnTranscodeUtil.byteArrayToBase64Str(cipher.doFinal(data.getBytes()));973 } catch(NoSuchAlgorithmException e) {974 e.printStackTrace();975 } catch(NoSuchPaddingException e) {976 e.printStackTrace();977 } catch(InvalidKeyException e) {978 e.printStackTrace();979 } catch(IllegalBlockSizeException e) {980 e.printStackTrace();981 } catch(BadPaddingException e) {982 e.printStackTrace();983 }984 return null;985 }986
987 /**
988 * 私钥解密989 *@paramdata 要解密的数据990 *@paramkeyStorePath keystore路径991 *@paramalias 别名992 *@parampassword 密码993 *@return返回解密后的数据994 */
995 public staticString decryptByPrivateKey(String data, String keyStorePath,String alias, String password) {996 try{997 //取得私钥
998 PrivateKey privateKey =getKeyStorePrivateKey(keyStorePath, alias, password);999 //对数据加密
1000 Cipher cipher =Cipher.getInstance(privateKey.getAlgorithm());1001 cipher.init(Cipher.DECRYPT_MODE, privateKey);1002 return newString(cipher.doFinal(TranscodeUtil.base64StrToByteArray(data)));1003 } catch(NoSuchAlgorithmException e) {1004 e.printStackTrace();1005 } catch(NoSuchPaddingException e) {1006 e.printStackTrace();1007 } catch(InvalidKeyException e) {1008 e.printStackTrace();1009 } catch(IllegalBlockSizeException e) {1010 e.printStackTrace();1011 } catch(BadPaddingException e) {1012 e.printStackTrace();1013 }1014 return null;1015 }1016
1017 /**
1018 * 私钥加密1019 *@paramdata 要加密的数据1020 *@paramcertificatePath 证书路径1021 *@return返回加密后的信息1022 */
1023 public staticString encryptByPublicKey(String data, String certificatePath) {1024 try{1025 //取得公钥
1026 PublicKey publicKey =getCertificatePublicKey(certificatePath);1027 //对数据加密
1028 Cipher cipher =Cipher.getInstance(publicKey.getAlgorithm());1029 cipher.init(Cipher.ENCRYPT_MODE, publicKey);1030 returnTranscodeUtil.byteArrayToBase64Str(cipher.doFinal(data.getBytes()));1031 } catch(NoSuchAlgorithmException e) {1032 e.printStackTrace();1033 } catch(NoSuchPaddingException e) {1034 e.printStackTrace();1035 } catch(InvalidKeyException e) {1036 e.printStackTrace();1037 } catch(IllegalBlockSizeException e) {1038 e.printStackTrace();1039 } catch(BadPaddingException e) {1040 e.printStackTrace();1041 }1042 return null;1043 }1044
1045 /**
1046 * 公钥解密1047 *@paramdata 要解密的数据1048 *@paramcertificatePath 证书路径1049 *@return返回解密信息1050 */
1051 public staticString decryptByPublicKey(String data, String certificatePath) {1052 try{1053 //取得公钥
1054 PublicKey publicKey =getCertificatePublicKey(certificatePath);1055 //对数据加密
1056 Cipher cipher =Cipher.getInstance(publicKey.getAlgorithm());1057 cipher.init(Cipher.DECRYPT_MODE, publicKey);1058 return newString(cipher.doFinal(TranscodeUtil.base64StrToByteArray(data)));1059 } catch(NoSuchAlgorithmException e) {1060 e.printStackTrace();1061 } catch(NoSuchPaddingException e) {1062 e.printStackTrace();1063 } catch(InvalidKeyException e) {1064 e.printStackTrace();1065 } catch(IllegalBlockSizeException e) {1066 e.printStackTrace();1067 } catch(BadPaddingException e) {1068 e.printStackTrace();1069 }1070 return null;1071 }1072
1073 /**
1074 * 验证证书是否过期1075 *@paramcertificatePath 证书路径1076 *@return返回验证结果1077 */
1078 public static booleanverifyCertificate(String certificatePath) {1079 return verifyCertificate(newDate(), certificatePath);1080 }1081
1082 /**
1083 * 验证证书是否过期1084 *@paramdate 日期1085 *@paramcertificatePath 证书路径1086 *@return返回验证结果1087 */
1088 public static booleanverifyCertificate(Date date, String certificatePath) {1089 boolean status = true;1090 try{1091 //取得证书
1092 Certificate certificate =getCertificate(certificatePath);1093 //验证证书是否过期或无效
1094 status =verifyCertificate(date, certificate);1095 } catch(Exception e) {1096 status = false;1097 }1098 returnstatus;1099 }1100
1101 /**
1102 * 验证证书是否过期1103 *@paramdate 日期1104 *@paramcertificate 证书1105 *@return返回验证结果1106 */
1107 private static booleanverifyCertificate(Date date, Certificate certificate) {1108 boolean status = true;1109 try{1110 X509Certificate x509Certificate =(X509Certificate) certificate;1111 x509Certificate.checkValidity(date);1112 } catch(Exception e) {1113 status = false;1114 }1115 returnstatus;1116 }1117
1118 /**
1119 * 对于数据进行签名1120 *@paramsign 要签名的信息1121 *@paramkeyStorePath keystore文件位置1122 *@paramalias 别名1123 *@parampassword 密码1124 *@return返回签名信息1125 */
1126 public staticString sign(String sign, String keyStorePath, String alias,String password) {1127 try{1128 //获得证书
1129 X509Certificate x509Certificate =(X509Certificate) getCertificate(1130 keyStorePath, alias, password);1131 //获取私钥
1132 KeyStore ks =getKeyStore(keyStorePath, password);1133 //取得私钥
1134 PrivateKey privateKey =(PrivateKey) ks.getKey(alias, password1135 .toCharArray());1136 //构建签名
1137 Signature signature =Signature.getInstance(x509Certificate1138 .getSigAlgName());1139 signature.initSign(privateKey);1140 signature.update(TranscodeUtil.base64StrToByteArray(sign));1141 returnTranscodeUtil.byteArrayToBase64Str(signature.sign());1142 } catch(UnrecoverableKeyException e) {1143 e.printStackTrace();1144 } catch(KeyStoreException e) {1145 e.printStackTrace();1146 } catch(NoSuchAlgorithmException e) {1147 e.printStackTrace();1148 } catch(InvalidKeyException e) {1149 e.printStackTrace();1150 } catch(SignatureException e) {1151 e.printStackTrace();1152 }1153 return null;1154 }1155
1156 /**
1157 * 验证签名信息1158 *@paramdata 要验证的信息1159 *@paramsign 签名信息1160 *@paramcertificatePath 证书路径1161 *@return返回验证结果1162 */
1163 public static booleanverify(String data, String sign,String certificatePath) {1164 try{1165 //获得证书
1166 X509Certificate x509Certificate =(X509Certificate) getCertificate(certificatePath);1167 //获得公钥
1168 PublicKey publicKey =x509Certificate.getPublicKey();1169 //构建签名
1170 Signature signature =Signature.getInstance(x509Certificate1171 .getSigAlgName());1172 signature.initVerify(publicKey);1173 signature.update(TranscodeUtil.base64StrToByteArray(data));1174 returnsignature.verify(TranscodeUtil.base64StrToByteArray(sign));1175 } catch(NoSuchAlgorithmException e) {1176 e.printStackTrace();1177 } catch(InvalidKeyException e) {1178 e.printStackTrace();1179 } catch(SignatureException e) {1180 e.printStackTrace();1181 }1182 return false;1183 }1184
1185 /**
1186 * 验证证书1187 *@paramdate 日期1188 *@paramkeyStorePath keystore文件路径1189 *@paramalias 别名1190 *@parampassword 密码1191 *@return返回验证结果1192 */
1193 public static booleanverifyCertificate(Date date, String keyStorePath,1194 String alias, String password) {1195 boolean status = true;1196 try{1197 Certificate certificate =getCertificate(keyStorePath, alias,1198 password);1199 status =verifyCertificate(date, certificate);1200 } catch(Exception e) {1201 status = false;1202 }1203 returnstatus;1204 }1205
1206 /**
1207 * 验证证书1208 *@paramkeyStorePath keystore文件路径1209 *@paramalias 别名1210 *@parampassword 密码1211 *@return返回验证结果1212 */
1213 public static booleanverifyCertificate(String keyStorePath, String alias,1214 String password) {1215 return verifyCertificate(newDate(), keyStorePath, alias, password);1216 }1217
1218 }