Example usage for javax.crypto AEADBadTagException getMessage

List of usage examples for javax.crypto AEADBadTagException getMessage

Introduction

In this page you can find the example usage for javax.crypto AEADBadTagException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.demandware.appsec.csrf.StatelessCSRFTokenManager.java

/**
 * Tests the given token id + string for validity. Also does internal checking of string to attempt to detect
 * tampering//  w  w  w . j av  a2 s  .  c o  m
 *
 * @param tokenId the random ID to use in key generation
 * @param sessionID the session of the current request
 * @param dataToCrypt (Optional) any other strings that should be used to validate the token. See class definition.
 * @param tokenString the token value to check against
 * @return true if the token is valid, false otherwise
 */
private boolean validateTokenInternal(String token, String sessionID, String... dataToCrypt) {
    boolean result = false;

    long timestamp = getCurrentTime();

    try {
        byte[] key = sessionID.getBytes(Charset.defaultCharset());

        byte[] tokenByte = decodeToken(token);
        byte[] iv = Arrays.copyOfRange(tokenByte, 0, TOKEN_SIZE);
        byte[] encryptedValue = Arrays.copyOfRange(tokenByte, TOKEN_SIZE, tokenByte.length);

        byte[] decrypted = crypt(key, iv, encryptedValue, Cipher.DECRYPT_MODE);
        String cryptText = new String(decrypted, "UTF-8");
        String[] decryptParts = cryptText.split(Pattern.quote(SEPARATOR));

        int cryptlen = dataToCrypt == null ? 0 : dataToCrypt.length;

        // 2 guaranteed pieces (session and timestamp) plus the additional data
        if (decryptParts.length == (2 + cryptlen)) {
            String decryptedSession = decryptParts[0];
            long decryptedTimestamp = Long.parseLong(decryptParts[1]);

            /*
             * verify sessions match verify that the timestamp in the 
             * token is within the permitted time allowance and verify 
             * all other possible data matches in order
             */
            if (!decryptedSession.equals(sessionID)) {
                String error = new StringBuilder().append("CSRF Token session ids don't match. Expected: ")
                        .append(sessionID).append("but received: ").append(decryptedSession).toString();

                this.handler.handleValidationError(error);
            } else if ((decryptedTimestamp + getAllowedExpiry()) < timestamp) {
                String error = new StringBuilder().append("CSRF Token has expired. Expected: ")
                        .append(timestamp).append(" but received: ").append(decryptedTimestamp).toString();

                this.handler.handleValidationError(error);
            } else if (cryptlen > 0) {
                for (int i = 0; i < cryptlen; i++) {
                    String decryptedData = decryptParts[2 + i];
                    String intendedData = dataToCrypt[i];
                    if (decryptedData.equals(intendedData)) {
                        result = true;
                    } else {
                        String error = new StringBuilder().append("CSRF Token data does not match. Excepted: ")
                                .append(intendedData).append(" but received: ").append(decryptedData)
                                .toString();

                        this.handler.handleValidationError(error);

                        result = false;

                        // if any fails, quit immediately
                        break;
                    }
                }
            } else {
                result = true;
            }
        }
    } catch (AEADBadTagException e) {
        String error = new StringBuilder().append("Could not validate token ").append(token)
                .append(" for different session ").append(sessionID).toString();

        this.handler.handleValidationError(error);
    } catch (Exception e) {
        String error = new StringBuilder().append("Could not validate token ").append(token)
                .append(" for session ").append(sessionID).append(" due to exception: ").append(e.getMessage())
                .toString();

        this.handler.handleFatalException(error, e);
    }

    return result;
}