/** * 公钥解密 * * @param data 解密前的字符串 * @param publicKey 公钥 * @return 解密后的字符串 * @throws Exception */ public static String decryptByPubKey(String data, String publicKey) throws Exception { byte [] pubKey = decodeBase64(publicKey); byte [] design = decryptByPubKey(Base64.getDecoder().decode(data), pubKey); return new String(design); } /** * 密钥转成byte[] * * @param key * @return */ public static byte [] decodeBase64(String key) { return Base64.getDecoder().decode(key); } /** * 数字签名,密钥算法 */ private static final String RSA_KEY_ALGORITHM = "RSA" ; /** * 数字签名签名/验证算法 */ private static final String SIGNATURE_ALGORITHM = "MD5withRSA" ; /** * RSA密钥长度,RSA算法的默认密钥长度是1024密钥长度必须是64的倍数,在512到65536位之间 */ private static final int KEY_SIZE = 1024 ; /** * RSA最大加密明文大小 */ private static final int MAX_ENCRYPT_BLOCK = 117 ; /** * RSA最大解密密文大小 */ private static final int MAX_DECRYPT_BLOCK = 128 ; /** * 公钥解密 * * @param data 待解密的数据 * @param pubKey 公钥 * @return 解密后的数据 * @throws Exception */ public static byte [] decryptByPubKey( byte [] data, byte [] pubKey) throws Exception { X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKey); KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM); PublicKey publicKey = keyFactory.generatePublic(x509KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, publicKey); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0 ; byte [] cache; int i = 0 ; // 对数据分段解密 while (inputLen - offSet > 0 ) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0 , cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte [] decryptedData = out.toByteArray(); out.close(); return decryptedData; } |