nodejs代码
const buf = Buffer.from(‘123456’, ‘hex’);
hex - 将每个字节编码为两个十六进制字符。
export function aesDecrypt(hexStr: string, hexKey: string) {
const buffer = new Buffer(hexStr, "hex"); const keyBuf = new Buffer(hexKey, "hex");
const aes = crypto.createDecipheriv('aes-128-ecb', keyBuf, Buffer.alloc(0));
aes.setAutoPadding(true);
const result = aes.update(buffer).toString("hex") + aes.final("hex");
return result;
}
java代码
private static final String ALGORITHM = "AES";
private static final String CIPHER_ALGORITHM_PADDING = "AES/ECB/PKCS5Padding";
public static String encrypt(String hexStr, String hexKey) {
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_PADDING);
SecretKeySpec skeySpec = new SecretKeySpec(HexByteUtil.hexToBytes(hexKey), ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encryptData = cipher.doFinal(HexByteUtil.hexToBytes(hexStr));
return HexByteUtil.parseByte2HexStr(encryptData).toLowerCase();
} catch (Exception ex) {
log.info("encryptPKCS5 error encrypt data = {}", hexStr, ex);
return "";
}
}
HexByteUtil
public static byte[] hexToBytes(String hex) {
byte[] buf = new byte[hex.length() / 2];
for (int i = 0; i < hex.length() / 2; i++) {
String sub = hex.substring(i * 2, i * 2 + 2);
buf[i] = (byte) Integer.parseInt(sub, 16);
}
return buf;
}
public static int uint8Array(int num) {
int j = num;
if (j < 0) {
j = num + Math.abs(num) / 256 * 256 + 256;
}
if (j > 255) {
j = num - num / 256 * 256;
}
return j;
}