Java AES加密代码分析:填充方式解析
该Java代码使用AES算法进行加密,秘钥长度必须是16位,采用ECB模式进行填充。具体填充方式没有明确指定,可能是默认的PKCS5Padding或者NoPadding方式。
public static String encryptByAES(String input, String key) throws Exception {
// 算法
String algorithm = 'AES';
String transformation = 'AES';
// Cipher:密码,获取加密对象
// transformation:参数表示使用什么类型加密
Cipher cipher = Cipher.getInstance(transformation);
// 指定秘钥规则
// 第一个参数表示:密钥,key的字节数组 长度必须是16位
// 第二个参数表示:算法
SecretKeySpec sks = new SecretKeySpec(key.getBytes(), algorithm);
// 对加密进行初始化
// 第一个参数:表示模式,有加密模式和解密模式
// 第二个参数:表示秘钥规则
cipher.init(Cipher.ENCRYPT_MODE,sks);
// 进行加密
byte[] bytes = cipher.doFinal(input.getBytes());
return bytesToHexString(bytes);
}
private static String bytesToHexString(byte[] sources) {
if (sources == null) return null;
StringBuilder stringBuffer = new StringBuilder();
for (byte source : sources) {
String result = Integer.toHexString(source& 0xff);
if (result.length() < 2) {
result = '0' + result;
}
stringBuffer.append(result);
}
return stringBuffer.toString();
}
原文地址: http://www.cveoy.top/t/topic/nQSI 著作权归作者所有。请勿转载和采集!