一、使用MessageDigest进行文件加签
(1)声明MessageDigest对象
protected static MessageDigest messagedigest = null;
(2)传入要使用的算法
messagedigest = MessageDigest.getInstance("MD5");
(3)传入要加密的数据
byte data[] = null;
String strs = key + str;
data = strs.getBytes("GBK");
// update传入的参数是字节类型或字节类型数组,对于字符串,需要先使用getBytes( )方法生成字符串数组。
messagedigest.update(data);
(4)执行加密方法
// 执行MessageDigest对象的digest( )方法完成计算,计算的结果通过字节类型的数组返回。
byte resultData[] = messagedigest.digest();
System.out.println(Arrays.toString(resultData));
return convertToHexString(resultData);
(5)将结果转化为16进制
private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
// 将byte数据转换成十六进制的字符串
private static String convertToHexString(byte[] bytes) {
char[] buf = new char[bytes.length * 2];
int index = 0;
for (byte b : bytes) { // 利用位运算进行转换,可以看作方法一的变种
buf[index++] = HEX_CHAR[b >>> 4 & 0xf];
buf[index++] = HEX_CHAR[b & 0xf];
}
return new String(buf);
}
二、使用SecretKeySpec进行文件加签
(1)数据加密
public static String getHmacMD5(String key, String str) throws Exception {
// 创建SecretKeySpec对象,设置加密算法并传入原数据
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "HmacMD5");
// 创建MAC对象,定义加密算法
Mac mac = Mac.getInstance("HmacMD5");
// 传入key值,
mac.init(secretKey);
// 传入加密数据,生成秘钥
return convertToHexString(mac.doFinal(str.getBytes()));
}
(2)结果转换
private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
// 将byte数据转换成十六进制的字符串
private static String convertToHexString(byte[] bytes) {
char[] buf = new char[bytes.length * 2];
int index = 0;
for (byte b : bytes) { // 利用位运算进行转换,可以看作方法一的变种
buf[index++] = HEX_CHAR[b >>> 4 & 0xf];
buf[index++] = HEX_CHAR[b & 0xf];
}
return new String(buf);
}
三、使用DigestUtils进行文件加密
(1)在maven项目中添加依赖
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>
(2)项目中使用
// 对数据进行签名
public static String getMd5(String key, String str) {
// 签名后的字符串
String encodeStr = DigestUtils.md5Hex(key + str);
return encodeStr;
}
// 对本地文件进行签名
public static String getFileMd5(String str) throws IOException {
InputStream inputStream = new FileInputStream(str);
String sha1Hex = DigestUtils.sha1Hex(inputStream);
inputStream.close();
return sha1Hex;
}
// 对数据进行验签
public static boolean verify(String key, String str, String md5)
throws Exception {
// 根据传入的密钥进行验证
String md5Text = getMd5(key, str);
if (md5Text.equalsIgnoreCase(md5)) {
return true;
}
return false;
}