(String str)
| 14 | private static final String rsaPubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8H6Gp7XP6UvEQzvUgGnt9nPX4exn1aNlmeyloMl6g2rEggeTNMp7I3iLPzQDbt6yedCru971fducKc2DgF/y2CcwAdqaKdxm0dSI2Zs4QLNYbKwWJ65wkgUh8+TJBnk+PGTgoxZ2wzvhJyRGjGhsFvLmZkUYPPxAPSNfjB3+/4wIDAQAB"; |
| 15 | |
| 16 | public static String encrypt(String str) { |
| 17 | try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { |
| 18 | PublicKey publicKeyFromX509 = getPublicKeyFromX509("RSA"); |
| 19 | Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); |
| 20 | cipher.init(Cipher.ENCRYPT_MODE, publicKeyFromX509); |
| 21 | byte[] bytes = str.getBytes(StandardCharsets.UTF_8); |
| 22 | // 根据密钥长度计算块大小 |
| 23 | int keySize = publicKeyFromX509.getEncoded().length * 8; |
| 24 | int blockSize = (keySize / 8) - 11; // 减去 PKCS1 填充的长度 |
| 25 | |
| 26 | for (int i = 0; i < bytes.length; i += blockSize) { |
| 27 | int length = Math.min(blockSize, bytes.length - i); |
| 28 | byte[] encryptedBlock = cipher.doFinal(bytes, i, length); |
| 29 | byteArrayOutputStream.write(encryptedBlock); |
| 30 | } |
| 31 | |
| 32 | return new String(Base64.encode(byteArrayOutputStream.toByteArray())); |
| 33 | } catch (Exception e) { |
| 34 | e.printStackTrace(); |
| 35 | } |
| 36 | return null; |
| 37 | } |
| 38 | |
| 39 | private static PublicKey getPublicKeyFromX509(String str) throws Exception { |
| 40 | KeyFactory keyFactory; |
no test coverage detected