Example usage for org.apache.commons.codec.digest DigestUtils sha

List of usage examples for org.apache.commons.codec.digest DigestUtils sha

Introduction

In this page you can find the example usage for org.apache.commons.codec.digest DigestUtils sha.

Prototype

@Deprecated
    public static byte[] sha(String data) 

Source Link

Usage

From source file:monasca.thresh.infrastructure.persistence.hibernate.AlarmSqlImpl.java

private MetricDefinitionDb insertMetricDefinition(final Session session,
        final MetricDefinitionAndTenantId mdtid) {

    final String region = ""; // TODO We currently don't have region
    final String definitionIdStringToHash = truncateString(mdtid.metricDefinition.name, MAX_COLUMN_LENGTH)
            + truncateString(mdtid.tenantId, MAX_COLUMN_LENGTH) + truncateString(region, MAX_COLUMN_LENGTH);
    final byte[] id = DigestUtils.sha(definitionIdStringToHash);
    final MetricDefinitionDb metricDefinition = new MetricDefinitionDb(id, mdtid.metricDefinition.name,
            mdtid.tenantId, region);//  ww  w  .ja v a2s . c  om

    if (session.get(MetricDefinitionDb.class, metricDefinition.getId()) == null) {
        session.persist(metricDefinition);
        return metricDefinition;
    }

    session.merge(metricDefinition);
    return metricDefinition;
}

From source file:FileBaseDataMap.java

protected static int createHashCode(String key) {

    int hashCode = new String(DigestUtils.sha(key.getBytes())).hashCode();

    if (hashCode < 0) {
        hashCode = hashCode - hashCode - hashCode;
    }//from   w ww  . ja v  a 2  s . c  o m

    return hashCode;
}

From source file:monasca.thresh.infrastructure.persistence.hibernate.AlarmSqlImpl.java

private byte[] calculateDimensionSHA1(final Map<String, String> dimensions) {
    // Calculate dimensions sha1 hash id.
    final StringBuilder dimensionIdStringToHash = new StringBuilder("");
    if (dimensions != null && !dimensions.isEmpty()) {
        // Sort the dimensions on name and value.
        final Map<String, String> dimensionTreeMap = Maps.newTreeMap(ImmutableSortedMap.copyOf(dimensions));
        for (final String dimensionName : dimensionTreeMap.keySet()) {
            if (dimensionName != null && !dimensionName.isEmpty()) {
                final String dimensionValue = dimensionTreeMap.get(dimensionName);
                if (dimensionValue != null && !dimensionValue.isEmpty()) {
                    dimensionIdStringToHash.append(this.truncateString(dimensionName, MAX_COLUMN_LENGTH))
                            .append(this.truncateString(dimensionValue, MAX_COLUMN_LENGTH));
                }/*w w w . j  ava 2 s .  c om*/
            }
        }
    }
    return DigestUtils.sha(dimensionIdStringToHash.toString());
}

From source file:es.javocsoft.android.lib.toucan.client.ToucanClient.java

private static String generateSHA1(String data) {
    return new String(Hex.encodeHex(DigestUtils.sha(data)));
}

From source file:com.otterca.common.crypto.acceptance.X509CertificateBuilderAcceptanceTest.java

/**
 * Test search criteria. There's no easy way to check the subject key id and
 * authority key id - we can get the extension's bytes but still need to
 * parse them./*w  ww .  jav  a2 s . c  o  m*/
 */
@Test
public void testTestSearchCriteria() throws GeneralSecurityException {

    // create issuer certificate
    populate(builder);
    builder.setSubject(ISSUER_NAME);
    builder.setIssuer(ISSUER_NAME);
    builder.setBasicConstraints(true);
    X509Certificate issuer = builder.build(issuerKeyPair.getPrivate());

    builder.reset();

    // create subject certificate
    populate(builder);
    builder.setIssuer(issuer);
    X509Certificate cert = builder.build(keyPair.getPrivate());

    assertEquals(certUtil.getFingerprint(cert), toHex(DigestUtils.sha(cert.getEncoded())));
    assertEquals(certUtil.getCertificateHash(cert), rfc4387(cert.getEncoded()));
    assertEquals(certUtil.getIHash(cert), rfc4387(cert.getIssuerX500Principal().getEncoded()));
    assertEquals(certUtil.getSHash(cert), rfc4387(cert.getSubjectX500Principal().getEncoded()));
}

