MD5、SM3数据摘要

/**
* 生成文件的MD5校验值
*
* @param file
* @return
* @throws
*/

public static String getMD5(String filePath) throws Exception {
File file = new File(filePath);
FileInputStream fis= new FileInputStream(file);
MessageDigest MD5 = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
MD5.update(buffer, 0, length);
}
fis.close();
return new String(Hex.encodeHex(MD5.digest()));
}
/**

*

* @param plainText

* 明文

* @return 32位密文

*/

public static String encryption(String plainText) {
String md5 = new String();

try {
MessageDigest md = MessageDigest.getInstance("MD5");

md.update(plainText.getBytes());

byte b[] = md.digest();

int i;

StringBuffer buf = new StringBuffer("");

for (int offset = 0; offset < b.length; offset++) {
i = b[offset];

if (i < 0)

i += 256;

if (i < 16)

buf.append("0");

buf.append(Integer.toHexString(i));

}

md5 = buf.toString();

} catch (NoSuchAlgorithmException e) {
e.printStackTrace();

}

return md5;

}

/**
* 生成文件的SM3校验值
*
* @param file
* @return
* @throws
*/
public static String getFileSM3String(File file) {
InputStream fis;
GeneralDigest digest = new SM3Digest();
String resultHexString = "";
try {
fis = new FileInputStream(file);

byte[] buffer = new byte[1024];
int numRead = 0;
while ((numRead = fis.read(buffer)) > 0) {
digest.update(buffer, 0, numRead);
}
fis.close();
byte[] hash = new byte[digest.getDigestSize()];

digest.doFinal(hash, 0);
resultHexString = ByteUtils.toHexString(hash);
}catch (Exception e){
e.printStackTrace();
}

return resultHexString;
}

你可能感兴趣的:(java,开发语言)