`
byf157
  • 浏览: 203220 次
  • 性别: Icon_minigender_1
  • 来自: 石家庄
社区版块
存档分类
最新评论

java md5 示例

    博客分类:
  • java
阅读更多

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

 

public class MD5 {

public static String MD5(String inStr) throws NoSuchAlgorithmException {

MessageDigest md5 = null;

md5 = MessageDigest.getInstance("MD5");

byte[] byteArray = inStr.getBytes();

 

byte[] md5Bytes = md5.digest(byteArray);

String str=byte2hex(md5Bytes);

return str;

}

 

private static String byte2hex(byte[] md5Bytes) {

StringBuffer hexValue = new StringBuffer();

int val=0;

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

val = ((int) md5Bytes[i]) & 0xff;

if (val < 16)

hexValue.append("0");

hexValue.append(Integer.toHexString(val));

}

return hexValue.toString();

}

 

// 测试主函数

public static void main(String args[]) throws NoSuchAlgorithmException {

String s = new String("a");

System.out.println("原始:" + s);

System.out.println("MD5后:" + MD5(s));

}

}

分享到:
评论
2 楼 byf157 2011-02-11  
Garfield.Geng 写道
上面的代码行太多了。应该用现成的。
/**
 * Test method for {@link org.springframework.util.DigestUtils#md5Digest(byte[])}.
 */
@Test
public void testMd5Digest() throws Exception {
    byte[] result = DigestUtils.md5Digest(bytes);
    byte[] expected = new byte[] { -0x4f, 0xa, -0x73, -0x4f, 0x64, -0x20, 0x75, 0x41, 0x5, -0x49, -0x57, -0x65,
            -0x19, 0x2e, 0x3f, -0x1b };
    assertArrayEquals("Invalid hash", expected, result);
}

有道理
1 楼 Garfield.Geng 2011-02-07  
上面的代码行太多了。应该用现成的。
/**
 * Test method for {@link org.springframework.util.DigestUtils#md5Digest(byte[])}.
 */
@Test
public void testMd5Digest() throws Exception {
    byte[] result = DigestUtils.md5Digest(bytes);
    byte[] expected = new byte[] { -0x4f, 0xa, -0x73, -0x4f, 0x64, -0x20, 0x75, 0x41, 0x5, -0x49, -0x57, -0x65,
            -0x19, 0x2e, 0x3f, -0x1b };
    assertArrayEquals("Invalid hash", expected, result);
}

相关推荐

Global site tag (gtag.js) - Google Analytics