From source file:com.otterca.common.crypto.acceptance.X509CertificateBuilderAcceptanceTest.java

/**
 * Compute SHA1 hash of DER-encoded value, encode it using Base64, and drop
 * the trailing '='. (from X509CertificateUtil)
 * /*from   w w  w.  j a va  2  s.c  o m*/
 * @param asn1
 * @return
 */
public final String rfc4387(byte[] asn1) {
    byte[] digest = DigestUtils.sha(asn1);
    return Base64.encodeBase64String(digest).substring(0, 28);
}

From source file:com.google.wave.api.WaveService.java

/**
 * Creates a URL that contains the necessary OAuth query parameters for the
 * given JSON string.// w w w  .jav a2 s . c  o  m
 *
 * The required OAuth parameters are:
 * <ul>
 * <li>oauth_body_hash</li>
 * <li>oauth_consumer_key</li>
 * <li>oauth_signature_method</li>
 * <li>oauth_timestamp</li>
 * <li>oauth_nonce</li>
 * <li>oauth_version</li>
 * <li>oauth_signature</li>
 * </ul>
 *
 * @param jsonBody the JSON string to construct the URL from.
 * @param rpcServerUrl the URL of the handler that services the JSON-RPC
 *        request.
 * @param accessor the OAuth accessor used to create the signed string.
 * @return a URL for the given JSON string, and the required OAuth parameters.
 */
public static String createOAuthUrlString(String jsonBody, String rpcServerUrl, OAuthAccessor accessor)
        throws IOException, URISyntaxException, OAuthException {
    OAuthMessage message = new OAuthMessage(POST, rpcServerUrl,
            Collections.<SimpleEntry<String, String>>emptyList());

    // Compute the hash of the body.
    byte[] rawBody = jsonBody.getBytes(UTF_8);
    byte[] hash = DigestUtils.sha(rawBody);
    byte[] encodedHash = Base64.encodeBase64(hash);
    message.addParameter(OAUTH_BODY_HASH, new String(encodedHash, UTF_8));

    // Add other parameters.

    message.addRequiredParameters(accessor);
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Signature base string: " + OAuthSignatureMethod.getBaseString(message));
    }

    // Construct the resulting URL.
    StringBuilder sb = new StringBuilder(rpcServerUrl);
    char connector = '?';
    for (Map.Entry<String, String> p : message.getParameters()) {
        if (!p.getKey().equals(jsonBody)) {
            sb.append(connector);
            sb.append(URLEncoder.encode(p.getKey(), UTF_8));
            sb.append('=');
            sb.append(URLEncoder.encode(p.getValue(), UTF_8));
            connector = '&';
        }
    }
    return sb.toString();
}

From source file:com.google.wave.api.AbstractRobot.java

/**
 * Creates a URL that contains the necessary OAuth query parameters for the
 * given JSON string./*from ww  w. ja  va2  s .  c  o m*/
 *
 * @param jsonBody the JSON string to construct the URL from.
 * @param rpcServerUrl the URL of the handler that services the JSON-RPC
 *     request.
 * @param consumerKey the OAuth consumerKey.
 * @param consumerSecret the OAuth consumerSecret.
 *
 * @return a URL for the given JSON string, and the required OAuth parameters:
 *     <ul>
 *       <li>oauth_body_hash</li>
 *       <li>oauth_consumer_key</li>
 *       <li>oauth_signature_method</li>
 *       <li>oauth_timestamp</li>
 *       <li>oauth_nonce</li>
 *       <li>oauth_version</li>
 *       <li>oauth_signature</li>
 *     </ul>
 */
