Example usage for java.security MessageDigest isEqual

List of usage examples for java.security MessageDigest isEqual

Introduction

In this page you can find the example usage for java.security MessageDigest isEqual.

Prototype

public static boolean isEqual(byte[] digesta, byte[] digestb) 

Source Link

Document

Compares two digests for equality.

Usage

From source file:org.apache.nifi.toolkit.tls.service.server.TlsCertificateAuthorityServiceHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    try {//from   w  w w  .j  a  va2 s . co m
        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);
    }
}

From source file:org.cryptomator.crypto.aes256.AesSivCipherUtil.java

static byte[] sivDecrypt(byte[] aesKey, byte[] macKey, byte[] ciphertext, byte[]... additionalData)
        throws DecryptFailedException, InvalidKeyException {
    if (aesKey.length != 16 && aesKey.length != 24 && aesKey.length != 32) {
        throw new InvalidKeyException("Invalid aesKey length " + aesKey.length);
    }//  w ww. ja v a  2  s. co  m

    final byte[] iv = Arrays.copyOf(ciphertext, 16);

    final byte[] actualCiphertext = Arrays.copyOfRange(ciphertext, 16, ciphertext.length);
    final int numBlocks = (actualCiphertext.length + 15) / 16;

    // clear out the 31st and 63rd (rightmost) bit:
    final byte[] ctr = Arrays.copyOf(iv, 16);
    ctr[8] = (byte) (ctr[8] & 0x7F);
    ctr[12] = (byte) (ctr[12] & 0x7F);
    final ByteBuffer ctrBuf = ByteBuffer.wrap(ctr);
    final long initialCtrVal = ctrBuf.getLong(8);

    final byte[] x = new byte[numBlocks * 16];
    final BlockCipher aes = new AESFastEngine();
    aes.init(true, new KeyParameter(aesKey));
    for (int i = 0; i < numBlocks; i++) {
        final long ctrVal = initialCtrVal + i;
        ctrBuf.putLong(8, ctrVal);
        aes.processBlock(ctrBuf.array(), 0, x, i * 16);
        aes.reset();
    }

    final byte[] plaintext = xor(actualCiphertext, x);

    final byte[] control = s2v(macKey, plaintext, additionalData);

    if (MessageDigest.isEqual(control, iv)) {
        return plaintext;
    } else {
        throw new DecryptFailedException("Authentication failed");
    }
}

From source file:com.qut.middleware.metadata.source.impl.MetadataSourceBase.java

protected boolean updateDigest(byte[] newDigest) {
    // Construct string from both digests to form log statement
    String newDigestString = new String(Hex.encodeHex(newDigest));
    String digestString = new String(Hex.encodeHex(this.digest));
    this.logger.debug("Metadata source {} - comparing new digest {} to previous {}.",
            new Object[] { this.getLocation(), newDigestString, digestString });

    // Compare and update
    if (!MessageDigest.isEqual(this.digest, newDigest)) {
        this.digest = newDigest;

        this.logger.info(
                "Metadata source {} - document has been updated and will be updated in the cache. New hash: {}. Old hash: {}",
                new Object[] { this.getLocation(), newDigestString, digestString });

        return true;
    }/*from   w  ww  . j av a  2 s . com*/

    return false;
}

From source file:com.bennavetta.appsite.webapi.ContentController.java

/**
 * Given a list of files and their MD5 hashes, calculate which ones are the same on the server, which ones should be uploaded,
 * and which ones should be deleted on the server (via a delete request).
 * @param files/*from   w w  w. j a  v  a  2s .co  m*/
 * @return
 */
@RequestMapping(value = "/diff", method = RequestMethod.POST)
@ResponseBody
public DiffResponse calculateDiff(@RequestBody List<DiffFile> files) {
    List<String> same = new ArrayList<>();
    List<String> different = new ArrayList<>();
    List<String> extra = new ArrayList<>();

    for (DiffFile file : files) {
        Resource onServer = Resource.get(file.getPath());
        if (onServer == null) {
            different.add(file.getPath());
            continue;
        }
        if (MessageDigest.isEqual(file.getMd5(), onServer.getMD5())) {
            same.add(file.getPath());
        } else {
            different.add(file.getPath());
        }
    }

    //TODO: find a better way of doing this?
    for (String path : Resource.allResources()) {
        if (!Iterables.all(files, new PathMatches(path))) //add the path to extras if none of the files match it
        {
            extra.add(path);
        }
    }

    DiffResponse response = new DiffResponse();
    response.setDifferent(different);
    response.setExtra(extra);
    response.setSame(same);
    return response;
}

