| | |
| | | import java.security.interfaces.RSAPublicKey; |
| | | import java.security.spec.PKCS8EncodedKeySpec; |
| | | import java.security.spec.X509EncodedKeySpec; |
| | | import java.util.Arrays; |
| | | import java.util.Base64; |
| | | import java.util.HashMap; |
| | | import java.util.Map; |
| | |
| | | |
| | | private static final String CHARSET = "utf-8"; |
| | | |
| | | private static final int KEYSIZE = 2048;// 密钥位数 |
| | | private static final int KEYSIZE = 1024;// 密钥位数 |
| | | private static final int RESERVE_BYTES = 11; |
| | | private static final String ECB_PADDING = "RSA/ECB/PKCS1Padding"; |
| | | |
| | |
| | | |
| | | String privateKeyStr = getPrivateKeyStr(map); |
| | | log.info("-----私钥={}", privateKeyStr); |
| | | System.out.println(privateKeyStr.length()); |
| | | |
| | | String publicKeyStr = getPublicKeyStr(map); |
| | | log.info("-----公钥={}", publicKeyStr); |
| | |
| | | * @return 加密后的密文 |
| | | */ |
| | | public static String encrypt(String text, String publicKeyStr) { |
| | | String result = ""; |
| | | try { |
| | | log.info("明文字符串为:[{}]", text); |
| | | // 加密 |
| | | Cipher cipher = Cipher.getInstance(KEY_ALGORITHM); |
| | | cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKeyStr)); |
| | | |
| | | // URLEncoder编码解决中文乱码问题 |
| | | byte[] data = text.getBytes(StandardCharsets.UTF_8); |
| | | // 加密时超过117字节就报错。为此采用分段加密的办法来加密 |
| | | byte[] enBytes = null; |
| | | for (int i = 0; i < data.length; i += MAX_ENCRYPT_BLOCK) { |
| | | // 注意要使用2的倍数,否则会出现加密后的内容再解密时为乱码 |
| | | byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(data, i, i + MAX_ENCRYPT_BLOCK)); |
| | | enBytes = ArrayUtils.addAll(enBytes, doFinal); |
| | | byte[] textArray = text.getBytes(); |
| | | int textLength = textArray.length; |
| | | log.info("加密字节数={}", textLength); |
| | | // 最大加密字节数,超出最大字节数需要分组加密 |
| | | int MAX_ENCRYPT_BLOCK = 117; |
| | | // 标识 |
| | | int offSet = 0; |
| | | byte[] resultBytes = {}; |
| | | byte[] cache = {}; |
| | | while (textLength - offSet > 0) { |
| | | if (textLength - offSet > MAX_ENCRYPT_BLOCK) { |
| | | cache = cipher.doFinal(textArray, offSet, MAX_ENCRYPT_BLOCK); |
| | | offSet += MAX_ENCRYPT_BLOCK; |
| | | } else { |
| | | cache = cipher.doFinal(textArray, offSet, textLength - offSet); |
| | | offSet = textLength; |
| | | } |
| | | return Base64.getEncoder().encodeToString(enBytes); |
| | | resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length); |
| | | System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length); |
| | | } |
| | | result = Base64.getEncoder().encodeToString(resultBytes); |
| | | } catch (Exception e) { |
| | | throw new RuntimeException("加密字符串[" + text + "]时遇到异常", e); |
| | | } |
| | | return result; |
| | | } |
| | | |
| | | /** |