@@ -15,3 +15,5 @@
|
||||
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
|
||||
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
|
||||
- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)
|
||||
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
|
||||
- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
### Relevant articles
|
||||
|
||||
- [Introduction to Apache Spark](http://www.baeldung.com/apache-spark)
|
||||
- [Building a Data Pipeline with Kafka, Spark Streaming and Cassandra](https://www.baeldung.com/kafka-spark-data-pipeline)
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.strings;
|
||||
|
||||
class Concatenate {
|
||||
String first = 'Hello'
|
||||
String last = 'Groovy'
|
||||
|
||||
String doSimpleConcat() {
|
||||
return 'My name is ' + first + ' ' + last
|
||||
}
|
||||
|
||||
String doConcatUsingGString() {
|
||||
return "My name is $first $last"
|
||||
}
|
||||
|
||||
String doConcatUsingGStringClosures() {
|
||||
return "My name is ${-> first} ${-> last}"
|
||||
}
|
||||
|
||||
String doConcatUsingStringConcatMethod() {
|
||||
return 'My name is '.concat(first).concat(' ').concat(last)
|
||||
}
|
||||
|
||||
String doConcatUsingLeftShiftOperator() {
|
||||
return 'My name is ' << first << ' ' << last
|
||||
}
|
||||
|
||||
String doConcatUsingArrayJoinMethod() {
|
||||
return ['My name is', first, last].join(' ')
|
||||
}
|
||||
|
||||
String doConcatUsingArrayInjectMethod() {
|
||||
return [first,' ', last]
|
||||
.inject(new StringBuffer('My name is '), { initial, name -> initial.append(name); return initial }).toString()
|
||||
}
|
||||
|
||||
String doConcatUsingStringBuilder() {
|
||||
return new StringBuilder().append('My name is ').append(first).append(' ').append(last)
|
||||
}
|
||||
|
||||
String doConcatUsingStringBuffer() {
|
||||
return new StringBuffer().append('My name is ').append(first).append(' ').append(last)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import com.baeldung.strings.Concatenate;
|
||||
|
||||
class ConcatenateTest extends GroovyTestCase {
|
||||
|
||||
void testSimpleConcat() {
|
||||
def name = new Concatenate()
|
||||
name.first = 'Joe';
|
||||
name.last = 'Smith';
|
||||
def expected = 'My name is Joe Smith'
|
||||
assertToString(name.doSimpleConcat(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingGString() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingGString(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingGStringClosures() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingGStringClosures(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingStringConcatMethod() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingStringConcatMethod(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingLeftShiftOperator() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingLeftShiftOperator(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingArrayJoinMethod() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingArrayJoinMethod(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingArrayInjectMethod() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingArrayInjectMethod(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingStringBuilder() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingStringBuilder(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingStringBuffer() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingStringBuffer(), expected)
|
||||
}
|
||||
|
||||
void testConcatMultilineUsingStringConcatMethod() {
|
||||
def name = new Concatenate()
|
||||
name.first = '''Joe
|
||||
Smith
|
||||
''';
|
||||
name.last = 'Junior';
|
||||
def expected = '''My name is Joe
|
||||
Smith
|
||||
Junior''';
|
||||
assertToString(name.doConcatUsingStringConcatMethod(), expected)
|
||||
}
|
||||
|
||||
void testGStringvsClosure(){
|
||||
def first = "Joe";
|
||||
def last = "Smith";
|
||||
def eagerGString = "My name is $first $last"
|
||||
def lazyGString = "My name is ${-> first} ${-> last}"
|
||||
|
||||
assert eagerGString == "My name is Joe Smith"
|
||||
assert lazyGString == "My name is Joe Smith"
|
||||
first = "David";
|
||||
assert eagerGString == "My name is Joe Smith"
|
||||
assert lazyGString == "My name is David Smith"
|
||||
}
|
||||
}
|
||||
@@ -3,3 +3,4 @@
|
||||
- [Java 11 Single File Source Code](https://www.baeldung.com/java-single-file-source-code)
|
||||
- [Java 11 Local Variable Syntax for Lambda Parameters](https://www.baeldung.com/java-var-lambda-params)
|
||||
- [Java 11 String API Additions](https://www.baeldung.com/java-11-string-api)
|
||||
- [Java 11 Nest Based Access Control](https://www.baeldung.com/java-nest-based-access-control)
|
||||
|
||||
@@ -39,6 +39,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
public class Java8CollectorsUnitTest {
|
||||
|
||||
private final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dd");
|
||||
private final List<String> listWithDuplicates = Arrays.asList("a", "bb", "c", "d", "bb");
|
||||
|
||||
@Test
|
||||
public void whenCollectingToList_shouldCollectToList() throws Exception {
|
||||
@@ -48,12 +49,19 @@ public class Java8CollectorsUnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToList_shouldCollectToSet() throws Exception {
|
||||
public void whenCollectingToSet_shouldCollectToSet() throws Exception {
|
||||
final Set<String> result = givenList.stream().collect(toSet());
|
||||
|
||||
assertThat(result).containsAll(givenList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenContainsDuplicateElements_whenCollectingToSet_shouldAddDuplicateElementsOnlyOnce() throws Exception {
|
||||
final Set<String> result = listWithDuplicates.stream().collect(toSet());
|
||||
|
||||
assertThat(result).hasSize(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
|
||||
final List<String> result = givenList.stream().collect(toCollection(LinkedList::new));
|
||||
@@ -83,6 +91,13 @@ public class Java8CollectorsUnitTest {
|
||||
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenContainsDuplicateElements_whenCollectingToMap_shouldThrowException() throws Exception {
|
||||
assertThatThrownBy(() -> {
|
||||
listWithDuplicates.stream().collect(toMap(Function.identity(), String::length));
|
||||
}).isInstanceOf(IllegalStateException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingAndThen_shouldCollect() throws Exception {
|
||||
final List<String> result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
||||
|
||||
@@ -26,3 +26,4 @@
|
||||
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
||||
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
|
||||
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)
|
||||
- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set)
|
||||
|
||||
@@ -14,3 +14,4 @@
|
||||
- [Array Operations in Java](http://www.baeldung.com/java-common-array-operations)
|
||||
- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection)
|
||||
- [Sorting Arrays in Java](https://www.baeldung.com/java-sorting-arrays)
|
||||
- [Convert a Float to a Byte Array in Java](https://www.baeldung.com/java-convert-float-to-byte-array)
|
||||
|
||||
@@ -36,6 +36,22 @@
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.sf.trove4j</groupId>
|
||||
<artifactId>trove4j</artifactId>
|
||||
<version>3.0.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>it.unimi.dsi</groupId>
|
||||
<artifactId>fastutil</artifactId>
|
||||
<version>8.1.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>colt</groupId>
|
||||
<artifactId>colt</artifactId>
|
||||
<version>1.2.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.list.primitive;
|
||||
|
||||
import com.google.common.primitives.ImmutableIntArray;
|
||||
import com.google.common.primitives.Ints;
|
||||
import gnu.trove.list.array.TIntArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.function.IntPredicate;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class PrimitiveCollections {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
int[] primitives = new int[] {5, 10, 0, 2, -8};
|
||||
|
||||
guavaPrimitives(primitives);
|
||||
|
||||
intStream(primitives);
|
||||
|
||||
TIntArrayList tList = new TIntArrayList(primitives);
|
||||
|
||||
cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList(primitives);
|
||||
|
||||
IntArrayList fastUtilList = new IntArrayList(primitives);
|
||||
|
||||
System.out.println(tList);
|
||||
|
||||
System.out.println(coltList);
|
||||
|
||||
System.out.println(fastUtilList);
|
||||
}
|
||||
|
||||
private static void intStream(int[] primitives) {
|
||||
|
||||
IntStream stream = IntStream.of(5, 10, 0, 2, -8);
|
||||
|
||||
IntStream newStream = IntStream.of(primitives);
|
||||
|
||||
OptionalDouble average = stream.filter(i -> i > 0).average();
|
||||
}
|
||||
|
||||
|
||||
private static void guavaPrimitives(int[] primitives) {
|
||||
|
||||
ImmutableIntArray immutableIntArray = ImmutableIntArray.builder().addAll(primitives).build();
|
||||
System.out.println(immutableIntArray);
|
||||
}
|
||||
}
|
||||
@@ -31,3 +31,4 @@
|
||||
- [A Guide to EnumMap](https://www.baeldung.com/java-enum-map)
|
||||
- [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator)
|
||||
- [Differences Between HashMap and Hashtable](https://www.baeldung.com/hashmap-hashtable-differences)
|
||||
- [Java ArrayList vs Vector](https://www.baeldung.com/java-arraylist-vs-vector)
|
||||
|
||||
@@ -36,4 +36,7 @@
|
||||
- [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array)
|
||||
- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader)
|
||||
- [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension)
|
||||
- [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type)
|
||||
- [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type)
|
||||
- [Create a Directory in Java](https://www.baeldung.com/java-create-directory)
|
||||
- [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv)
|
||||
- [List Files in a Directory in Java](https://www.baeldung.com/java-list-directory-files)
|
||||
|
||||
@@ -16,4 +16,5 @@
|
||||
- [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system)
|
||||
- [Java Switch Statement](https://www.baeldung.com/java-switch)
|
||||
- [The Modulo Operator in Java](https://www.baeldung.com/modulo-java)
|
||||
- [Ternary Operator In Java](https://www.baeldung.com/java-ternary-operator)
|
||||
- [Ternary Operator In Java](https://www.baeldung.com/java-ternary-operator)
|
||||
- [Java instanceof Operator](https://www.baeldung.com/java-instanceof)
|
||||
|
||||
@@ -34,4 +34,10 @@
|
||||
- [“Sneaky Throws” in Java](http://www.baeldung.com/java-sneaky-throws)
|
||||
- [Retrieving a Class Name in Java](https://www.baeldung.com/java-class-name)
|
||||
- [Java Compound Operators](https://www.baeldung.com/java-compound-operators)
|
||||
- [Guide to Java Packages](https://www.baeldung.com/java-packages)
|
||||
- [Guide to Java Packages](https://www.baeldung.com/java-packages)
|
||||
- [The Java Native Keyword and Methods](https://www.baeldung.com/java-native)
|
||||
- [If-Else Statement in Java](https://www.baeldung.com/java-if-else)
|
||||
- [Control Structures in Java](https://www.baeldung.com/java-control-structures)
|
||||
- [Java Interfaces](https://www.baeldung.com/java-interfaces)
|
||||
- [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values)
|
||||
- [Variable Scope in Java](https://www.baeldung.com/java-variable-scope)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.variable.scope.examples;
|
||||
package com.baeldung.scope;
|
||||
|
||||
public class BracketScopeExample {
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.variable.scope.examples;
|
||||
package com.baeldung.scope;
|
||||
|
||||
public class ClassScopeExample {
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.variable.scope.examples;
|
||||
package com.baeldung.scope;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.variable.scope.examples;
|
||||
package com.baeldung.scope;
|
||||
|
||||
public class MethodScopeExample {
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.variable.scope.examples;
|
||||
package com.baeldung.scope;
|
||||
|
||||
public class NestedScopesExample {
|
||||
|
||||
|
||||
+27
-2
@@ -1,18 +1,43 @@
|
||||
package com.baeldung.java.enumiteration;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class EnumIterationExamples {
|
||||
public static void main(String[] args) {
|
||||
System.out.println("Enum iteration using forEach:");
|
||||
System.out.println("Enum iteration using EnumSet:");
|
||||
EnumSet.allOf(DaysOfWeekEnum.class).forEach(day -> System.out.println(day));
|
||||
|
||||
System.out.println("Enum iteration using Stream:");
|
||||
DaysOfWeekEnum.stream().filter(d -> d.getTypeOfDay().equals("off")).forEach(System.out::println);
|
||||
|
||||
System.out.println("Enum iteration using for loop:");
|
||||
System.out.println("Enum iteration using a for loop:");
|
||||
for (DaysOfWeekEnum day : DaysOfWeekEnum.values()) {
|
||||
System.out.println(day);
|
||||
}
|
||||
|
||||
System.out.println("Enum iteration using Arrays.asList():");
|
||||
Arrays.asList(DaysOfWeekEnum.values()).forEach(day -> System.out.println(day));
|
||||
|
||||
System.out.println("Add Enum values to ArrayList:");
|
||||
List<DaysOfWeekEnum> days = new ArrayList<>();
|
||||
days.add(DaysOfWeekEnum.FRIDAY);
|
||||
days.add(DaysOfWeekEnum.SATURDAY);
|
||||
days.add(DaysOfWeekEnum.SUNDAY);
|
||||
for (DaysOfWeekEnum day : days) {
|
||||
System.out.println(day);
|
||||
}
|
||||
System.out.println("Remove SATURDAY from the list:");
|
||||
days.remove(DaysOfWeekEnum.SATURDAY);
|
||||
if (!days.contains(DaysOfWeekEnum.SATURDAY)) {
|
||||
System.out.println("Saturday is no longer in the list");
|
||||
}
|
||||
for (DaysOfWeekEnum day : days) {
|
||||
System.out.println(day);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,4 +5,5 @@
|
||||
- [Different Ways to Capture Java Heap Dumps](https://www.baeldung.com/java-heap-dump-capture)
|
||||
- [Understanding Memory Leaks in Java](https://www.baeldung.com/java-memory-leaks)
|
||||
- [OutOfMemoryError: GC Overhead Limit Exceeded](http://www.baeldung.com/java-gc-overhead-limit-exceeded)
|
||||
- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions)
|
||||
- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions)
|
||||
- [Monitoring Java Applications with Flight Recorder](https://www.baeldung.com/java-flight-recorder-monitoring)
|
||||
|
||||
@@ -8,4 +8,5 @@
|
||||
- [Encrypting and Decrypting Files in Java](http://www.baeldung.com/java-cipher-input-output-stream)
|
||||
- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing)
|
||||
- [SSL Handshake Failures](https://www.baeldung.com/java-ssl-handshake-failures)
|
||||
- [SHA-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java)
|
||||
- [SHA-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java)
|
||||
- [Enabling TLS v1.2 in Java 7](https://www.baeldung.com/java-7-tls-v12)
|
||||
|
||||
@@ -44,8 +44,8 @@
|
||||
|
||||
<!-- util -->
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<bouncycastle.version>1.55</bouncycastle.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
<bouncycastle.version>1.60</bouncycastle.version>
|
||||
<commons-codec.version>1.11</commons-codec.version>
|
||||
|
||||
<!-- testing -->
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.hashing;
|
||||
|
||||
public class DigestAlgorithms {
|
||||
|
||||
public static final String SHA3_256 = "SHA3-256";
|
||||
public static final String SHA_256 = "SHA-256";
|
||||
public static final String KECCAK_256 = "Keccak-256";
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.hashing;
|
||||
|
||||
import org.bouncycastle.jcajce.provider.digest.Keccak;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
import org.bouncycastle.util.encoders.Hex;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.Security;
|
||||
|
||||
import static com.baeldung.hashing.DigestAlgorithms.KECCAK_256;
|
||||
import static com.baeldung.hashing.SHACommonUtils.bytesToHex;
|
||||
|
||||
public class Keccak256Hashing {
|
||||
|
||||
public static String hashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException {
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
final MessageDigest digest = MessageDigest.getInstance(KECCAK_256);
|
||||
final byte[] encodedhash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
|
||||
return bytesToHex(encodedhash);
|
||||
}
|
||||
|
||||
public static String hashWithBouncyCastle(final String originalString) {
|
||||
Keccak.Digest256 digest256 = new Keccak.Digest256();
|
||||
byte[] hashbytes = digest256.digest(originalString.getBytes(StandardCharsets.UTF_8));
|
||||
return new String(Hex.encode(hashbytes));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -8,15 +8,18 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
import static com.baeldung.hashing.DigestAlgorithms.SHA_256;
|
||||
import static com.baeldung.hashing.SHACommonUtils.bytesToHex;
|
||||
|
||||
public class SHA256Hashing {
|
||||
|
||||
public static String HashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException {
|
||||
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
final MessageDigest digest = MessageDigest.getInstance(SHA_256);
|
||||
final byte[] encodedhash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
|
||||
return bytesToHex(encodedhash);
|
||||
}
|
||||
|
||||
public static String HashWithGuava(final String originalString) {
|
||||
public static String hashWithGuava(final String originalString) {
|
||||
final String sha256hex = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
|
||||
return sha256hex;
|
||||
}
|
||||
@@ -27,20 +30,10 @@ public class SHA256Hashing {
|
||||
}
|
||||
|
||||
public static String HashWithBouncyCastle(final String originalString) throws NoSuchAlgorithmException {
|
||||
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
final MessageDigest digest = MessageDigest.getInstance(SHA_256);
|
||||
final byte[] hash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
|
||||
final String sha256hex = new String(Hex.encode(hash));
|
||||
return sha256hex;
|
||||
}
|
||||
|
||||
private static String bytesToHex(byte[] hash) {
|
||||
StringBuffer hexString = new StringBuffer();
|
||||
for (int i = 0; i < hash.length; i++) {
|
||||
String hex = Integer.toHexString(0xff & hash[i]);
|
||||
if (hex.length() == 1)
|
||||
hexString.append('0');
|
||||
hexString.append(hex);
|
||||
}
|
||||
return hexString.toString();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.hashing;
|
||||
|
||||
import com.google.common.hash.Hashing;
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.bouncycastle.crypto.digests.SHA3Digest;
|
||||
import org.bouncycastle.jcajce.provider.digest.SHA3;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
import org.bouncycastle.util.encoders.Hex;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.Security;
|
||||
|
||||
import static com.baeldung.hashing.DigestAlgorithms.SHA3_256;
|
||||
import static com.baeldung.hashing.SHACommonUtils.bytesToHex;
|
||||
|
||||
public class SHA3Hashing {
|
||||
|
||||
/* works with JDK9+ only */
|
||||
public static String hashWithJavaMessageDigestJDK9(final String originalString) throws NoSuchAlgorithmException {
|
||||
final MessageDigest digest = MessageDigest.getInstance(SHA3_256);
|
||||
final byte[] hashbytes = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
|
||||
return bytesToHex(hashbytes);
|
||||
}
|
||||
|
||||
public static String hashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException {
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
final MessageDigest digest = MessageDigest.getInstance(SHA3_256);
|
||||
final byte[] hashbytes = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
|
||||
return bytesToHex(hashbytes);
|
||||
}
|
||||
|
||||
/* works with JDK9+ only */
|
||||
public static String hashWithApacheCommonsJDK9(final String originalString) {
|
||||
return new DigestUtils(SHA3_256).digestAsHex(originalString);
|
||||
}
|
||||
|
||||
public static String hashWithBouncyCastle(final String originalString) {
|
||||
SHA3.Digest256 digest256 = new SHA3.Digest256();
|
||||
byte[] hashbytes = digest256.digest(originalString.getBytes(StandardCharsets.UTF_8));
|
||||
return new String(Hex.encode(hashbytes));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.hashing;
|
||||
|
||||
class SHACommonUtils {
|
||||
|
||||
public static String bytesToHex(byte[] hash) {
|
||||
StringBuffer hexString = new StringBuffer();
|
||||
for (byte h : hash) {
|
||||
String hex = Integer.toHexString(0xff & h);
|
||||
if (hex.length() == 1)
|
||||
hexString.append('0');
|
||||
hexString.append(hex);
|
||||
}
|
||||
return hexString.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.hashing;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class Keccak256HashingUnitTest {
|
||||
|
||||
private static String originalValue = "abc123";
|
||||
private static String hashedValue = "719accc61a9cc126830e5906f9d672d06eab6f8597287095a2c55a8b775e7016";
|
||||
|
||||
@Test public void testHashWithJavaMessageDigest() throws Exception {
|
||||
final String currentHashedValue = Keccak256Hashing.hashWithJavaMessageDigest(originalValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
|
||||
@Test public void testHashWithBouncyCastle() {
|
||||
final String currentHashedValue = Keccak256Hashing.hashWithBouncyCastle(originalValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user