List of usage examples for java.security MessageDigest isEqual
public static boolean isEqual(byte[] digesta, byte[] digestb)
From source file:com.nexmo.security.RequestSigning.java
/** * looks at the current http request and verifies that the request signature, if supplied is valid. * * @param request The servlet request object to be verified * @param secretKey the pre-shared secret key used by the sender of the request to create the signature * * @return boolean returns true only if the signature is correct for this request and secret key. *///from w w w . j a v a 2s.c om public static boolean verifyRequestSignature(HttpServletRequest request, String secretKey) { // identify the signature supplied in the request ... String suppliedSignature = request.getParameter(PARAM_SIGNATURE); if (suppliedSignature == null) return false; // Firstly, extract the timestamp parameter and verify that it is within 5 minutes of 'current time' String timeString = request.getParameter(PARAM_TIMESTAMP); long time = -1; try { if (timeString != null) time = Long.parseLong(timeString) * 1000; } catch (NumberFormatException e) { log.debug("Error parsing 'time' parameter [ " + timeString + " ]", e); time = 0; } long diff = System.currentTimeMillis() - time; if (diff > MAX_ALLOWABLE_TIME_DELTA || diff < -MAX_ALLOWABLE_TIME_DELTA) { log.warn("SECURITY-KEY-VERIFICATION -- BAD-TIMESTAMP ... Timestamp [ " + time + " ] delta [ " + diff + " ] max allowed delta [ " + -MAX_ALLOWABLE_TIME_DELTA + " ] "); return false; } // Next, construct a sorted list of the name-value pair parameters supplied in the request, excluding the signature parameter Map<String, String> sortedParams = new TreeMap<>(); for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) { String name = entry.getKey(); String value = entry.getValue()[0]; if (name.equals(PARAM_SIGNATURE)) continue; if (value == null || value.trim().equals("")) continue; sortedParams.put(name, value); } // walk this sorted list of parameters and construct a string StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> param : sortedParams.entrySet()) { String name = param.getKey(); String value = param.getValue(); sb.append("&").append(clean(name)).append("=").append(clean(value)); } // append the secret key and calculate an md5 signature of the resultant string sb.append(secretKey); String str = sb.toString(); String md5 = "no signature"; try { md5 = MD5Util.calculateMd5(str); } catch (Exception e) { log.error("error...", e); return false; } log.info("SECURITY-KEY-VERIFICATION -- String [ " + str + " ] Signature [ " + md5 + " ] SUPPLIED SIGNATURE [ " + suppliedSignature + " ] "); // verify that the supplied signature matches generated one // use MessageDigest.isEqual as an alternative to String.equals() to defend against timing based attacks try { if (!MessageDigest.isEqual(md5.getBytes("UTF-8"), suppliedSignature.getBytes("UTF-8"))) return false; } catch (UnsupportedEncodingException e) { log.error("This should not occur!!", e); return false; } return true; }
From source file:net.yacy.data.TransactionManager.java
/** * Check the current request is a valid HTTP POST transaction : the current user is authenticated, * and the request post parameters contain a valid transaction token. * @param header current request header/* w ww . j a v a2 s. c o m*/ * @param post request parameters * @throws IllegalArgumentException when a parameter is null. * @throws DisallowedMethodException when the HTTP method is something else than post * @throws TemplateMissingParameterException when the transaction token is missing * @throws BadTransactionException when a condition for valid transaction is not met. */ public static void checkPostTransaction(final RequestHeader header, final serverObjects post) { if (header == null || post == null) { throw new IllegalArgumentException("Missing required parameters."); } if (!HeaderFramework.METHOD_POST.equals(header.getMethod())) { throw new DisallowedMethodException("HTTP POST method is the only one authorized."); } String userName = getCurrentUserName(header); if (userName == null) { throw new BadTransactionException("User is not authenticated."); } final String transactionToken = post.get(TRANSACTION_TOKEN_PARAM); if (transactionToken == null) { throw new TemplateMissingParameterException("Missing transaction token."); } final String token = new HmacUtils(HmacAlgorithms.HMAC_SHA_1, SIGNING_KEY) .hmacHex(TOKEN_SEED + userName + header.getPathInfo()); /* Compare the server generated token with the one received in the post parameters, * using a time constant function */ if (!MessageDigest.isEqual(token.getBytes(StandardCharsets.UTF_8), transactionToken.getBytes(StandardCharsets.UTF_8))) { throw new BadTransactionException("Invalid transaction token."); } }
From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.util.io.FileProtection.java
/** * Validates the file.//from w w w.j ava 2s .c om * * @param file the file being validated * @param actual the actual message digest of the file * @throws IOException if an I/O error occurred */ private static void validate(File file, byte[] actual) throws IOException { String mode = Settings.getFileProtectionMode(); File digestFile = getDigestFile(file); if (digestFile.exists()) { byte[] expected = loadDigest(file); if (!MessageDigest.isEqual(actual, expected)) { throw new ValidationException(file, "digest does not match"); } } else { if (mode.equalsIgnoreCase(STRICT_MODE)) { throw new ValidationException(file, "no digest file"); } else { System.err.println("no digest file exists to validate " + file); } } }
From source file:org.apache.nifi.toolkit.tls.service.client.TlsCertificateSigningRequestPerformer.java
/** * Submits a CSR to the Certificate authority, checks the resulting hmac, and returns the chain if everything succeeds * * @param keyPair the keypair to generate the csr for * @throws IOException if there is a problem during the process * @return the resulting certificate chain *///from w w w. j a v a 2 s . com public X509Certificate[] perform(KeyPair keyPair) throws IOException { try { List<X509Certificate> certificates = new ArrayList<>(); HttpClientBuilder httpClientBuilder = httpClientBuilderSupplier.get(); SSLContextBuilder sslContextBuilder = SSLContextBuilder.create(); sslContextBuilder.useProtocol("TLSv1.2"); // We will be validating that we are talking to the correct host once we get the response's hmac of the token and public key of the ca sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); httpClientBuilder.setSSLSocketFactory(new TlsCertificateAuthorityClientSocketFactory( sslContextBuilder.build(), caHostname, certificates)); String jsonResponseString; int responseCode; try (CloseableHttpClient client = httpClientBuilder.build()) { JcaPKCS10CertificationRequest request = TlsHelper.generateCertificationRequest(dn, domainAlternativeNames, keyPair, signingAlgorithm); TlsCertificateAuthorityRequest tlsCertificateAuthorityRequest = new TlsCertificateAuthorityRequest( TlsHelper.calculateHMac(token, request.getPublicKey()), TlsHelper.pemEncodeJcaObject(request)); HttpPost httpPost = new HttpPost(); httpPost.setEntity( new ByteArrayEntity(objectMapper.writeValueAsBytes(tlsCertificateAuthorityRequest))); if (logger.isInfoEnabled()) { logger.info("Requesting certificate with dn " + dn + " from " + caHostname + ":" + port); } try (CloseableHttpResponse response = client.execute(new HttpHost(caHostname, port, "https"), httpPost)) { jsonResponseString = IOUtils.toString( new BoundedInputStream(response.getEntity().getContent(), 1024 * 1024), StandardCharsets.UTF_8); responseCode = response.getStatusLine().getStatusCode(); } } if (responseCode != Response.SC_OK) { throw new IOException( RECEIVED_RESPONSE_CODE + responseCode + " with payload " + jsonResponseString); } if (certificates.size() != 1) { throw new IOException(EXPECTED_ONE_CERTIFICATE); } TlsCertificateAuthorityResponse tlsCertificateAuthorityResponse = objectMapper .readValue(jsonResponseString, TlsCertificateAuthorityResponse.class); if (!tlsCertificateAuthorityResponse.hasHmac()) { throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_HMAC); } X509Certificate caCertificate = certificates.get(0); byte[] expectedHmac = TlsHelper.calculateHMac(token, caCertificate.getPublicKey()); if (!MessageDigest.isEqual(expectedHmac, tlsCertificateAuthorityResponse.getHmac())) { throw new IOException(UNEXPECTED_HMAC_RECEIVED_POSSIBLE_MAN_IN_THE_MIDDLE); } if (!tlsCertificateAuthorityResponse.hasCertificate()) { throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_CERTIFICATE); } X509Certificate x509Certificate = TlsHelper .parseCertificate(new StringReader(tlsCertificateAuthorityResponse.getPemEncodedCertificate())); x509Certificate.verify(caCertificate.getPublicKey()); if (logger.isInfoEnabled()) { logger.info("Got certificate with dn " + x509Certificate.getSubjectX500Principal()); } return new X509Certificate[] { x509Certificate, caCertificate }; } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException(e); } }
From source file:alfio.manager.PaypalManager.java
public static boolean isValidHMAC(CustomerName customerName, String email, String billingAddress, String hmac, Event event) {//w w w . ja v a 2s . c o m String computedHmac = computeHMAC(customerName, email, billingAddress, event); return MessageDigest.isEqual(hmac.getBytes(StandardCharsets.UTF_8), computedHmac.getBytes(StandardCharsets.UTF_8)); }
From source file:com.googlesource.gerrit.plugins.github.notification.WebhookServlet.java
/** * validates callback signature sent from github * * @param signatureHeader signature HTTP request header of a github webhook * @param payload HTTP request body/*w ww.j a va 2 s.c o m*/ * @return true if webhook secret is not configured or signatureHeader is * valid against payload and the secret, false if otherwise. * @throws UnsupportedEncodingException */ private boolean validateSignature(String signatureHeader, String body, String encoding) throws UnsupportedEncodingException { byte[] payload = body.getBytes(encoding == null ? "UTF-8" : encoding); if (config.webhookSecret == null || config.webhookSecret.equals("")) { logger.debug("{}.webhookSecret not configured. Skip signature validation", GitHubConfig.CONF_SECTION); return true; } if (!StringUtils.startsWith(signatureHeader, SIGNATURE_PREFIX)) { logger.error("Unsupported webhook signature type: {}", signatureHeader); return false; } byte[] signature; try { signature = Hex.decodeHex(signatureHeader.substring(SIGNATURE_PREFIX.length()).toCharArray()); } catch (DecoderException e) { logger.error("Invalid signature: {}", signatureHeader); return false; } return MessageDigest.isEqual(signature, getExpectedSignature(payload)); }
From source file:io.syndesis.rest.v1.state.ClientSideState.java
<T> TimestampedState<T> restoreWithTimestamp(final Cookie cookie, final Class<T> type) { final String value = cookie.getValue(); final String[] parts = value.split("\\|", 5); final byte[] atime = DECODER.decode(parts[1]); final long atimeLong = atime(atime); if (atimeLong + timeout < timeSource.getAsLong()) { throw new IllegalArgumentException("Given value has timed out at: " + Instant.ofEpochSecond(atimeLong)); }//from ww w.j a v a 2 s . c om final byte[] tid = DECODER.decode(parts[2]); if (!MessageDigest.isEqual(tid, edition.tid)) { throw new IllegalArgumentException(String.format("Given TID `%s`, mismatches current TID `%s`", new BigInteger(tid).toString(16), new BigInteger(edition.tid).toString(16))); } final KeySource keySource = edition.keySource(); final int lastSeparatorIdx = value.lastIndexOf('|'); final byte[] mac = DECODER.decode(parts[4]); final byte[] calculated = mac(edition.authenticationAlgorithm, value.substring(0, lastSeparatorIdx), keySource.authenticationKey()); if (!MessageDigest.isEqual(mac, calculated)) { throw new IllegalArgumentException("Cookie value fails authenticity check"); } final byte[] iv = DECODER.decode(parts[3]); final byte[] encrypted = DECODER.decode(parts[0]); final byte[] clear = decrypt(edition.encryptionAlgorithm, iv, encrypted, keySource.encryptionKey()); @SuppressWarnings("unchecked") final T ret = (T) deserialization.apply(type, clear); return new TimestampedState<>(ret, atimeLong); }
From source file:es.mityc.firmaJava.ts.TSCliente.java
/** * Este mtodo valida el Sello de Tiempo//from www. ja v a 2s .c o m * @param binarioaSellar fichero binario a validar * @param sellodeTiempo El Sello de Tiempo se ingresa en formato binario * @return TSValidacion Valores TSA * @throws NoSuchAlgorithmException * @throws TSPException * @throws IOException * @throws NoSuchProviderException * @throws CertStoreException * @throws TSClienteError */ public static TSValidacion validarSelloTiempo(byte[] binarioaSellar, byte[] sellodeTiempo) throws NoSuchAlgorithmException, TSPException, IOException, NoSuchProviderException, CertStoreException, TSClienteError { // Set permitidos = new HashSet(Arrays.asList(TSPAlgoritmos.getValoresPermitidos())); // si el algoritmo pasado no es permitido o es nulo se usa el algortimo por defecto TimeStampToken tst = null; TSValidacion tsv = new TSValidacion(); try { tst = new TimeStampToken(new CMSSignedData(sellodeTiempo)); } catch (CMSException e) { // Intenta obtenerlo como una TimeStampResp try { TimeStampResponse tsr = new TimeStampResponse(sellodeTiempo); tst = tsr.getTimeStampToken(); if (tst == null) throw new TSClienteError(I18n.getResource(ConstantesTSA.LIBRERIA_TSA_ERROR_2)); } catch (TSPException ex) { throw new TSClienteError(I18n.getResource(ConstantesTSA.LIBRERIA_TSA_ERROR_2)); } catch (IOException ex) { throw new TSClienteError(I18n.getResource(ConstantesTSA.LIBRERIA_TSA_ERROR_2)); } } tsv.setTst(tst); TimeStampTokenInfo tokenInfo = tst.getTimeStampInfo(); MessageDigest resumen = TSPAlgoritmos.getDigest(tokenInfo.getMessageImprintAlgOID()); if (resumen == null) { tsv.setRespuesta(false); return tsv; } resumen.update(binarioaSellar); if (MessageDigest.isEqual(resumen.digest(), tst.getTimeStampInfo().getMessageImprintDigest())) { //TimeStampTokenInfo tokenInfo = tst.getTimeStampInfo(); SimpleDateFormat formato = new SimpleDateFormat(FORMATO_FECHA); tsv.setFecha(formato.format(tokenInfo.getGenTime())); tsv.setFechaDate(tokenInfo.getGenTime()); GenTimeAccuracy precision = tokenInfo.getGenTimeAccuracy(); tsv.setPrecision(precision); long accuLong = 0; if (precision != null) { accuLong = (precision.getMicros() * 1L) + (precision.getMillis() * 1000L) + (precision.getSeconds() * 1000000L); } tsv.setPrecisionLong(accuLong); tsv.setSello(tokenInfo.getSerialNumber()); tsv.setFirmaDigest(new String(Base64Coder.encode(tokenInfo.getMessageImprintDigest()))); tsv.setRespuesta(true); tsv.setSelloAlg(tokenInfo.getMessageImprintAlgOID()); tsv.setEmisor(tst.getSID().getIssuer()); } else { tsv.setRespuesta(false); } return tsv; }
From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.util.io.FileProtection.java
@Override public void run(CommandLine commandLine) throws Exception { if (commandLine.hasOption("check")) { int validCount = 0; int invalidCount = 0; String mode = Settings.getFileProtectionMode(); for (String filename : commandLine.getArgs()) { File file = new File(filename); System.out.print(file); System.out.print(": "); if (getDigestFile(file).exists()) { byte[] actual = computeDigest(file); byte[] expected = loadDigest(file); boolean valid = MessageDigest.isEqual(actual, expected); if (valid) { validCount++;/*ww w. j a v a2 s. co m*/ System.out.println("OK"); } else { invalidCount++; System.out.println("FAILED"); } } else { if (mode.equalsIgnoreCase(STRICT_MODE)) { invalidCount++; System.out.println("FAILED"); } else { validCount++; System.out.println("OK (NO DIGEST FILE)"); } } } if (invalidCount > 0) { System.err.print("WARNING: "); System.err.print(invalidCount); System.err.print(" of "); System.err.print(validCount + invalidCount); System.err.println(" computed checksums did NOT match"); } } else { for (String filename : commandLine.getArgs()) { File file = new File(filename); byte[] digest = computeDigest(file); saveDigest(file, digest); } } }
From source file:org.bremersee.common.security.crypto.password.PasswordEncoderImpl.java
@Override public boolean userPasswordMatches(final byte[] userPassword, final String clearPassword) { if (userPassword == null && StringUtils.isBlank(clearPassword)) { return true; }//from www. j a v a2s . com if (userPassword == null || StringUtils.isBlank(clearPassword)) { return false; } final String[] ap = getAlgorithmAndPassword(userPassword); final String localAlgorithm = ap[0]; final String password = ap[1]; if (NO_ENCRYPTION.equalsIgnoreCase(localAlgorithm)) { return StringUtils.isBlank(clearPassword) && password == null || clearPassword.equals(password); } final MessageDigest md = getMessageDigest(localAlgorithm); if (isSaltedSha(localAlgorithm)) { // extract the SHA hashed data into hs[0] // extract salt into hs[1] final byte[][] hs = split(Base64.decodeBase64(password), getPasswordHashSize(localAlgorithm)); final byte[] hash = hs[0]; final byte[] salt = hs[1]; // Update digest object with byte array of clear text string and salt md.reset(); md.update(clearPassword.getBytes()); md.update(salt); // Complete hash computation, this is now binary data final byte[] pwhash = md.digest(); if (log.isDebugEnabled()) { log.debug("Salted Hash extracted (in hex): " + Hex.encodeHexString(hash)); log.debug("Salt extracted (in hex): " + Hex.encodeHexString(salt)); log.debug("Hash length is: " + hash.length); log.debug("Salt length is: " + salt.length); log.debug("Salted Hash presented in hex: " + Hex.encodeHexString(pwhash)); } final boolean result = MessageDigest.isEqual(hash, pwhash); log.debug("Password matches? " + result); return result; } final byte[] digest = md.digest(CodingUtils.toBytesSilently(clearPassword, StandardCharsets.UTF_8)); return MessageDigest.isEqual(digest, Base64.decodeBase64(password)); }