/**
* 解密十六进制字符串为字符串
* @param encodedHex
* @param password
* @return
* @throws Exception
*/
public static String decryptHex(String encodedHex, String password) throws Exception {
String hex = URLDecoder.decode(encodedHex, StandardCharsets.UTF_8.name())
.replaceAll("\\s+", "");
if (hex.length() == 0 || (hex.length() & 1) != 0 || !hex.matches("[0-9A-Fa-f]+")) {
throw new IllegalArgumentException("密文必须是偶数长度的十六进制字符串");
}
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, legacyAesKey(password));
byte[] plaintext = cipher.doFinal(hexToBytes(hex));
return new String(plaintext, StandardCharsets.UTF_8);
}
/**
* 将十六进制字符串转换为字节数组
* @param hex
* @return
*/
public static byte[] hexToBytes(String hex) {
byte[] bytes = new byte[hex.length() / 2];
for (int i = 0; i < bytes.length; i++) {
int high = Character.digit(hex.charAt(i * 2), 16);
int low = Character.digit(hex.charAt(i * 2 + 1), 16);
bytes[i] = (byte) ((high << 4) + low);
}
return bytes;
}
public static void main(String[] args) throws Exception {
String token = "7262ba75aa32339ba5893797b6351dfc3dd72c3fcc6928c70443cf5502a2f69820b86edd5ac9bf51c73d99bdf25d572b7e4b87d801db111cf1e56ffb4af1bd9e705c6837d7e4f1fd1f6a288e16be4229";
String encryptResultStr = URLEncoder.encode(token, "UTF-8");
// 合作方密钥,由微医分配
String key = "ZAinz^ƒ8SFb6FNj9bCQ7FxMnQc";
String decryptResult = OpenApiUtil.decryptHex(encryptResultStr, key);
System.out.println("解密后:" + decryptResult);
}