Hex Representation of a SHA-1 Digest of a String in Java (#14239)

* Hex Representation of a SHA-1 Digest of a String in Java

* Hex Representation of a SHA-1 Digest of a String in Java

* Hex Representation of a SHA-1 Digest of a String in Java
This commit is contained in:
Michael Olayemi 2023-06-20 15:47:00 +00:00 committed by GitHub
parent 11469c7c85
commit c4334bf328
2 changed files with 49 additions and 1 deletions

View File

@ -30,6 +30,11 @@
<artifactId>jaxb-api</artifactId>
<version>${jaxb-api.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${google-guava.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
@ -39,9 +44,10 @@
<properties>
<bouncycastle.version>1.70</bouncycastle.version>
<commons-codec.version>1.11</commons-codec.version>
<commons-codec.version>1.15</commons-codec.version>
<jaxb-api.version>2.3.1</jaxb-api.version>
<spring-security-crypto.version>6.0.3</spring-security-crypto.version>
<google-guava.version>31.0.1-jre</google-guava.version>
</properties>
</project>

View File

@ -0,0 +1,42 @@
package com.baeldung.crypto.sha1;
import static org.junit.jupiter.api.Assertions.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.digest.DigestUtils;
import org.junit.jupiter.api.Test;
import com.google.common.hash.Hashing;
public class HexRepresentationSha1DigestUnitTest {
String input = "Hello, World";
String expectedHexValue = "907d14fb3af2b0d4f18c2d46abe8aedce17367bd";
@Test
public void givenMessageDigest_whenUpdatingWithData_thenDigestShouldMatchExpectedValue() throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(input.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
byte[] digest = md.digest();
for (byte b : digest) {
hexString.append(String.format("%02x", b));
}
assertEquals(expectedHexValue, hexString.toString());
}
@Test
public void givenDigestUtils_whenCalculatingSHA1Hex_thenDigestShouldMatchExpectedValue() {
assertEquals(expectedHexValue, DigestUtils.sha1Hex(input));
}
@Test
public void givenHashingLibrary_whenCalculatingSHA1Hash_thenDigestShouldMatchExpectedValue() {
assertEquals(expectedHexValue, Hashing.sha1().hashString(input, StandardCharsets.UTF_8).toString());
}
}