From source file:org.apache.nifi.scripting.ScriptFactory.java

/**
 * @param aScriptFileName//www.ja  va  2s  . co m
 * @param properties
 * @param flowFile
 * @return
 * @throws IOException
 * @throws ScriptException
 */
public Script getScript(final String aScriptFileName, final Map<String, String> properties,
        final FlowFile flowFile) throws IOException, ScriptException {
    final Script instance;
    long now = System.currentTimeMillis();
    readLock.lock();
    try {
        if (!aScriptFileName.equals(this.scriptFileName)) {
            readLock.unlock();
            writeLock.lock();
            try {
                if (!aScriptFileName.equals(this.scriptFileName)) {
                    // need to get brand new engine
                    compiledScript = null;
                    this.md5Hash = getMD5Hash(aScriptFileName);
                    this.lastTimeChecked = now;
                    this.scriptFileName = aScriptFileName;
                    updateEngine();
                } // else another thread beat me to the change...so just get a script
            } finally {
                readLock.lock();
                writeLock.unlock();
            }
        } else if (lastTimeChecked + scriptCheckIntervalMS < now) {
            readLock.unlock();
            writeLock.lock();
            try {
                if (lastTimeChecked + scriptCheckIntervalMS < now) {
                    byte[] md5 = getMD5Hash(this.scriptFileName);
                    if (!MessageDigest.isEqual(md5Hash, md5)) {
                        // need to get brand new engine
                        compiledScript = null;
                        updateEngine();
                        this.md5Hash = md5;
                    } // else no change to script, so just update time checked
                    this.lastTimeChecked = now;
                } // else another thread beat me to the check...so just get a script
            } finally {
                readLock.lock();
                writeLock.unlock();
            }
        }
        try {
            instance = getScriptInstance(properties);
            instance.setFileName(this.scriptFileName);
            instance.setProperties(properties);
            instance.setLogger(logger);
            instance.setFlowFile(flowFile);
        } catch (ScriptException e) {
            // need to reset state to enable re-initialization
            this.lastTimeChecked = 0;
            this.scriptFileName = null;
            throw e;
        }
    } finally {
        readLock.unlock();
    }

    return instance;

}

From source file:jenkins.security.ApiTokenProperty.java

public boolean matchesPassword(String password) {
    String token = getApiTokenInsecure();
    // String.equals isn't constant time, but this is
    return MessageDigest.isEqual(password.getBytes(Charset.forName("US-ASCII")),
            token.getBytes(Charset.forName("US-ASCII")));
}

From source file:org.xdi.oxauth.model.jws.RSASigner.java

@Override
public boolean validateSignature(String signingInput, String signature) throws SignatureException {
    if (getSignatureAlgorithm() == null) {
        throw new SignatureException("The signature algorithm is null");
    }/*from  ww  w .  ja  v  a  2s .c  om*/
    if (rsaPublicKey == null) {
        throw new SignatureException("The RSA public key is null");
    }
    if (signingInput == null) {
        throw new SignatureException("The signing input is null");
    }

    String algorithm = null;
    switch (getSignatureAlgorithm()) {
    case RS256:
        algorithm = "SHA-256";
        break;
    case RS384:
        algorithm = "SHA-384";
        break;
    case RS512:
        algorithm = "SHA-512";
        break;
    default:
        throw new SignatureException("Unsupported signature algorithm");
    }

    ASN1InputStream aIn = null;
    try {
        byte[] sigBytes = JwtUtil.base64urldecode(signature);
        byte[] sigInBytes = signingInput.getBytes(Util.UTF8_STRING_ENCODING);

        RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(rsaPublicKey.getModulus(),
                rsaPublicKey.getPublicExponent());

        KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
        PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec);

        Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
        cipher.init(Cipher.DECRYPT_MODE, publicKey);

        byte[] decSig = cipher.doFinal(sigBytes);
        aIn = new ASN1InputStream(decSig);

        ASN1Sequence seq = (ASN1Sequence) aIn.readObject();

        MessageDigest hash = MessageDigest.getInstance(algorithm, "BC");
        hash.update(sigInBytes);

        ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
        return MessageDigest.isEqual(hash.digest(), sigHash.getOctets());
    } catch (IOException e) {
        throw new SignatureException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new SignatureException(e);
    } catch (InvalidKeyException e) {
        throw new SignatureException(e);
    } catch (InvalidKeySpecException e) {
        throw new SignatureException(e);
    } catch (NoSuchPaddingException e) {
        throw new SignatureException(e);
    } catch (BadPaddingException e) {
        throw new SignatureException(e);
    } catch (NoSuchProviderException e) {
        throw new SignatureException(e);
    } catch (IllegalBlockSizeException e) {
        throw new SignatureException(e);
    } catch (Exception e) {
        throw new SignatureException(e);
    } finally {
        IOUtils.closeQuietly(aIn);
    }
}

