Skip to content

Commit

Permalink
replace usage of google Hashing with java built in MessageDigest
Browse files Browse the repository at this point in the history
  • Loading branch information
sclassen committed Jul 14, 2019
1 parent 1eee8a5 commit 5e3e68b
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@
import static com.dlsc.preferencesfx.util.Constants.WINDOW_WIDTH;

import com.dlsc.preferencesfx.model.Setting;
import com.google.common.hash.Hashing;
import com.google.gson.Gson;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
Expand Down Expand Up @@ -261,10 +259,7 @@ private String deprecatedHash(String key) {
* @return SHA-256 representation of breadcrumb
*/
public String hash(String key) {
Objects.requireNonNull(key);
return Hashing.sha256()
.hashString(key, StandardCharsets.UTF_8)
.toString();
return Strings.sha256(key);
}

public Preferences getPreferences() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,61 @@
package com.dlsc.preferencesfx.util;

import static java.util.Objects.requireNonNull;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
* Helper methods for working with strings.
*/
public class Strings {

private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray();

/**
* Checks if a string is null or empty.
*
* @param string the string to test, may be {@code null}.
* @return {@code true} iff the string is not null and not empty
*/
public static boolean isNullOrEmpty(String string) {
return string == null || string.isEmpty();
}

/**
* Calculates the SHA-256 digest of a string.
*
* @param string the string to digest, must not be {@code null}.
* @return the SHA-256 digest of the input string
*/
public static String sha256(String string) {
requireNonNull(string);
try {
final MessageDigest digest = MessageDigest.getInstance("sha-256");
final byte[] hash = digest.digest(string.getBytes(StandardCharsets.UTF_8));
return hexString(hash);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}

/**
* Calculates the HEX representation of a byte array.
*
* @param bytes the byte array, must not be {@code null}.
* @return the HEX representation of the byte array.
*/
public static String hexString(byte[] bytes) {
requireNonNull(bytes);
final int numBytes = bytes.length;
char[] hexChars = new char[numBytes * 2];
for (int i = 0; i < numBytes; i++) {
int v = bytes[i] & 0xFF;
hexChars[i * 2] = HEX_ARRAY[v >>> 4];
hexChars[(i * 2) + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}

}

0 comments on commit 5e3e68b

Please sign in to comment.