java加密解密

   1 package com.jetsum.util;
   2 
   3 import java.io.FileInputStream;
   4 import java.io.FileNotFoundException;
   5 import java.io.IOException;
   6 import java.security.InvalidAlgorithmParameterException;
   7 import java.security.InvalidKeyException;
   8 import java.security.Key;
   9 import java.security.KeyFactory;
  10 import java.security.KeyPair;
  11 import java.security.KeyPairGenerator;
  12 import java.security.KeyStore;
  13 import java.security.KeyStoreException;
  14 import java.security.MessageDigest;
  15 import java.security.NoSuchAlgorithmException;
  16 import java.security.PrivateKey;
  17 import java.security.PublicKey;
  18 import java.security.SecureRandom;
  19 import java.security.Signature;
  20 import java.security.SignatureException;
  21 import java.security.UnrecoverableKeyException;
  22 import java.security.cert.Certificate;
  23 import java.security.cert.CertificateException;
  24 import java.security.cert.CertificateFactory;
  25 import java.security.cert.X509Certificate;
  26 import java.security.interfaces.RSAPrivateKey;
  27 import java.security.interfaces.RSAPublicKey;
  28 import java.security.spec.AlgorithmParameterSpec;
  29 import java.security.spec.InvalidKeySpecException;
  30 import java.security.spec.PKCS8EncodedKeySpec;
  31 import java.security.spec.X509EncodedKeySpec;
  32 import java.util.Date;
  33 import java.util.HashMap;
  34 import java.util.Map;
  35 import java.util.Random;
  36 
  37 import javax.crypto.BadPaddingException;
  38 import javax.crypto.Cipher;
  39 import javax.crypto.IllegalBlockSizeException;
  40 import javax.crypto.KeyAgreement;
  41 import javax.crypto.KeyGenerator;
  42 import javax.crypto.Mac;
  43 import javax.crypto.NoSuchPaddingException;
  44 import javax.crypto.SecretKey;
  45 import javax.crypto.SecretKeyFactory;
  46 import javax.crypto.interfaces.DHPrivateKey;
  47 import javax.crypto.interfaces.DHPublicKey;
  48 import javax.crypto.spec.DHParameterSpec;
  49 import javax.crypto.spec.IvParameterSpec;
  50 import javax.crypto.spec.PBEKeySpec;
  51 import javax.crypto.spec.PBEParameterSpec;
  52 import javax.crypto.spec.SecretKeySpec;
  53 
  54 public class CipherUtil {
  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      * AESkey
  79      */
  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      * <pre>
 116      * DH
 117      * Default Keysize 1024
 118      * Keysize must be a multiple of 64, ranging from 512 to 1024 (inclusive).
 119      * </pre>
 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_STORE
 140      */
 141     private static final String KEY_STORE = "JKS";
 142 
 143     private static final String X509 = "X.509";
 144 
 145     /**
 146      * 信息摘要算法
 147      * @param algorithm 算法类型
 148      * @param data 要加密的字符串
 149      * @return 返回加密后的摘要信息
 150      */
 151     private static String encryptEncode(String algorithm, String data) {
 152         try {
 153             MessageDigest md = MessageDigest.getInstance(algorithm);
 154             return TranscodeUtil.byteArrayToHexStr(md.digest(data.getBytes()));
 155         } catch(NoSuchAlgorithmException ex) {
 156             ex.printStackTrace();
 157         }
 158         return null;
 159     }
 160 
 161     /**
 162      * 使用MD5加密
 163      * @param data 要加密的字符串
 164      * @return 返回加密后的信息
 165      */
 166     public static String MD5Encode(String data) {
 167         return encryptEncode(ALGORITHM_MD5, data);
 168     }
 169 
 170     /**
 171      * 使用SHA加密
 172      * @param data 要加密的字符串
 173      * @return 返回加密后的信息
 174      */
 175     public static String SHAEncode(String data) {
 176         return encryptEncode(ALGORITHM_SHA, data);
 177     }
 178 
 179     /**
 180      * 生成HMAC密钥
 181      * @return 返回密钥信息
 182      */
 183     public static String generateMACKey() {
 184         try {
 185             KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM_MAC);
 186             SecretKey secretKey = keyGenerator.generateKey();
 187             return TranscodeUtil.byteArrayToBase64Str(secretKey.getEncoded());
 188         } catch (NoSuchAlgorithmException e) {
 189             e.printStackTrace();
 190         }
 191         return null;
 192     }
 193 
 194     /**
 195      * 使用HMAC加密
 196      * @param data 要加密的字符串
 197      * @param key 密钥
 198      * @return 返回加密后的信息
 199      */
 200     public static String 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             return TranscodeUtil.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      * @param key 密钥字符串
 217      * @param algorithm 加密算法
 218      * @return 返回密钥对象
 219      */
 220     private static Key toKey(String key,String algorithm) {
 221         SecretKey secretKey = new SecretKeySpec(TranscodeUtil.base64StrToByteArray(key), algorithm);
 222         return secretKey;
 223     }
 224 
 225     /**
 226      * 生成DES密钥
 227      * @param seed 密钥种子
 228      * @return 返回base64编码的密钥字符串
 229      */
 230     public static String generateDESKey(String seed) {
 231         try {
 232             KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_DES);
 233             kg.init(new SecureRandom(seed.getBytes()));
 234             SecretKey secretKey = kg.generateKey();
 235             return TranscodeUtil.byteArrayToBase64Str(secretKey.getEncoded());
 236         } catch (NoSuchAlgorithmException e) {
 237             e.printStackTrace();
 238         }
 239         return null;
 240     }
 241 
 242     /**
 243      * DES加密
 244      * @param data 要加密的数据
 245      * @param key 密钥
 246      * @return 返回加密后的数据(经过base64编码)
 247      */
 248     public static String DESEncrypt(String data,String key) {
 249         return DESCipher(data,key,Cipher.ENCRYPT_MODE);
 250     }
 251 
 252     /**
 253      * DES解密
 254      * @param data 要解密的数据
 255      * @param key 密钥
 256      * @return 返回解密后的数据
 257      */
 258     public static String DESDecrypt(String data, String key) {
 259         return DESCipher(data,key,Cipher.DECRYPT_MODE);
 260     }
 261 
 262     /**
 263      * DES的加密解密
 264      * @param data 要加密或解密的数据
 265      * @param key 密钥
 266      * @param mode 加密或解密模式
 267      * @return 返回加密或解密的数据
 268      */
 269     private static String DESCipher(String data, String key, int mode) {
 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?new String(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 static String generatePBESalt() {
 286         byte[] salt = new byte[8];
 287         Random random = new Random();
 288         random.nextBytes(salt);
 289         return TranscodeUtil.byteArrayToBase64Str(salt);
 290     }
 291 
 292     /**
 293      * PBE(Password-based encryption基于密码加密)加密
 294      * @param data 要加密的数据
 295      * @param password 密码
 296      * @param salt 盐
 297      * @return 返回加密后的数据(经过base64编码)
 298      */
 299     public static String PBEEncrypt(String data,String password,String salt) {
 300         return PBECipher( data, password, salt, Cipher.ENCRYPT_MODE);
 301     }
 302 
 303     /**
 304      * PBE(Password-based encryption基于密码加密)解密
 305      * @param data 要解密的数据
 306      * @param password 密码
 307      * @param salt 盐
 308      * @return 返回解密后的数据
 309      */
 310     public static String PBEDecrypt(String data,String password,String salt) {
 311         return PBECipher( data, password, salt, Cipher.DECRYPT_MODE);
 312     }
 313 
 314     /**
 315      * PBE加密解密
 316      * @param data 要加密解密的信息
 317      * @param password 密码
 318      * @param salt 盐
 319      * @param mode 加密或解密模式
 320      * @return 返回加密解密后的数据
 321      */
 322     private static String PBECipher(String data,String password,String salt,int mode) {
 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?new String(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      * 生成PBEkey
 347      * @param password 使用的密码
 348      * @return 返回生成的PBEkey
 349      */
 350     private static Key toPBEKey(String password) {
 351         PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
 352         try {
 353             SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM_PBE);
 354             SecretKey secretKey = keyFactory.generateSecret(keySpec);
 355             return secretKey;
 356         } catch (NoSuchAlgorithmException e) {
 357             e.printStackTrace();
 358         } catch (InvalidKeySpecException e) {
 359             e.printStackTrace();
 360         }
 361         return null;
 362     }
 363 
 364     /**
 365      * 生成AESkey
 366      * @param keySize key的位数
 367      * @param seed 随机种子
 368      * @return 返回base64编码后的key信息
 369      */
 370     public static String generateAESKey(int keySize,String seed) {
 371         try {
 372             KeyGenerator kgen = KeyGenerator.getInstance(KEY_AES);
 373             kgen.init(keySize,new SecureRandom(seed.getBytes()));
 374             SecretKey key = kgen.generateKey();
 375             return TranscodeUtil.byteArrayToBase64Str(key.getEncoded());
 376         } catch (NoSuchAlgorithmException e) {
 377             e.printStackTrace();
 378         }
 379         return null;
 380     }
 381 
 382     /**
 383      * AES加密
 384      * @param data 要加密的数据
 385      * @param key 密钥
 386      * @param algorithmParameter 算法参数
 387      * @return 返回加密数据
 388      */
 389     public static String AESEncrypt(String data,String key,String algorithmParameter) {
 390         return AESCipher(data, key, algorithmParameter,Cipher.ENCRYPT_MODE);
 391     }
 392 
 393     /**
 394      * AES解密
 395      * @param data 要解密的数据
 396      * @param key 密钥
 397      * @param algorithmParameter 算法参数
 398      * @return 返回解密数据
 399      */
 400     public static String AESDecrypt(String data,String key,String algorithmParameter) {
 401         return AESCipher(data, key, algorithmParameter,Cipher.DECRYPT_MODE);
 402     }
 403 
 404     /**
 405      * 实现AES加密解密
 406      * @param data 要加密或解密的数据
 407      * @param key 密钥
 408      * @param algorithmParameter 算法参数
 409      * @param mode 加密或解密
 410      * @return 返回加密或解密的数据
 411      */
 412     private static String AESCipher(String data, String key, String algorithmParameter,int mode) {
 413         try {
 414             Key k = toKey(key,KEY_AES);
 415             AlgorithmParameterSpec paramSpec = new IvParameterSpec(algorithmParameter.getBytes());
 416             Cipher ecipher = Cipher.getInstance(ALGORITHM_AES);
 417             ecipher.init(mode, k, paramSpec);
 418             return mode==Cipher.DECRYPT_MODE?new String(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      * @param data 要签名的密文
 438      * @param privateKey 私钥
 439      * @return 返回签名信息
 440      */
 441     public static String RSASign(String data, String privateKey) {
 442         try {
 443             // 解密由base64编码的私钥
 444             byte[] keyBytes = TranscodeUtil.base64StrToByteArray(privateKey);
 445             // 构造PKCS8EncodedKeySpec对象
 446             PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(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             return TranscodeUtil.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      * @param data 要验证的密文
 471      * @param publicKey 公钥
 472      * @param sign 签名信息
 473      * @return 返回验证成功状态
 474      */
 475     public static boolean RSAVerify(String data, String publicKey, String sign) {
 476         try {
 477             // 解密由base64编码的公钥
 478             byte[] keyBytes = TranscodeUtil.base64StrToByteArray(publicKey);
 479             // 构造X509EncodedKeySpec对象
 480             X509EncodedKeySpec keySpec = new X509EncodedKeySpec(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             return signature.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      * @param data 要解密的字符串
 506      * @param key 私钥
 507      * @return 返回解密后的字符串
 508      */
 509     public static String RSADecryptByPrivateKey(String data, String key) {
 510         try {
 511             // 对密钥解密
 512             byte[] keyBytes = TranscodeUtil.base64StrToByteArray(key);
 513             // 取得私钥
 514             PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(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 new String(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      * @param data 要解密的数据
 540      * @param key 公钥
 541      * @return 返回解密后的数据
 542      */
 543     public static String RSADecryptByPublicKey(String data, String key) {
 544         try {
 545             // 对密钥解密
 546             byte[] keyBytes = TranscodeUtil.base64StrToByteArray(key);
 547             // 取得公钥
 548             X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(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 new String(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      * @param data 要加密的数据
 574      * @param key 公钥
 575      * @return 返回加密的数据
 576      */
 577     public static String RSAEncryptByPublicKey(String data, String key) {
 578         try {
 579             // 对公钥解密
 580             byte[] keyBytes = TranscodeUtil.base64StrToByteArray(key);
 581             // 取得公钥
 582             X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(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             return TranscodeUtil.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      * @param data 要加密的数据
 608      * @param key 私钥
 609      * @return 返回加密后的数据
 610      */
 611     public static String RSAEncryptByPrivateKey(String data, String key) {
 612         try {
 613             // 对密钥解密
 614             byte[] keyBytes = TranscodeUtil.base64StrToByteArray(key);
 615             // 取得私钥
 616             PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(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             return TranscodeUtil.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      * @param keyMap 密钥对
 642      * @return 返回经过base64编码的私钥
 643      */
 644     public static String getRSAPrivateKey(Map<String, Object> keyMap) {
 645         Key key = (Key) keyMap.get(RSAPRIVATE_KEY);
 646         return TranscodeUtil.byteArrayToBase64Str(key.getEncoded());
 647     }
 648 
 649     /**
 650      * 获得公钥(base64编码)
 651      * @param keyMap 密钥对
 652      * @return 返回经过base64编码的公钥
 653      */
 654     public static String getRSAPublicKey(Map<String, Object> keyMap) {
 655         Key key = (Key) keyMap.get(RSAPUBLIC_KEY);
 656         return TranscodeUtil.byteArrayToBase64Str(key.getEncoded());
 657     }
 658 
 659     /**
 660      * 初始化密钥对
 661      * @return 返回密钥对
 662      */
 663     public static Map<String, Object> initRSAKey() {
 664         Map<String, Object> keyMap = new HashMap<String, Object>(2);
 665         try {
 666             KeyPairGenerator keyPairGen = KeyPairGenerator
 667                                           .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         return keyMap;
 680     }
 681 
 682     /**
 683      * 初始化甲方密钥对
 684      * @return 返回甲方密钥对
 685      */
 686     public static Map<String, Object> initDHKey() {
 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<String, Object> keyMap = new HashMap<String, Object>(2);
 696             keyMap.put(DHPUBLIC_KEY, publicKey);
 697             keyMap.put(DHPRIVATE_KEY, privateKey);
 698             return keyMap;
 699         } catch (NoSuchAlgorithmException e) {
 700             e.printStackTrace();
 701         }
 702         return null;
 703     }
 704 
 705     /**
 706      * 使用甲方公钥初始化乙方密钥对
 707      * @param key 甲方公钥
 708      * @return 返回乙方密钥对
 709      */
 710     public static Map<String, Object> initDHKey(String key) {
 711         try {
 712             // 解析甲方公钥
 713             byte[] keyBytes = TranscodeUtil.base64StrToByteArray(key);
 714             X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(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<String, Object> keyMap = new HashMap<String, Object>(2);
 727             keyMap.put(DHPUBLIC_KEY, publicKey);
 728             keyMap.put(DHPRIVATE_KEY, privateKey);
 729             return keyMap;
 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      * @param data 要加密的数据
 743      * @param publicKey 甲方或乙方公钥
 744      * @param privateKey 甲方或乙方私钥
 745      * @return 加密结果
 746      */
 747     public static String 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             return TranscodeUtil.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      * @param data 要解密的数据
 772      * @param publicKey 公钥
 773      * @param privateKey 私钥
 774      * @return 返回解密结果
 775      */
 776     public static String 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 new String(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      * @param publicKey 公钥
 801      * @param privateKey 私钥
 802      * @return 返回本地密钥
 803      */
 804     private static SecretKey getDHSecretKey(String publicKey, String privateKey) {
 805         try {
 806             // 初始化公钥
 807             byte[] pubKeyBytes = TranscodeUtil.base64StrToByteArray(publicKey);
 808             KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_DH);
 809             X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKeyBytes);
 810             PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
 811             // 初始化私钥
 812             byte[] priKeyBytes = TranscodeUtil.base64StrToByteArray(privateKey);
 813             PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(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             return secretKey;
 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      * @param keyMap 密钥对
 834      * @return 返回base64编码的私钥
 835      */
 836     public static String getDHPrivateKey(Map<String, Object> keyMap) {
 837         Key key = (Key) keyMap.get(DHPRIVATE_KEY);
 838         return TranscodeUtil.byteArrayToBase64Str(key.getEncoded());
 839     }
 840 
 841     /**
 842      * 获取公钥
 843      * @param keyMap 密钥对
 844      * @return 返回base64编码的公钥
 845      */
 846     public static String getDHPublicKey(Map<String, Object> keyMap) {
 847         Key key = (Key) keyMap.get(DHPUBLIC_KEY);
 848         return TranscodeUtil.byteArrayToBase64Str(key.getEncoded());
 849     }
 850 
 851     /**
 852      * 获取私钥
 853      * @param keyStorePath keystore文件路径
 854      * @param alias 别名
 855      * @param password 密码
 856      * @return 返回私钥
 857      */
 858     private static PrivateKey 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             return key;
 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      * @param certificatePath 证书文件路径
 876      * @return 返回公钥
 877      */
 878     private static PublicKey getCertificatePublicKey(String certificatePath) {
 879         try {
 880             Certificate certificate = getCertificate(certificatePath);
 881             PublicKey key = certificate.getPublicKey();
 882             return key;
 883         } catch (Exception e) {
 884             e.printStackTrace();
 885         }
 886         return null;
 887     }
 888 
 889     /**
 890      * 加载证书文件
 891      * @param certificatePath 证书文件路径
 892      * @return 返回证书
 893      */
 894     private static Certificate getCertificate(String certificatePath) {
 895         try {
 896             CertificateFactory certificateFactory = CertificateFactory.getInstance(X509);
 897             FileInputStream in = new FileInputStream(certificatePath);
 898             Certificate certificate = certificateFactory.generateCertificate(in);
 899             in.close();
 900             return certificate;
 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      * @param keyStorePath keystore文件路径
 914      * @param alias 别名
 915      * @param password 密码
 916      * @return 返回证书
 917      */
 918     private static Certificate getCertificate(String keyStorePath,String alias, String password) {
 919         try {
 920             KeyStore ks = getKeyStore(keyStorePath, password);
 921             Certificate certificate = ks.getCertificate(alias);
 922             return certificate;
 923         } catch (KeyStoreException e) {
 924             e.printStackTrace();
 925         }
 926         return null;
 927     }
 928 
 929     /**
 930      * 加载KeyStore文件
 931      * @param keyStorePath keystore文件地址
 932      * @param password keystore密码
 933      * @return 返回KeyStore
 934      */
 935     private static KeyStore getKeyStore(String keyStorePath, String password) {
 936         try {
 937             FileInputStream is = new FileInputStream(keyStorePath);
 938             KeyStore ks = KeyStore.getInstance(KEY_STORE);
 939             ks.load(is, password.toCharArray());
 940             is.close();
 941             return ks;
 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      * @param data 要加密的数据
 959      * @param keyStorePath keystore路径
 960      * @param alias 别名
 961      * @param password 密码
 962      * @return 返回加密后的数据
 963      */
 964     public static String 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             return TranscodeUtil.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      * @param data 要解密的数据
 990      * @param keyStorePath keystore路径
 991      * @param alias 别名
 992      * @param password 密码
 993      * @return 返回解密后的数据
 994      */
 995     public static String 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 new String(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      * @param data 要加密的数据
1020      * @param certificatePath 证书路径
1021      * @return 返回加密后的信息
1022      */
1023     public static String 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             return TranscodeUtil.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      * @param data 要解密的数据
1048      * @param certificatePath 证书路径
1049      * @return 返回解密信息
1050      */
1051     public static String 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 new String(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      * @param certificatePath 证书路径
1076      * @return 返回验证结果
1077      */
1078     public static boolean verifyCertificate(String certificatePath) {
1079         return verifyCertificate(new Date(), certificatePath);
1080     }
1081 
1082     /**
1083      * 验证证书是否过期
1084      * @param date 日期
1085      * @param certificatePath 证书路径
1086      * @return 返回验证结果
1087      */
1088     public static boolean verifyCertificate(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         return status;
1099     }
1100 
1101     /**
1102      * 验证证书是否过期
1103      * @param date 日期
1104      * @param certificate 证书
1105      * @return 返回验证结果
1106      */
1107     private static boolean verifyCertificate(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         return status;
1116     }
1117 
1118     /**
1119      * 对于数据进行签名
1120      * @param sign 要签名的信息
1121      * @param keyStorePath keystore文件位置
1122      * @param alias 别名
1123      * @param password 密码
1124      * @return 返回签名信息
1125      */
1126     public static String 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, password
1135                                     .toCharArray());
1136             // 构建签名
1137             Signature signature = Signature.getInstance(x509Certificate
1138                                   .getSigAlgName());
1139             signature.initSign(privateKey);
1140             signature.update(TranscodeUtil.base64StrToByteArray(sign));
1141             return TranscodeUtil.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      * @param data 要验证的信息
1159      * @param sign 签名信息
1160      * @param certificatePath 证书路径
1161      * @return 返回验证结果
1162      */
1163     public static boolean verify(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(x509Certificate
1171                                   .getSigAlgName());
1172             signature.initVerify(publicKey);
1173             signature.update(TranscodeUtil.base64StrToByteArray(data));
1174             return signature.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      * @param date 日期
1188      * @param keyStorePath keystore文件路径
1189      * @param alias 别名
1190      * @param password 密码
1191      * @return 返回验证结果
1192      */
1193     public static boolean verifyCertificate(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         return status;
1204     }
1205 
1206     /**
1207      * 验证证书
1208      * @param keyStorePath keystore文件路径
1209      * @param alias 别名
1210      * @param password 密码
1211      * @return 返回验证结果
1212      */
1213     public static boolean verifyCertificate(String keyStorePath, String alias,
1214                                             String password) {
1215         return verifyCertificate(new Date(), keyStorePath, alias, password);
1216     }
1217 
1218 }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

扫码关注云+社区

领取腾讯云代金券