Merge pull request #674 from joshiparthin/parth-md5

Parth md5
This commit is contained in:
Eugen 2016-09-29 14:20:32 +03:00 committed by GitHub
commit 50990c622f
2 changed files with 96 additions and 0 deletions

View File

@ -124,6 +124,12 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,90 @@
package org.baeldung.java.md5;
import static org.junit.Assert.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.codec.digest.DigestUtils;
import org.junit.Before;
import org.junit.Test;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import java.io.File;
import java.io.IOException;
import java.nio.*;
import static org.assertj.core.api.Assertions.assertThat;
public class JavaMD5Test {
String filename = "src/test/resources/test_md5.txt";
String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3";
String hash = "35454B055CC325EA1AF2126E27707052";
String password = "ILoveJava";
@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();
}
@Test
public void givenFile_generatingChecksum_thenVerifying() throws NoSuchAlgorithmException, IOException {
String filename = "src/test/resources/test_md5.txt";
String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3";
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(Files.readAllBytes(Paths.get(filename)));
byte[] digest = md.digest();
String myChecksum = DatatypeConverter
.printHexBinary(digest).toUpperCase();
assertThat(myChecksum.equals(checksum)).isTrue();
}
@Test
public void givenPassword_whenHashingUsingCommons_thenVerifying() {
String hash = "35454B055CC325EA1AF2126E27707052";
String password = "ILoveJava";
String md5Hex = DigestUtils
.md5Hex(password).toUpperCase();
assertThat(md5Hex.equals(hash)).isTrue();
}
@Test
public void givenFile_whenChecksumUsingGuava_thenVerifying() throws IOException {
String filename = "src/test/resources/test_md5.txt";
String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3";
HashCode hash = com.google.common.io.Files
.hash(new File(filename), Hashing.md5());
String myChecksum = hash.toString()
.toUpperCase();
assertThat(myChecksum.equals(checksum)).isTrue();
}
}