/** * Returns true if the two parameters are equal. This method is null-safe and evaluates the * equality in constant-time rather than "short-circuiting" on the first inequality. This * prevents timing attacks (side channel attacks) when comparing passwords or hash values. * * @param a a byte[] to compare * @param b a byte[] to compare * @return true if the values are equal */ public static boolean constantTimeEquals(byte[] a, byte[] b) { return MessageDigest.isEqual(a, b); }
public boolean match(byte[] hashedBytes) { byte[] hashFromHex; try { hashFromHex = Util.fromHexString(value.hash); } catch (NumberFormatException e) { LOGGER.log(Level.INFO, "The API token with name=[{0}] is not in hex-format and so cannot be used", name); return false; } // String.equals() is not constant-time but this method is. No link between correctness and time spent return MessageDigest.isEqual(hashFromHex, hashedBytes); }
/** * {@inheritDoc} */ @Override public boolean validateCrumb(ServletRequest request, String salt, String crumb) { if (request instanceof HttpServletRequest) { String newCrumb = issueCrumb(request, salt); if ((newCrumb != null) && (crumb != null)) { // String.equals() is not constant-time, but this is return MessageDigest.isEqual(newCrumb.getBytes(Charset.forName("US-ASCII")), crumb.getBytes(Charset.forName("US-ASCII"))); } } return false; }
private boolean safeEquals (String a, String b) { byte[] aByteArray = a.getBytes(Charset.forName("UTF-8")); byte[] bByteArray = b.getBytes(Charset.forName("UTF-8")); return MessageDigest.isEqual(aByteArray, bByteArray); }
/** * Implements a time constant equality check. If either value is null, false is returned. * * @param value1 value1 * @param value2 value2 * @return if value1 equals value2 */ private boolean timeConstantEqualityCheck(final String value1, final String value2) { if (value1 == null || value2 == null) { return false; } return MessageDigest.isEqual(value1.getBytes(StandardCharsets.UTF_8), value2.getBytes(StandardCharsets.UTF_8)); } }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final CacheKey otherCacheKey = (CacheKey) o; return MessageDigest.isEqual(key.getBytes(StandardCharsets.UTF_8), otherCacheKey.key.getBytes(StandardCharsets.UTF_8)); }
public boolean isValid(String theirCodeString) { if (timestamp + TimeUnit.MINUTES.toMillis(30) < System.currentTimeMillis()) { return false; } byte[] ourCode = code.getBytes(); byte[] theirCode = theirCodeString.getBytes(); return MessageDigest.isEqual(ourCode, theirCode); } }
@Override public boolean isValid(byte[] data, byte[] signature) { byte[] computed = this.signer.sign(data); return MessageDigest.isEqual(computed, signature); } }
Security.addProvider(new BouncyCastleProvider()); String data = "hello world"; MessageDigest mda = MessageDigest.getInstance("SHA-512", "BC"); byte [] digesta = mda.digest(data.getBytes()); MessageDigest mdb = MessageDigest.getInstance("SHA-512", "BC"); byte [] digestb = mdb.digest(data.getBytes()); System.out.println(MessageDigest.isEqual(digesta, digestb)); System.out.println(Hex.encodeHex(digesta));
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AuthCredentials other = (AuthCredentials) obj; if (internalPasswordHash == null || other.internalPasswordHash == null || !MessageDigest.isEqual(internalPasswordHash, other.internalPasswordHash)) return false; if (username == null) { if (other.username != null) return false; } else if (!username.equals(other.username)) return false; return true; }
/** * Verify signature for JWT header and payload. * * @param algorithm algorithm name. * @param secretBytes algorithm secret. * @param header JWT header. * @param payload JWT payload. * @param signatureBytes JWT signature. * @return true if signature is valid. * @throws NoSuchAlgorithmException if the algorithm is not supported. * @throws InvalidKeyException if the given key is inappropriate for initializing the specified algorithm. */ boolean verifySignatureFor(String algorithm, byte[] secretBytes, byte[] headerBytes, byte[] payloadBytes, byte[] signatureBytes) throws NoSuchAlgorithmException, InvalidKeyException { return MessageDigest.isEqual(createSignatureFor(algorithm, secretBytes, headerBytes, payloadBytes), signatureBytes); }
/** * Verify signature. * * @param algorithm algorithm name. * @param secretBytes algorithm secret. * @param contentBytes the content to which the signature applies. * @param signatureBytes JWT signature. * @return true if signature is valid. * @throws NoSuchAlgorithmException if the algorithm is not supported. * @throws InvalidKeyException if the given key is inappropriate for initializing the specified algorithm. * @deprecated rather use corresponding method which takes header and payload as separate inputs */ @Deprecated boolean verifySignatureFor(String algorithm, byte[] secretBytes, byte[] contentBytes, byte[] signatureBytes) throws NoSuchAlgorithmException, InvalidKeyException { return MessageDigest.isEqual(createSignatureFor(algorithm, secretBytes, contentBytes), signatureBytes); }
public static boolean hmacMatches(byte[] hmac, byte[] data, byte[] secret, byte[] salt) throws Exception { return MessageDigest.isEqual(hmac, Crypto.hmac(data, secret, salt)); }
private boolean isValidSignature(String prefix, String suffix, Mac mac) { try { byte[] ourSuffix = Util.truncate(getHmac(key, prefix.getBytes(), mac), 10); byte[] theirSuffix = Hex.decodeHex(suffix.toCharArray()); return MessageDigest.isEqual(ourSuffix, theirSuffix); } catch (DecoderException e) { logger.warn("DirectoryCredentials", e); return false; } }
/** * Returns {@code true} if the specified object is a Hash and its {@link #getBytes byte array} is identical to * this Hash's byte array, {@code false} otherwise. * * @param o the object (Hash) to check for equality. * @return {@code true} if the specified object is a Hash and its {@link #getBytes byte array} is identical to * this Hash's byte array, {@code false} otherwise. */ public boolean equals(Object o) { if (o instanceof Hash) { Hash other = (Hash) o; return MessageDigest.isEqual(getBytes(), other.getBytes()); } return false; }
/** * Returns {@code true} if the specified object is a Hash and its {@link #getBytes byte array} is identical to * this Hash's byte array, {@code false} otherwise. * * @param o the object (Hash) to check for equality. * @return {@code true} if the specified object is a Hash and its {@link #getBytes byte array} is identical to * this Hash's byte array, {@code false} otherwise. */ public boolean equals(Object o) { if (o instanceof Hash) { Hash other = (Hash) o; return MessageDigest.isEqual(getBytes(), other.getBytes()); } return false; }
private byte[] validateServerSignature(final byte[] challenge) throws SaslException { String serverResponse = encodeUTF8(challenge); HashMap<String, String> map = parseServerResponse(serverResponse); if (!MessageDigest.isEqual(decodeBase64(map.get("v")), serverSignature)) { throw new SaslException("Server signature was invalid."); } return challenge; }
/** * Verifies that the given identifier and password are valid and match. * @param identifier Token identifier. * @param password Password in the token. * @throws InvalidToken */ public synchronized void verifyToken(TokenIdent identifier, byte[] password) throws InvalidToken { byte[] storedPassword = retrievePassword(identifier); if (!MessageDigest.isEqual(password, storedPassword)) { throw new InvalidToken("token " + formatTokenId(identifier) + " is invalid, password doesn't match"); } }
public static @CheckForNull User isConnectingUsingApiToken(String username, String tokenValue){ User user = User.getById(username, false); if(user == null){ ApiTokenPropertyConfiguration apiTokenConfiguration = GlobalConfiguration.all().getInstance(ApiTokenPropertyConfiguration.class); if(apiTokenConfiguration.isTokenGenerationOnCreationEnabled()){ String generatedTokenOnCreation = Util.getDigestOf(ApiTokenProperty.API_KEY_SEED.mac(username)); boolean areTokenEqual = MessageDigest.isEqual( generatedTokenOnCreation.getBytes(StandardCharsets.US_ASCII), tokenValue.getBytes(StandardCharsets.US_ASCII) ); if(areTokenEqual){ // directly return the user freshly created // and no need to check its token as the generated token // will be the same as the one we checked just above return User.getById(username, true); } } }else{ ApiTokenProperty t = user.getProperty(ApiTokenProperty.class); if (t!=null && t.matchesPassword(tokenValue)) { return user; } } return null; } }
private boolean validateRequest(final DigestContext context, final byte[] ha1) { byte[] ha2; DigestQop qop = context.getQop(); // Step 2.2 Calculate H(A2) if (qop == null || qop.equals(DigestQop.AUTH)) { ha2 = createHA2Auth(context, context.getParsedHeader()); } else { ha2 = createHA2AuthInt(); } byte[] requestDigest; if (qop == null) { requestDigest = createRFC2069RequestDigest(ha1, ha2, context); } else { requestDigest = createRFC2617RequestDigest(ha1, ha2, context); } byte[] providedResponse = context.getParsedHeader().get(DigestAuthorizationToken.RESPONSE).getBytes(StandardCharsets.UTF_8); return MessageDigest.isEqual(requestDigest, providedResponse); }