Java Code Examples for java.security.MessageDigest#isEqual()
The following examples show how to use
java.security.MessageDigest#isEqual() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MessageToken_v2.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
/** * Verifies the validity of checksum field * * @param data the application data * @param offset the offset where the data begins * @param len the length of the application data * * @throws GSSException if an error occurs in the checksum calculation */ public final boolean verifySign(byte[] data, int offset, int len) throws GSSException { // debug("\t====In verifySign:====\n"); // debug("\t\t checksum: [" + getHexBytes(checksum) + "]\n"); // debug("\t\t data = [" + getHexBytes(data) + "]\n"); byte[] myChecksum = getChecksum(data, offset, len); // debug("\t\t mychecksum: [" + getHexBytes(myChecksum) +"]\n"); if (MessageDigest.isEqual(checksum, myChecksum)) { // debug("\t\t====Checksum PASS:====\n"); return true; } return false; }
Example 2
Source File: AesCbcHmacJweDecryption.java From cxf with Apache License 2.0 | 6 votes |
protected void validateAuthenticationTag(JweDecryptionInput jweDecryptionInput, byte[] theCek) { byte[] actualAuthTag = jweDecryptionInput.getAuthTag(); final AesCbcHmacJweEncryption.MacState macState = AesCbcHmacJweEncryption.getInitializedMacState(theCek, jweDecryptionInput.getInitVector(), jweDecryptionInput.getAad(), jweDecryptionInput.getJweHeaders(), jweDecryptionInput.getDecodedJsonHeaders()); macState.mac.update(jweDecryptionInput.getEncryptedContent()); byte[] expectedAuthTag = AesCbcHmacJweEncryption.signAndGetTag(macState); if (!MessageDigest.isEqual(actualAuthTag, expectedAuthTag)) { LOG.warning("Invalid authentication tag"); throw new JweException(JweException.Error.CONTENT_DECRYPTION_FAILURE); } }
Example 3
Source File: MessageToken_v2.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
/** * Verifies the validity of checksum field * * @param data the application data * @param offset the offset where the data begins * @param len the length of the application data * * @throws GSSException if an error occurs in the checksum calculation */ public final boolean verifySign(byte[] data, int offset, int len) throws GSSException { // debug("\t====In verifySign:====\n"); // debug("\t\t checksum: [" + getHexBytes(checksum) + "]\n"); // debug("\t\t data = [" + getHexBytes(data) + "]\n"); byte[] myChecksum = getChecksum(data, offset, len); // debug("\t\t mychecksum: [" + getHexBytes(myChecksum) +"]\n"); if (MessageDigest.isEqual(checksum, myChecksum)) { // debug("\t\t====Checksum PASS:====\n"); return true; } return false; }
Example 4
Source File: UpdateApkReadyListener.java From mollyim-android with GNU General Public License v3.0 | 6 votes |
private boolean isMatchingDigest(Context context, long downloadId, String theirEncodedDigest) { try { if (theirEncodedDigest == null) return false; byte[] theirDigest = Hex.fromStringCondensed(theirEncodedDigest); DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); FileInputStream fin = new FileInputStream(downloadManager.openDownloadedFile(downloadId).getFileDescriptor()); byte[] ourDigest = FileUtils.getFileDigest(fin); fin.close(); return MessageDigest.isEqual(ourDigest, theirDigest); } catch (IOException e) { Log.w(TAG, e); return false; } }
Example 5
Source File: SecureSecretKeySpec.java From mollyim-android with GNU General Public License v3.0 | 6 votes |
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof SecretKey)) { return false; } String thatAlg = ((SecretKey)obj).getAlgorithm(); if (!(thatAlg.equalsIgnoreCase(this.algorithm))) { return false; } byte[] thatKey = ((SecretKey)obj).getEncoded(); return MessageDigest.isEqual(this.key, thatKey); }
Example 6
Source File: MessageToken_v2.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 6 votes |
/** * Verifies the validity of checksum field * * @param data the application data * @param offset the offset where the data begins * @param len the length of the application data * * @throws GSSException if an error occurs in the checksum calculation */ public final boolean verifySign(byte[] data, int offset, int len) throws GSSException { // debug("\t====In verifySign:====\n"); // debug("\t\t checksum: [" + getHexBytes(checksum) + "]\n"); // debug("\t\t data = [" + getHexBytes(data) + "]\n"); byte[] myChecksum = getChecksum(data, offset, len); // debug("\t\t mychecksum: [" + getHexBytes(myChecksum) +"]\n"); if (MessageDigest.isEqual(checksum, myChecksum)) { // debug("\t\t====Checksum PASS:====\n"); return true; } return false; }
Example 7
Source File: AESCrypt.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
void init(boolean decrypting, String algorithm, byte[] key) throws InvalidKeyException { if (!algorithm.equalsIgnoreCase("AES") && !algorithm.equalsIgnoreCase("Rijndael")) { throw new InvalidKeyException ("Wrong algorithm: AES or Rijndael required"); } if (!isKeySizeValid(key.length)) { throw new InvalidKeyException("Invalid AES key length: " + key.length + " bytes"); } if (!MessageDigest.isEqual(key, lastKey)) { // re-generate session key 'sessionK' when cipher key changes makeSessionKey(key); lastKey = key.clone(); // save cipher key } // set sub key to the corresponding session Key this.K = sessionK[(decrypting? 1:0)]; }
Example 8
Source File: MessageToken_v2.java From openjdk-8-source with GNU General Public License v2.0 | 6 votes |
/** * Verifies the validity of checksum field * * @param data the application data * @param offset the offset where the data begins * @param len the length of the application data * * @throws GSSException if an error occurs in the checksum calculation */ public final boolean verifySign(byte[] data, int offset, int len) throws GSSException { // debug("\t====In verifySign:====\n"); // debug("\t\t checksum: [" + getHexBytes(checksum) + "]\n"); // debug("\t\t data = [" + getHexBytes(data) + "]\n"); byte[] myChecksum = getChecksum(data, offset, len); // debug("\t\t mychecksum: [" + getHexBytes(myChecksum) +"]\n"); if (MessageDigest.isEqual(checksum, myChecksum)) { // debug("\t\t====Checksum PASS:====\n"); return true; } return false; }
Example 9
Source File: OzoneClientKeyValidator.java From hadoop-ozone with Apache License 2.0 | 5 votes |
private void validateDigest(String objectName, byte[] digest) { if (!MessageDigest.isEqual(referenceDigest, digest)) { throw new IllegalStateException( "Reference (=first) message digest doesn't match with digest of " + objectName); } }
Example 10
Source File: TestDelegatedKey.java From aws-dynamodb-encryption-java with Apache License 2.0 | 5 votes |
@Override public boolean verify(byte[] dataToSign, byte[] signature, String algorithm) { try { byte[] expected = sign(dataToSign, extractAlgorithm(algorithm)); return MessageDigest.isEqual(expected, signature); } catch (GeneralSecurityException ex) { return false; } }
Example 11
Source File: BitBucketCloudAuth.java From gocd with Apache License 2.0 | 5 votes |
default void validateAuth(String webhookSecret) { String token = getTokenFromHeader(request()); if (isBlank(token)) { throw die("No token specified via basic authentication!"); } if (!MessageDigest.isEqual(token.getBytes(), webhookSecret.getBytes())) { throw die("Token specified via basic authentication did not match!"); } if (!"git".equals(scmType())) { throw die("Only 'git' repositories are currently supported!"); } }
Example 12
Source File: User.java From fernet-java8 with Apache License 2.0 | 5 votes |
/** * @param singleRoundPasswordHash password that has been hashed once between the client and the server (Base 64 URL encoded) * @return true if and only if the password is correct */ public boolean isPasswordCorrect(final String singleRoundPasswordHash) { try { final MessageDigest digest = MessageDigest.getInstance("SHA-512"); digest.update(decoder.decode(singleRoundPasswordHash)); digest.update(decoder.decode(getSalt())); return MessageDigest.isEqual(digest.digest(), decoder.decode(getTwoRoundPasswordHash())); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException("Password hashing algorithm not found: " + e.getMessage(), e); } }
Example 13
Source File: GitHubAuth.java From gocd with Apache License 2.0 | 5 votes |
default void validateAuth(String secret) { String signature = request().headers("X-Hub-Signature"); if (isBlank(signature)) { throw die("No HMAC signature specified via 'X-Hub-Signature' header!"); } String expectedSignature = "sha1=" + new HmacUtils(HmacAlgorithms.HMAC_SHA_1, secret).hmacHex(request().body()); if (!MessageDigest.isEqual(expectedSignature.getBytes(), signature.getBytes())) { throw die("HMAC signature specified via 'X-Hub-Signature' did not match!"); } }
Example 14
Source File: TlsCertificateAuthorityServiceHandler.java From nifi with Apache License 2.0 | 5 votes |
@Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try { TlsCertificateAuthorityRequest tlsCertificateAuthorityRequest = objectMapper.readValue(new BoundedReader(request.getReader(), 1024 * 1024), TlsCertificateAuthorityRequest.class); if (!tlsCertificateAuthorityRequest.hasHmac()) { writeResponse(objectMapper, request, response, new TlsCertificateAuthorityResponse(HMAC_FIELD_MUST_BE_SET), Response.SC_BAD_REQUEST); return; } if (!tlsCertificateAuthorityRequest.hasCsr()) { writeResponse(objectMapper, request, response, new TlsCertificateAuthorityResponse(CSR_FIELD_MUST_BE_SET), Response.SC_BAD_REQUEST); return; } JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = TlsHelper.parseCsr(tlsCertificateAuthorityRequest.getCsr()); byte[] expectedHmac = TlsHelper.calculateHMac(token, jcaPKCS10CertificationRequest.getPublicKey()); if (MessageDigest.isEqual(expectedHmac, tlsCertificateAuthorityRequest.getHmac())) { String dn = jcaPKCS10CertificationRequest.getSubject().toString(); if (logger.isInfoEnabled()) { logger.info("Received CSR with DN " + dn); } X509Certificate x509Certificate = CertificateUtils.generateIssuedCertificate(dn, jcaPKCS10CertificationRequest.getPublicKey(), CertificateUtils.getExtensionsFromCSR(jcaPKCS10CertificationRequest), caCert, keyPair, signingAlgorithm, days); writeResponse(objectMapper, request, response, new TlsCertificateAuthorityResponse(TlsHelper.calculateHMac(token, caCert.getPublicKey()), TlsHelper.pemEncodeJcaObject(x509Certificate)), Response.SC_OK); return; } else { writeResponse(objectMapper, request, response, new TlsCertificateAuthorityResponse(FORBIDDEN), Response.SC_FORBIDDEN); return; } } catch (Exception e) { throw new ServletException("Server error"); } finally { baseRequest.setHandled(true); } }
Example 15
Source File: TestDigestIOStream.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
/** * Test DigestInputStream and DigestOutputStream digest function when use * same message digest object. * * @param algo * Message Digest algorithm * @param dataLength * plain test data length. * @exception Exception * throw unexpected exception */ public boolean testMDShare(String algo, int dataLength) throws Exception { MessageDigest mdCommon = MessageDigest.getInstance(algo); // Generate the DigestInputStream/DigestOutputStream object try (ByteArrayInputStream bais = new ByteArrayInputStream(data); DigestInputStream dis = new DigestInputStream(bais, mdCommon); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DigestOutputStream dos = new DigestOutputStream(baos, mdCommon);) { // Perform the update using all available/possible update methods int k = 0; byte[] buffer = new byte[10]; // use both read() and read(byte[], int, int) while (k < data.length) { int len = dis.read(buffer, 0, buffer.length); if (len != -1) { k += len; if (k < data.length) { dos.write(data[k]); k++; dis.skip(1); } } } // Get the output and the "correct" digest values byte[] output = mdCommon.digest(); byte[] standard = md.digest(data); // Compare generated digest values return MessageDigest.isEqual(output, standard); } catch (Exception ex) { out.println("TestMDShare failed at:" + algo + "/" + dataLength + " with unexpected exception"); throw ex; } }
Example 16
Source File: EciesEncryption.java From protect with MIT License | 5 votes |
public static byte[] decrypt(final byte[] ciphertext, final EcPoint sharedSecret) throws BadPaddingException, IllegalBlockSizeException { // Deserialize components of the ciphertext final byte[][] combined = Parse.splitArrays(ciphertext); if (combined.length != 3) { throw new BadPaddingException("Invalid ciphertext"); } final byte[] messageCiphertext = combined[1]; final byte[] macValue = combined[2]; // Setup key generator final HmacKeyDerivationFunction kdf = EntropyExtractor.getKeyGenerator(ECIES, sharedSecret); // Get cipher final Cipher aesGcmCipher = EntropyExtractor.getCipher(kdf, Cipher.DECRYPT_MODE); // Get hmac final byte[] hmacKey = kdf.createKey(HMAC, HMAC_KEY_LEN); try { final Mac hmac = Mac.getInstance(HMAC_ALG); hmac.init(new SecretKeySpec(hmacKey, HMAC_ALG)); // Verify the hmac value before proceeding final byte[] mac = hmac.doFinal(messageCiphertext); if (!MessageDigest.isEqual(macValue, mac)) { throw new BadPaddingException("Invalid HMAC!"); } } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new RuntimeException(e); } // Pperform decryption return aesGcmCipher.doFinal(messageCiphertext); }
Example 17
Source File: SCTCanceller.java From cxf with Apache License 2.0 | 5 votes |
private boolean matchDOMSignatureSecret( Map<String, Object> messageContext, byte[] secretToMatch ) { final List<WSHandlerResult> handlerResults = CastUtils.cast((List<?>) messageContext.get(WSHandlerConstants.RECV_RESULTS)); if (handlerResults != null && !handlerResults.isEmpty()) { WSHandlerResult handlerResult = handlerResults.get(0); List<WSSecurityEngineResult> signedResults = handlerResult.getActionResults().get(WSConstants.SIGN); if (signedResults != null) { for (WSSecurityEngineResult engineResult : signedResults) { byte[] receivedKey = (byte[])engineResult.get(WSSecurityEngineResult.TAG_SECRET); if (MessageDigest.isEqual(secretToMatch, receivedKey)) { LOG.log( Level.FINE, "Verification of the proof of possession of the key associated with " + "the security context successful." ); return true; } } } } return false; }
Example 18
Source File: MessageToken.java From dragonwell8_jdk with GNU General Public License v2.0 | 4 votes |
/** * Verifies that the checksum field and sequence number direction bytes * are valid and consistent with the application data. * * @param optionalHeader an optional header that will be processed first * during checksum calculation. * * @param data the application data * @param offset the offset where the data begins * @param len the length of the application data * * @param optionalTrailer an optional trailer that will be processed last * during checksum calculation. e.g., padding that should be appended to * the application data * * @throws GSSException if an error occurs in the checksum calculation or * encryption sequence number calculation. */ public final boolean verifySignAndSeqNumber(byte[] optionalHeader, byte[] data, int offset, int len, byte[] optionalTrailer) throws GSSException { // debug("\tIn verifySign:\n"); // debug("\t\tchecksum: [" + getHexBytes(checksum) + "]\n"); byte[] myChecksum = getChecksum(optionalHeader, data, offset, len, optionalTrailer); // debug("\t\tmychecksum: [" + getHexBytes(myChecksum) +"]\n"); // debug("\t\tchecksum: [" + getHexBytes(checksum) + "]\n"); if (MessageDigest.isEqual(checksum, myChecksum)) { seqNumberData = cipherHelper.decryptSeq( checksum, encSeqNumber, 0, 8); // debug("\t\tencSeqNumber: [" + getHexBytes(encSeqNumber) // + "]\n"); // debug("\t\tseqNumberData: [" + getHexBytes(seqNumberData) // + "]\n"); /* * The token from the initiator has direction bytes 0x00 and * the token from the acceptor has direction bytes 0xff. */ byte directionByte = 0; if (initiator) directionByte = (byte) 0xff; // Received token from acceptor if ((seqNumberData[4] == directionByte) && (seqNumberData[5] == directionByte) && (seqNumberData[6] == directionByte) && (seqNumberData[7] == directionByte)) return true; } return false; }
Example 19
Source File: HmacJwsSignatureVerifier.java From cxf with Apache License 2.0 | 4 votes |
@Override public boolean verify(byte[] signature) { byte[] macBytes = mac.doFinal(); return MessageDigest.isEqual(macBytes, signature); }
Example 20
Source File: MessageToken.java From openjdk-8 with GNU General Public License v2.0 | 4 votes |
/** * Verifies that the checksum field and sequence number direction bytes * are valid and consistent with the application data. * * @param optionalHeader an optional header that will be processed first * during checksum calculation. * * @param data the application data * @param offset the offset where the data begins * @param len the length of the application data * * @param optionalTrailer an optional trailer that will be processed last * during checksum calculation. e.g., padding that should be appended to * the application data * * @throws GSSException if an error occurs in the checksum calculation or * encryption sequence number calculation. */ public final boolean verifySignAndSeqNumber(byte[] optionalHeader, byte[] data, int offset, int len, byte[] optionalTrailer) throws GSSException { // debug("\tIn verifySign:\n"); // debug("\t\tchecksum: [" + getHexBytes(checksum) + "]\n"); byte[] myChecksum = getChecksum(optionalHeader, data, offset, len, optionalTrailer); // debug("\t\tmychecksum: [" + getHexBytes(myChecksum) +"]\n"); // debug("\t\tchecksum: [" + getHexBytes(checksum) + "]\n"); if (MessageDigest.isEqual(checksum, myChecksum)) { seqNumberData = cipherHelper.decryptSeq( checksum, encSeqNumber, 0, 8); // debug("\t\tencSeqNumber: [" + getHexBytes(encSeqNumber) // + "]\n"); // debug("\t\tseqNumberData: [" + getHexBytes(seqNumberData) // + "]\n"); /* * The token from the initiator has direction bytes 0x00 and * the token from the acceptor has direction bytes 0xff. */ byte directionByte = 0; if (initiator) directionByte = (byte) 0xff; // Received token from acceptor if ((seqNumberData[4] == directionByte) && (seqNumberData[5] == directionByte) && (seqNumberData[6] == directionByte) && (seqNumberData[7] == directionByte)) return true; } return false; }