Skip to content

Commit

Permalink
Adding exception handling to log string value when decoding fails
Browse files Browse the repository at this point in the history
  • Loading branch information
Sumanth Pasupuleti authored and sumanth-pasupuleti committed Sep 6, 2019
1 parent 8dc826a commit 1941797
Showing 1 changed file with 21 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,18 @@
import java.util.zip.CRC32;
import java.util.zip.Checksum;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* @author Sumanth Pasupuleti
*
* CheckSumUtil contains methods around generation and validation of CRC32 based checksum
*/
public class CheckSumUtil
{
private static final Logger logger = LoggerFactory.getLogger(CheckSumUtil.class);

/**
* Generates a checksum of the input string or an abridged version of the input string (depending upon append param)
* and returns a base64 encoded string of the input string (or an abridged version of it) + checksum.
Expand Down Expand Up @@ -81,14 +86,22 @@ public static String appendCheckSumAndEncodeBase64(String inputString, boolean a
*/
public static boolean isChecksumValid(String encodedInput)
{
byte[] inputInBytes = Base64.getDecoder().decode(encodedInput);
// assumes last 8 bytes to be checksum and remaining bytes to be the original input string
byte[] extractedInputStringInBytes = Arrays.copyOfRange(inputInBytes, 0, inputInBytes.length - 8);
byte[] extractedChecksumInBytes = Arrays.copyOfRange(inputInBytes, inputInBytes.length - 8, inputInBytes.length);
try
{
byte[] inputInBytes = Base64.getDecoder().decode(encodedInput);
// assumes last 8 bytes to be checksum and remaining bytes to be the original input string
byte[] extractedInputStringInBytes = Arrays.copyOfRange(inputInBytes, 0, inputInBytes.length - 8);
byte[] extractedChecksumInBytes = Arrays.copyOfRange(inputInBytes, inputInBytes.length - 8, inputInBytes.length);

Checksum checksum = new CRC32();
checksum.update(extractedInputStringInBytes, 0, extractedInputStringInBytes.length);
byte[] generatedChecksumInBytes = ByteBuffer.allocate(Long.SIZE / Byte.SIZE).putLong(checksum.getValue()).array();
return Arrays.equals(extractedChecksumInBytes, generatedChecksumInBytes);
Checksum checksum = new CRC32();
checksum.update(extractedInputStringInBytes, 0, extractedInputStringInBytes.length);
byte[] generatedChecksumInBytes = ByteBuffer.allocate(Long.SIZE / Byte.SIZE).putLong(checksum.getValue()).array();
return Arrays.equals(extractedChecksumInBytes, generatedChecksumInBytes);
}
catch (Exception ex)
{
logger.error("Exception during checksum validation for encoded input string: {}", encodedInput, ex);
return false;
}
}
}

0 comments on commit 1941797

Please sign in to comment.