From source file:edu.usf.cutr.gtfsrtvalidator.background.BackgroundTask.java

@Override
public void run() {
    try {/*from   w ww.j  av  a 2 s . co  m*/
        long startTimeNanos = System.nanoTime();
        GtfsRealtime.FeedMessage currentFeedMessage;
        GtfsRealtime.FeedMessage previousFeedMessage = null;
        GtfsDaoImpl gtfsData;
        GtfsMetadata gtfsMetadata;

        // Holds data needed in the database under each iteration
        GtfsRtFeedIterationModel feedIteration;

        // Get the GTFS feed from the GtfsDaoMap using the gtfsFeedId of the current feed.
        gtfsData = GtfsFeed.GtfsDaoMap.get(mCurrentGtfsRtFeed.getGtfsFeedModel().getFeedId());
        // Create the GTFS metadata if it doesn't already exist
        gtfsMetadata = mGtfsMetadata.computeIfAbsent(mCurrentGtfsRtFeed.getGtfsFeedModel().getFeedId(),
                k -> new GtfsMetadata(mCurrentGtfsRtFeed.getGtfsFeedModel().getGtfsUrl(),
                        TimeZone.getTimeZone(mCurrentGtfsRtFeed.getGtfsFeedModel().getAgency()), gtfsData));

        // Read the GTFS-rt feed from the feed URL
        URL gtfsRtFeedUrl;
        Session session;
        try {
            gtfsRtFeedUrl = new URL(mCurrentGtfsRtFeed.getGtfsUrl());
        } catch (MalformedURLException e) {
            _log.error("Malformed Url: " + mCurrentGtfsRtFeed.getGtfsUrl(), e);
            e.printStackTrace();
            return;
        }

        try {
            // Get the GTFS-RT feedMessage for this method
            InputStream in = gtfsRtFeedUrl.openStream();
            byte[] gtfsRtProtobuf = IOUtils.toByteArray(in);

            boolean isUniqueFeed = true;
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] prevFeedDigest = null;
            byte[] currentFeedDigest = md.digest(gtfsRtProtobuf);

            session = GTFSDB.initSessionBeginTrans();
            feedIteration = (GtfsRtFeedIterationModel) session
                    .createQuery("FROM GtfsRtFeedIterationModel" + " WHERE rtFeedId = "
                            + mCurrentGtfsRtFeed.getGtfsRtId() + " ORDER BY IterationId DESC")
                    .setMaxResults(1).uniqueResult();
            if (feedIteration != null) {
                prevFeedDigest = feedIteration.getFeedHash();
            }

            if (MessageDigest.isEqual(currentFeedDigest, prevFeedDigest)) {
                // If previous feed digest and newly fetched/current feed digest are equal means, we received the same feed again.
                isUniqueFeed = false;
            }

            InputStream is = new ByteArrayInputStream(gtfsRtProtobuf);
            currentFeedMessage = GtfsRealtime.FeedMessage.parseFrom(is);

            long feedTimestamp = TimeUnit.SECONDS.toMillis(currentFeedMessage.getHeader().getTimestamp());

            // Create new feedIteration object and save the iteration to the database
            if (isUniqueFeed) {
                if (feedIteration != null && feedIteration.getFeedprotobuf() != null) {
                    // Get the previous feed message
                    InputStream previousIs = new ByteArrayInputStream(feedIteration.getFeedprotobuf());
                    previousFeedMessage = GtfsRealtime.FeedMessage.parseFrom(previousIs);
                }

                feedIteration = new GtfsRtFeedIterationModel(System.currentTimeMillis(), feedTimestamp,
                        gtfsRtProtobuf, mCurrentGtfsRtFeed, currentFeedDigest);
            } else {
                feedIteration = new GtfsRtFeedIterationModel(System.currentTimeMillis(), feedTimestamp, null,
                        mCurrentGtfsRtFeed, currentFeedDigest);
            }
            session.save(feedIteration);
            GTFSDB.commitAndCloseSession(session);

            if (!isUniqueFeed) {
                return;
            }
        } catch (Exception e) {
            _log.error("The URL '" + gtfsRtFeedUrl + "' does not contain valid Gtfs-Rt data", e);
            return;
        }

        // Read all GTFS-rt entities for the current feed
        mGtfsRtFeedMap.put(feedIteration.getGtfsRtFeedModel().getGtfsRtId(), currentFeedMessage);

        session = GTFSDB.initSessionBeginTrans();

        List<GtfsRealtime.FeedEntity> allEntitiesArrayList = new ArrayList<>();

        List<GtfsRtFeedModel> gtfsRtFeedModelList;
        gtfsRtFeedModelList = session.createQuery("FROM GtfsRtFeedModel" + " WHERE gtfsFeedID = "
                + mCurrentGtfsRtFeed.getGtfsFeedModel().getFeedId()).list();

        GTFSDB.closeSession(session);

        GtfsRealtime.FeedHeader header = null;

        if (gtfsRtFeedModelList.size() < 1) {
            _log.error("The URL '" + gtfsRtFeedUrl + "' is not stored properly into the database");
            return;
        }

        for (GtfsRtFeedModel gtfsRtFeedModel : gtfsRtFeedModelList) {
            GtfsRealtime.FeedMessage message = mGtfsRtFeedMap.get(gtfsRtFeedModel.getGtfsRtId());
            if (header == null) {
                // Save one header to use in our combined feed below
                header = message.getHeader();
            } else {
                if (message.getHeader() != null && message.getHeader().getTimestamp() > header.getTimestamp()) {
                    // Use largest header timestamp with multiple feeds - see #239
                    header = message.getHeader();
                }
            }
            if (message != null) {
                allEntitiesArrayList.addAll(message.getEntityList());
            }
        }

        GtfsRealtime.FeedMessage.Builder feedMessageBuilder = GtfsRealtime.FeedMessage.newBuilder();
        feedMessageBuilder.setHeader(header);
        feedMessageBuilder.addAllEntity(allEntitiesArrayList);

        GtfsRealtime.FeedMessage combinedFeed = feedMessageBuilder.build();

        // Use the same current time for all rules for consistency
        long currentTimeMillis = System.currentTimeMillis();

        // Run validation rules
        for (FeedEntityValidator rule : mValidationRules) {
            validateEntity(currentTimeMillis, combinedFeed, previousFeedMessage, gtfsData, gtfsMetadata,
                    feedIteration, rule);
        }

        logDuration(_log, "Processed " + mCurrentGtfsRtFeed.getGtfsUrl() + " in ", startTimeNanos);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.apache.jcp.xml.dsig.internal.dom.DOMHMACSignatureMethod.java

boolean verify(Key key, SignedInfo si, byte[] sig, XMLValidateContext context)
        throws InvalidKeyException, SignatureException, XMLSignatureException {
    if (key == null || si == null || sig == null) {
        throw new NullPointerException();
    }//from  ww w.j  av a2 s  . c o m
    if (!(key instanceof SecretKey)) {
        throw new InvalidKeyException("key must be SecretKey");
    }
    if (hmac == null) {
        try {
            hmac = Mac.getInstance(getJCAAlgorithm());
        } catch (NoSuchAlgorithmException nsae) {
            throw new XMLSignatureException(nsae);
        }
    }
    if (outputLengthSet && outputLength < getDigestLength()) {
        throw new XMLSignatureException("HMACOutputLength must not be less than " + getDigestLength());
    }
    hmac.init((SecretKey) key);
    ((DOMSignedInfo) si).canonicalize(context, new MacOutputStream(hmac));
    byte[] result = hmac.doFinal();

    return MessageDigest.isEqual(sig, result);
}

From source file:com.facebook.infrastructure.utils.FBUtilities.java

public static boolean isEqual(byte[] digestA, byte[] digestB) {
    return MessageDigest.isEqual(digestA, digestB);
}