java md5byte数组_java实现MD5加密方法汇总

代码一:

/**

* 实现MD5加密

*

*/

public class MD5 {

/**

* 获取加密后的字符串

* @param input

* @return

*/

public static String stringMD5(String pw) {

try {

// 拿到一个MD5转换器(如果想要SHA1参数换成”SHA1”)

MessageDigest messageDigest =MessageDigest.getInstance("MD5");

// 输入的字符串转换成字节数组

byte[] inputByteArray = pw.getBytes();

// inputByteArray是输入字符串转换得到的字节数组

messageDigest.update(inputByteArray);

// 转换并返回结果,也是字节数组,包含16个元素

byte[] resultByteArray = messageDigest.digest();

// 字符数组转换成字符串返回

return byteArrayToHex(resultByteArray);

} catch (NoSuchAlgorithmException e) {

return null;

}

}

public static String byteArrayToHex(byte[] byteArray) {

// 首先初始化一个字符数组,用来存放每个16进制字符

char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F' };

// new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方))

char[] resultCharArray =new char[byteArray.length * 2];

// 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去

int index = 0;

for (byte b : byteArray) {

resultCharArray[index++] = hexDigits[b>>> 4 & 0xf];

resultCharArray[index++] = hexDigits[b& 0xf];

}

// 字符数组组合成字符串返回

return new String(resultCharArray);

}

}

方法二:

package other;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

/*

* MD5 算法

*/

public class MD5 {

// 全局数组

private final static String[] strDigits = { "0", "1", "2", "3", "4", "5",

"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

public MD5() {

}

// 返回形式为数字跟字符串

private static String byteToArrayString(byte bByte) {

int iRet = bByte;

// System.out.println("iRet="+iRet);

if (iRet < 0) {

iRet += 256;

}

int iD1 = iRet / 16;

int iD2 = iRet % 16;

return strDigits[iD1] + strDigits[iD2];

}

// 返回形式只为数字

private static String byteToNum(byte bByte) {

int iRet = bByte;

System.out.println("iRet1=" + iRet);

if (iRet < 0) {

iRet += 256;

}

return String.valueOf(iRet);

}

// 转换字节数组为16进制字串

private static String byteToString(byte[] bByte) {

StringBuffer sBuffer = new StringBuffer();

for (int i = 0; i < bByte.length; i++) {

sBuffer.append(byteToArrayString(bByte[i]));

}

return sBuffer.toString();

}

public static String GetMD5Code(String strObj) {

String resultString = null;

try {

resultString = new String(strObj);

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

// md.digest() 该函数返回值为存放哈希值结果的byte数组

resultString = byteToString(md.digest(strObj.getBytes()));

} catch (NoSuchAlgorithmException ex) {

ex.printStackTrace();

}

return resultString;

}

public static void main(String[] args) {

MD5 getMD5 = new MD5();

System.out.println(getMD5.GetMD5Code("000000"));

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值