private static String createOAuthUrlString(String jsonBody, String rpcServerUrl, String consumerKey,
        String consumerSecret) throws IOException, URISyntaxException, OAuthException {
    OAuthMessage message = new OAuthMessage(POST, rpcServerUrl, Collections.<Entry<String, String>>emptyList());

    // Compute the hash of the body.
    byte[] hash = DigestUtils.sha(jsonBody);
    byte[] encodedHash = Base64.encodeBase64(hash, false);
    message.addParameter(OAUTH_BODY_HASH, new String(encodedHash, UTF_8));

    // Add other parameters.
    OAuthConsumer consumer = new OAuthConsumer(null, OAUTH_CONSUMER_KEY_DOMAIN + ":" + consumerKey,
            consumerSecret, null);
    consumer.setProperty(OAuth.OAUTH_SIGNATURE_METHOD, OAuth.HMAC_SHA1);
    OAuthAccessor accessor = new OAuthAccessor(consumer);
    message.addRequiredParameters(accessor);
    LOG.info("Signature base string: " + OAuthSignatureMethod.getBaseString(message));

    // Construct the resulting URL.
    StringBuilder sb = new StringBuilder(rpcServerUrl);
    char connector = '?';
    for (Map.Entry<String, String> p : message.getParameters()) {
        if (!p.getKey().equals(jsonBody)) {
            sb.append(connector);
            sb.append(URLEncoder.encode(p.getKey(), "UTF-8"));
            sb.append('=');
            sb.append(URLEncoder.encode(p.getValue(), "UTF-8"));
            connector = '&';
        }
    }
    return sb.toString();
}

From source file:okuyama.imdst.util.DataDispatcher.java

/**
 * sha1??Hash??java?hashCode???.<br>
 * ????<br>//w w  w.  j  a  v a  2 s.c om
 *
 * @param targete
 * @param int
 */
public static int sha1Hash4Int(String target) {
    int ret = new String(DigestUtils.sha(target.getBytes())).hashCode();
    if (ret < 0) {
        ret = ret - ret - ret;
    }
    return ret;
}

From source file:org.apache.abdera.ext.oauth.OAuthScheme.java

private String sign(String method, String baseString, Certificate cert) throws AuthenticationException {
    if (method.equalsIgnoreCase("HMAC-MD5") || method.equalsIgnoreCase("HMAC-SHA1")) {
        try {/*w  w w  .  ja v a  2  s . c o m*/
            String[] tokens = method.split("-");
            String methodName = tokens[0].substring(0, 1).toUpperCase() + tokens[0].substring(1).toLowerCase()
                    + tokens[1];
            KeyGenerator kg = KeyGenerator.getInstance(methodName);

            Mac mac = Mac.getInstance(kg.getAlgorithm());
            mac.init(kg.generateKey());
            byte[] result = mac.doFinal(baseString.getBytes());

            return new String(Base64.encodeBase64(result));
        } catch (Exception e) {
            throw new AuthenticationException(e.getMessage(), e);
        }
    } else if (method.equalsIgnoreCase("md5")) {
        return new String(Base64.encodeBase64(DigestUtils.md5(baseString)));
    } else if (method.equalsIgnoreCase("sha1")) {
        return new String(Base64.encodeBase64(DigestUtils.sha(baseString)));
    } else if (method.equalsIgnoreCase("RSA-SHA1")) {
        if (cert == null) {
            throw new AuthenticationException("a cert is mandatory to use SHA1 with RSA");
        }
        try {
            Cipher cipher = Cipher.getInstance("SHA1withRSA");
            cipher.init(Cipher.ENCRYPT_MODE, cert);
            byte[] result = cipher.doFinal(baseString.getBytes());
            return new String(Base64.encodeBase64(result));
        } catch (Exception e) {
            throw new AuthenticationException(e.getMessage(), e);
        }
    } else {
        throw new AuthenticationException("unsupported algorithm method: " + method);
    }
}