Java后端将文件进行加密,本文可以实现 MD5 , SHA1 , SHA-256, SHA-384, SHA-512 etc等类型的加密。
1.首先创建get file MD5方法,最好是封装一个工具类,以后使用方面
/**
* @param File
* @param algorithm 所请求算法的名称 for example: MD5, SHA1, SHA-256, SHA-384, SHA-512 etc.
* @return
*/ public static String getFileMD5(File file,String algorithm) {
if (!file.isFile()) {
return null;
}
MessageDigest digest = null;
FileInputStream in = null;
byte buffer[] = new byte [1024];
int len;
try {
digest = MessageDigest. getInstance (algorithm);
in = new FileInputStream(file);
while ((len = in.read(buffer, 0, 1024)) != -1) {
digest.update(buffer, 0, len );
}
in.close();
} catch ( Exception e) {
e.printStackTrace();
return null;
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
}
2.调用即可
getFileMD5(file,"SHA1");
就是这么简单,你学会了吗?
关注博智互联,不定时分享各类技术小技巧~