Skip to content

Commit

Permalink
consolidate hash creation methods
Browse files Browse the repository at this point in the history
  • Loading branch information
jclausen committed Jan 13, 2024
1 parent 6859a1b commit 1624ecf
Showing 1 changed file with 60 additions and 6 deletions.
66 changes: 60 additions & 6 deletions src/main/java/ortus/boxlang/runtime/util/EncodingUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,44 @@

public final class EncodingUtil {

public static String checksum( Path filePath ) {
return checksum( filePath, "MD5" );
public static String DEFAULT_ALGORITHM = "MD5";

/**
* Performs a hash of a an object using the default algorithm
*
* @param object The object to be hashed
*
* @return returns the hashed string
*/
public static String hash( Object object ) {
return hash( object, DEFAULT_ALGORITHM );
}

public static String checksum( Path filePath, String algorithm ) {
StringBuilder result = new StringBuilder();
/**
* Performs a hash of an object using a supported algorithm
*
* @param byteArray the byte array representing the object
* @param algorithm The supported {@link java.security.MessageDigest } algorithm (case-insensitive)
*
* @return returns the hashed string
*/
public static String hash( Object object, String algorithm ) {
return hash( object.toString().getBytes(), algorithm );
}

/**
* Performs a hash of a byte array using a supported algorithm
*
* @param byteArray the byte array representing the object
* @param algorithm The supported {@link java.security.MessageDigest } algorithm (case-insensitive)
*
* @return returns the hashed string
*/
public static String hash( byte[] byteArray, String algorithm ) {
try {
MessageDigest md = MessageDigest.getInstance( algorithm.toUpperCase() );
md.update( Files.readAllBytes( filePath ) );
StringBuilder result = new StringBuilder();
MessageDigest md = MessageDigest.getInstance( algorithm.toUpperCase() );
md.update( byteArray );
byte[] digest = md.digest();
IntStream
.range( 0, digest.length )
Expand All @@ -33,6 +62,31 @@ public static String checksum( Path filePath, String algorithm ) {
algorithm.toUpperCase()
)
);
}
}

/**
* Peforms a checksum of a file path object using the MD5 algorithm
*
* @param filePath The {@link java.nio.file.Path} object
*
* @return returns the checksum string
*/
public static String checksum( Path filePath ) {
return checksum( filePath, DEFAULT_ALGORITHM );
}

/**
* Peforms a checksum of a file path object using a supported algorithm
*
* @param filePath The {@link java.nio.file.Path} object
* @param algorithm The supported {@link java.security.MessageDigest } algorithm (case-insensitive)
*
* @return returns the checksum string
*/
public static String checksum( Path filePath, String algorithm ) {
try {
return hash( Files.readAllBytes( filePath ) );
} catch ( IOException e ) {
throw new BoxIOException( e );
}
Expand Down

0 comments on commit 1624ecf

Please sign in to comment.