MD5 in JAVA

using Apache Commons

需要引入org.apache.commons.codec.digest.DigestUtils这个包,pom.xml文件配置如下:

<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.10</version>
</dependency>

 

demo代码如下:

@Test
public void givenPassword_whenHashingUsingCommons_thenVerifying()  {
    String hash = "35454B055CC325EA1AF2126E27707052";
    String password = "ILoveJava";
 
    String md5Hex = DigestUtils
      .md5Hex(password).toUpperCase();
         
    assertThat(md5Hex.equals(hash)).isTrue();
}

 

MD5 Using MessageDigest Class

jdk自带的,in java.security.MessageDigest Class

demo代码如下

@Test
public void givenPassword_whenHashing_thenVerifying() 
  throws NoSuchAlgorithmException {
    String hash = "35454B055CC325EA1AF2126E27707052";
    String password = "ILoveJava";
         
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(password.getBytes());
    byte[] digest = md.digest();
    String myHash = DatatypeConverter
      .printHexBinary(digest).toUpperCase();
         
    assertThat(myHash.equals(hash)).isTrue();
}

 

posted @ 2017-06-22 18:54  whendream  阅读(433)  评论(0编辑  收藏  举报