| | |
| | | import javax.crypto.SecretKey; |
| | | import javax.crypto.spec.IvParameterSpec; |
| | | import javax.crypto.spec.SecretKeySpec; |
| | | import java.nio.charset.StandardCharsets; |
| | | import java.security.InvalidKeyException; |
| | | import java.security.MessageDigest; |
| | | import java.security.NoSuchAlgorithmException; |
| | |
| | | /** |
| | | * aes解密 |
| | | * @param secretKey 秘钥 |
| | | * @param encryptedData Data |
| | | * @param encryptedData 密文 |
| | | * @return digest as a hex string |
| | | */ |
| | | public static String decryptAes(String encryptedData, String secretKey) throws Exception { |
| | | // AES 密钥长度需要是 128, 192, 或 256 位(16, 24, 或 32 字节) |
| | | byte[] keyBytes = secretKey.getBytes("UTF-8"); |
| | | byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8); |
| | | SecretKeySpec key = new SecretKeySpec(keyBytes, "AES"); |
| | | |
| | | // 初始化向量 IV 也需要是 128 位(16 字节) |
| | | byte[] ivBytes = secretKey.substring(0, 16).getBytes("UTF-8"); |
| | | byte[] ivBytes = secretKey.substring(0, 16).getBytes(StandardCharsets.UTF_8); |
| | | IvParameterSpec iv = new IvParameterSpec(ivBytes); |
| | | |
| | | // 解密 |
| | |
| | | byte[] decodedValue = Base64.getDecoder().decode(encryptedData); |
| | | byte[] decryptedBytes = cipher.doFinal(decodedValue); |
| | | |
| | | return new String(decryptedBytes, "UTF-8"); |
| | | return new String(decryptedBytes, StandardCharsets.UTF_8); |
| | | } |
| | | |
| | | /** |
| | | * aes解密 |
| | | * @param secretKey 秘钥 |
| | | * @param decryptData 明文 |
| | | * @return digest as a hex string |
| | | */ |
| | | public static String encryptAes(String decryptData, String secretKey) throws Exception{ |
| | | // AES 密钥长度需要是 128, 192, 或 256 位(16, 24, 或 32 字节) |
| | | byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8); |
| | | SecretKeySpec key = new SecretKeySpec(keyBytes, "AES"); |
| | | |
| | | // 初始化向量 IV 也需要是 128 位(16 字节) |
| | | byte[] ivBytes = secretKey.substring(0, 16).getBytes(StandardCharsets.UTF_8); |
| | | IvParameterSpec iv = new IvParameterSpec(ivBytes); |
| | | |
| | | // 加密 |
| | | Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); |
| | | cipher.init(Cipher.ENCRYPT_MODE, key, iv); |
| | | |
| | | byte[] encryptBytes = cipher.doFinal(decryptData.getBytes(StandardCharsets.UTF_8)); |
| | | return Base64.getEncoder().encodeToString(encryptBytes); |
| | | } |
| | | |
| | | /** |