您的位置:首页 > 其它

md5工具类

2016-04-21 17:33 309 查看
public class MD5Utils {

/**

* md5加密方法

*

* @param string

* 需要md5的字符串

*/

public static String md5(String string) {

try {

// 得到一个信息摘要器

MessageDigest digest = MessageDigest.getInstance("md5");

byte[] result = digest.digest(string.getBytes());

StringBuffer buffer = new StringBuffer();

// 把没一个byte 做一个与运算 0xff;

for (byte b : result) {

// 与运算

int number = b & 0xff;// 加盐

String str = Integer.toHexString(number);

if (str.length() == 1) {

buffer.append("0");

}

buffer.append(str);

}

// 标准的md5加密后的结果

return buffer.toString();

} catch (NoSuchAlgorithmException e) {

// TODO Auto-generated catch block

e.printStackTrace();

return "";

}

}

/**

* MD5加密算法

*

* @param bytes

* 需要md5的字节数组

*/

public static String md5(byte[] bytes) {

if (bytes == null) {

return null;

}

StringBuffer sb = null;

try {

MessageDigest digest = MessageDigest.getInstance("md5");

byte[] bs = digest.digest(bytes);

sb = new StringBuffer();

// 把每一个byte做一次 与运算 0ff

for (byte b : bs) {

int num = b & 0xff;

String str = Integer.toHexString(num);

if (str.length() == 1) {

sb.append("0");

}

sb.append(str);

}

} catch (Exception e) {

e.printStackTrace();

}

return sb.toString();

}

/**

* 对一个文件进行MD5加密操作

*

* @param filePath

* 需要md5的文件路径

*/

public static String md5File(String filePath) throws Exception {

if (filePath == null) {

throw new IllegalArgumentException("文件路径不能为空");

}

File file = new File(filePath);

MessageDigest digest = MessageDigest.getInstance("md5");

FileInputStream fin = new FileInputStream(file);

byte[] buffer = new byte[1024];

int len = -1;

while ((len = fin.read(buffer)) != -1) {

digest.update(buffer, 0, len);

}

fin.close();

byte[] result = digest.digest();

StringBuffer sb = new StringBuffer();

// 把没一个byte 做一个与运算 0xff;

for (byte b : result) {

// 与运算

int number = b & 0xff;// 加盐

String str = Integer.toHexString(number);

if (str.length() == 1) {

sb.append("0");

}

sb.append(str);

}

// 标准的md5加密后的结果

return sb.toString();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: