RSA加密 @param data 待加密数据 @return
(String data)
| 68 | * @return |
| 69 | */ |
| 70 | public static String encrypt(String data) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException { |
| 71 | PublicKey publicKey = getPublicKey(thpubk); |
| 72 | Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding"); |
| 73 | cipher.init(Cipher.ENCRYPT_MODE, publicKey); |
| 74 | int inputLen = data.getBytes().length; |
| 75 | ByteArrayOutputStream out = new ByteArrayOutputStream(); |
| 76 | int offset = 0; |
| 77 | byte[] cache; |
| 78 | int i = 0; |
| 79 | // 对数据分段加密 |
| 80 | while (inputLen - offset > 0) { |
| 81 | if (inputLen - offset > MAX_ENCRYPT_BLOCK) { |
| 82 | cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK); |
| 83 | } else { |
| 84 | cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset); |
| 85 | } |
| 86 | out.write(cache, 0, cache.length); |
| 87 | i++; |
| 88 | offset = i * MAX_ENCRYPT_BLOCK; |
| 89 | } |
| 90 | byte[] encryptedData = out.toByteArray(); |
| 91 | out.close(); |
| 92 | // 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串 |
| 93 | // 加密后的字符串 |
| 94 | return Base64.encodeToString(encryptedData, Base64.NO_WRAP); |
| 95 | } |
| 96 | /** |
| 97 | * RSA解密 |
| 98 | * |
nothing calls this directly
no test coverage detected