下面是Java的demo,leader希望用golang实现,主要是我查了下资料,官方貌似是不支持aes-128-ecb加密解密的,而且限时一天,催的很紧。另外对接方提供的这个加密key是15位的,我用标准16位加密结果和Java版本跑出来结果是一致的,但是用15位golang程序就会出错,现在对这个key的填充方式表示很懵逼
(```)
public static String decryptAES(String encryptResultStr, String password) {
byte[] decryptFrom = parseHexStr2Byte(encryptResultStr);
byte[] decryptResult = decrypt(decryptFrom, password);
return new String(decryptResult);
}
private static byte[] decrypt(byte[] content, String password) {
try {
SecretKeySpec key = new SecretKeySpec(Arrays.copyOf(password.getBytes("utf-8"), 16), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] result = cipher.doFinal(content);
return result;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
return null;
}
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length()/2];
for (int i = 0;i< hexStr.length()/2; i++) {
int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
public static void main(String[] args) {
String encryText = "encrypted content"; //待解密内容
System.out.print(decryptAES(encryText, "password")); //解密密钥
}
(```)
以下是PHP版本的,PHP版本实现起来就比较简单
(```)
function decrypt($encryptedStr, $key) {
return openssl_decrypt(hex2bin($encryptedStr), 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
}
(```)
更多评论