Java Code Examples for org.apache.commons.codec.digest.DigestUtils#sha()

The following examples show how to use org.apache.commons.codec.digest.DigestUtils#sha() . 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: WeakMessageDigest.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void apacheApiVariations() {

        printHex(DigestUtils.getMd2Digest().digest("123".getBytes()));
        printHex(DigestUtils.getMd5Digest().digest("123".getBytes()));
        printHex(DigestUtils.getDigest("md2").digest("123".getBytes()));
        printHex(DigestUtils.getDigest("md5").digest("123".getBytes()));
        DigestUtils.md2("123".getBytes());
        DigestUtils.md5("123".getBytes());
        System.out.println(DigestUtils.md2Hex("123".getBytes()));
        System.out.println(DigestUtils.md5Hex("123".getBytes()));

        printHex(DigestUtils.getSha1Digest().digest("123".getBytes()));
        printHex(DigestUtils.getShaDigest().digest("123".getBytes()));
        printHex(DigestUtils.getDigest("sha1").digest("123".getBytes()));
        printHex(DigestUtils.getDigest("sha-1").digest("123".getBytes()));
        DigestUtils.sha1("123".getBytes());
        DigestUtils.sha("123".getBytes());
        DigestUtils.sha1Hex("123".getBytes());
        DigestUtils.shaHex("123".getBytes());

        printHex(DigestUtils.getDigest("sha256").digest("123".getBytes())); //OK!
        printHex(DigestUtils.getDigest(getDigest()).digest("123".getBytes())); //Unknown
    }
 
Example 2
Source File: AlarmSqlImpl.java    From monasca-thresh with Apache License 2.0 6 votes vote down vote up
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));
        }
      }
    }
  }
  return DigestUtils.sha(dimensionIdStringToHash.toString());
}
 
Example 3
Source File: AlarmDAOImpl.java    From monasca-thresh with Apache License 2.0 6 votes vote down vote up
private byte[] calculateDimensionSHA1(final Map<String, String> dimensions) {
  // Calculate dimensions sha1 hash id.
  final StringBuilder dimensionIdStringToHash = new StringBuilder("");
  if (dimensions != null) {
    // Sort the dimensions on name and value.
    TreeMap<String, String> dimensionTreeMap = new TreeMap<>(dimensions);
    for (String dimensionName : dimensionTreeMap.keySet()) {
      if (dimensionName != null && !dimensionName.isEmpty()) {
        String dimensionValue = dimensionTreeMap.get(dimensionName);
        if (dimensionValue != null && !dimensionValue.isEmpty()) {
          dimensionIdStringToHash.append(trunc(dimensionName, MAX_COLUMN_LENGTH));
          dimensionIdStringToHash.append(trunc(dimensionValue, MAX_COLUMN_LENGTH));
        }
      }
    }
  }

  final byte[] dimensionIdSha1Hash = DigestUtils.sha(dimensionIdStringToHash.toString());
  return dimensionIdSha1Hash;
}
 
Example 4
Source File: WaveService.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a URL that contains the necessary OAuth query parameters for the
 * given JSON string.
 *
 * 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();
}
 
Example 5
Source File: CassandraMetricRepo.java    From monasca-persister with Apache License 2.0 5 votes vote down vote up
@Override
public void addToBatch(MetricEnvelope metricEnvelope, String id) {
  Metric metric = metricEnvelope.metric;
  Map<String, Object> metaMap = metricEnvelope.meta;

  String tenantId = getMeta(TENANT_ID, metric, metaMap, id);
  String region = getMeta(REGION, metric, metaMap, id);
  String metricName = metric.getName();
  TreeMap<String, String> dimensions = metric.getDimensions() == null ? new TreeMap<String, String>()
      : new TreeMap<>(metric.getDimensions());

  StringBuilder sb = new StringBuilder(region).append(tenantId).append(metricName);

  Iterator<String> it = dimensions.keySet().iterator();
  while (it.hasNext()) {
    String k = it.next();
    sb.append(k).append(dimensions.get(k));
  }

  byte[] defIdSha = DigestUtils.sha(sb.toString());
  Sha1HashId defIdShaHash = new Sha1HashId(defIdSha);

  if (cluster.getMetricIdCache().getIfPresent(defIdShaHash.toHexString()) == null) {
    addDefinitionToBatch(defIdShaHash, metricName, dimensions, tenantId, region, id,
        metric.getTimestamp());
    batches.addMeasurementQuery(buildMeasurementInsertQuery(defIdShaHash, metric.getTimestamp(),
        metric.getValue(), metric.getValueMeta(), region, tenantId, metricName, dimensions, id));
  } else {
    metricCacheHitMeter.mark();
    // MUST update all relevant columns to ensure TTL consistency in a row
    batches.addMetricQuery(cluster.getMetricInsertStmt().bind(retention,
        defIdShaHash.getSha1HashByteBuffer(), new Timestamp(metric.getTimestamp()),
        new Timestamp(metric.getTimestamp()), region, tenantId, metricName,
        getDimensionList(dimensions), new ArrayList<>(dimensions.keySet())));
    batches.addMeasurementQuery(buildMeasurementUpdateQuery(defIdShaHash, metric.getTimestamp(),
        metric.getValue(), metric.getValueMeta(), id));
  }

  metricCount++;
}
 
Example 6
Source File: AlarmSqlImpl.java    From monasca-thresh with Apache License 2.0 5 votes vote down vote up
private MetricDefinitionDimensionsDb insertMetricDefinitionDimension(final Session session,
                                                                     final MetricDefinitionAndTenantId mdtId) {
  final MetricDefinitionDb metricDefinition = this.insertMetricDefinition(session, mdtId);
  final BinaryId metricDimensionSetId = this.insertMetricDimensionSet(session, mdtId.metricDefinition.dimensions);
  final byte[] definitionDimensionsIdSha1Hash = DigestUtils.sha(
      metricDefinition.getId().toHexString() + metricDimensionSetId.toHexString()
  );
  final MetricDefinitionDimensionsDb metricDefinitionDimensions = new MetricDefinitionDimensionsDb(
      definitionDimensionsIdSha1Hash,
      metricDefinition,
      metricDimensionSetId
  );
  return (MetricDefinitionDimensionsDb) session.merge(metricDefinitionDimensions);
}
 
Example 7
Source File: AlarmDAOImpl.java    From monasca-thresh with Apache License 2.0 5 votes vote down vote up
private Sha1HashId insertMetricDefinitionDimension(Handle h, MetricDefinitionAndTenantId mdtid) {
  final Sha1HashId metricDefinitionId = insertMetricDefinition(h, mdtid);
  final Sha1HashId metricDimensionSetId =
      insertMetricDimensionSet(h, mdtid.metricDefinition.dimensions);
  final byte[] definitionDimensionsIdSha1Hash =
      DigestUtils.sha(metricDefinitionId.toHexString() + metricDimensionSetId.toHexString());
  h.insert(
      "insert into metric_definition_dimensions (id, metric_definition_id, metric_dimension_set_id) values (?, ?, ?)"
          + "on duplicate key update id=id", definitionDimensionsIdSha1Hash,
      metricDefinitionId.getSha1Hash(), metricDimensionSetId.getSha1Hash());
  return new Sha1HashId(definitionDimensionsIdSha1Hash);
}
 
Example 8
Source File: AlarmDAOImpl.java    From monasca-thresh with Apache License 2.0 5 votes vote down vote up
private Sha1HashId insertMetricDefinition(Handle h, MetricDefinitionAndTenantId mdtid) {
  final String region = ""; // TODO We currently don't have region
  final String definitionIdStringToHash =
      trunc(mdtid.metricDefinition.name, MAX_COLUMN_LENGTH)
          + trunc(mdtid.tenantId, MAX_COLUMN_LENGTH) + trunc(region, MAX_COLUMN_LENGTH);
  final byte[] id = DigestUtils.sha(definitionIdStringToHash);
  h.insert("insert into metric_definition(id, name, tenant_id) values (?, ?, ?) " +
           "on duplicate key update id=id", id, mdtid.metricDefinition.name, mdtid.tenantId);
  return new Sha1HashId(id);
}
 
Example 9
Source File: CacheHelper.java    From yawp with MIT License 5 votes vote down vote up
private static String hash(String string) {
    byte[] shaArray = DigestUtils.sha(string);
    byte[] encodedArray = Base64.getEncoder().encode(shaArray);
    String returnValue = new String(encodedArray);
    returnValue = StringUtils.removeEnd(returnValue, "\r\n");
    return returnValue.replaceAll("=", "").replaceAll("/", "-").replaceAll("\\+", "\\_");
}
 
Example 10
Source File: WaveService.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a URL that contains the necessary OAuth query parameters for the
 * given JSON string.
 *
 * 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();
}
 
Example 11
Source File: Base64BinaryTest.java    From FHIR with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
@Test(enabled = true, groups = { "server-binary" })
public void testCreateDocumentReference() throws Exception {
    WebTarget target = getWebTarget();

    // Create an Attachment element
    String valueString = "Hello, World! attachment test.";
    byte[] value = valueString.getBytes();
    byte[] valueHash = DigestUtils.sha(valueString);
    Attachment attachment = Attachment.builder().contentType(Code.of("text/plain")).language(Code.of("en-US"))
            .data(Base64Binary.builder().value(value).build()).hash(Base64Binary.builder().value(valueHash).build())
            .build();

    // Create a DocumentReference resource and connect the attachment to it.
    List<DocumentReference.Content> listDocRef = new ArrayList<DocumentReference.Content>();
    listDocRef.add(DocumentReference.Content.builder().attachment(attachment).build());

    DocumentReference docRef = DocumentReference.builder()
            .status(DocumentReferenceStatus.CURRENT)
            .content(listDocRef)
            .type(CodeableConcept.builder()
                    .coding(Coding.builder().code(Code.of("attachmentTest")).build()).build())
            .date(Instant.of(ZonedDateTime.now())).build();

    // Persist the DocumentReference
    Entity<DocumentReference> entity = Entity.entity(docRef, FHIRMediaType.APPLICATION_FHIR_JSON);
    Response response = target.path("DocumentReference").request().post(entity, Response.class);
    assertResponse(response, Response.Status.CREATED.getStatusCode());

    if (DEBUG) {
        FHIRGenerator.generator(Format.JSON).generate(docRef, System.out);
    }

    // Retrieve the DocumentReference
    String docRefId = getLocationLogicalId(response);
    response = target.path("DocumentReference/" + docRefId).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
    assertResponse(response, Response.Status.OK.getStatusCode());
    DocumentReference responseDocRef = response.readEntity(DocumentReference.class);

    if (DEBUG) {
        FHIRGenerator.generator(Format.JSON).generate(responseDocRef, System.out);
    }

    // Compare original and retrieved values.
    assertEquals(new String(responseDocRef.getContent().get(0).getAttachment().getData().getValue()), valueString);
    assertTrue(Arrays.equals(responseDocRef.getContent().get(0).getAttachment().getHash().getValue(), valueHash));
}
 
Example 12
Source File: Guid.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private static byte[] computeGuid(byte[] bytes) {
  return DigestUtils.sha(bytes);
}
 
Example 13
Source File: VerticaMetricRepo.java    From monasca-persister with Apache License 2.0 2 votes vote down vote up
@Override
public void addToBatch(MetricEnvelope metricEnvelope, String id) {

  Metric metric = metricEnvelope.metric;
  Map<String, Object> metaMap = metricEnvelope.meta;

  String tenantId = getMeta(TENANT_ID, metric, metaMap, id);

  String region = getMeta(REGION, metric, metaMap, id);

  // Add the definition to the batch.
  StringBuilder definitionIdStringToHash =
      new StringBuilder(trunc(metric.getName(), MAX_COLUMN_LENGTH, id));

  definitionIdStringToHash.append(trunc(tenantId, MAX_COLUMN_LENGTH, id));

  definitionIdStringToHash.append(trunc(region, MAX_COLUMN_LENGTH, id));

  byte[] definitionIdSha1Hash = DigestUtils.sha(definitionIdStringToHash.toString());

  Sha1HashId definitionSha1HashId = new Sha1HashId((definitionIdSha1Hash));

  addDefinitionToBatch(definitionSha1HashId, trunc(metric.getName(), MAX_COLUMN_LENGTH, id),
                       trunc(tenantId, MAX_COLUMN_LENGTH, id),
                       trunc(region, MAX_COLUMN_LENGTH, id), id);

  // Calculate dimensions sha1 hash id.
  StringBuilder dimensionIdStringToHash = new StringBuilder();

  Map<String, String> preppedDimMap = prepDimensions(metric.getDimensions(), id);

  for (Map.Entry<String, String> entry : preppedDimMap.entrySet()) {

    dimensionIdStringToHash.append(entry.getKey());

    dimensionIdStringToHash.append(entry.getValue());
  }

  byte[] dimensionIdSha1Hash = DigestUtils.sha(dimensionIdStringToHash.toString());

  Sha1HashId dimensionsSha1HashId = new Sha1HashId(dimensionIdSha1Hash);

  // Add the dimension name/values to the batch.
  addDimensionsToBatch(dimensionsSha1HashId, preppedDimMap, id);

  // Add the definition dimensions to the batch.
  StringBuilder definitionDimensionsIdStringToHash =
      new StringBuilder(definitionSha1HashId.toHexString());

  definitionDimensionsIdStringToHash.append(dimensionsSha1HashId.toHexString());

  byte[] definitionDimensionsIdSha1Hash =
      DigestUtils.sha(definitionDimensionsIdStringToHash.toString());

  Sha1HashId definitionDimensionsSha1HashId = new Sha1HashId(definitionDimensionsIdSha1Hash);

  addDefinitionDimensionToBatch(definitionDimensionsSha1HashId, definitionSha1HashId,
                                dimensionsSha1HashId, id);

  // Add the measurement to the batch.
  String timeStamp = simpleDateFormat.format(new Date(metric.getTimestamp()));

  double value = metric.getValue();

  addMetricToBatch(definitionDimensionsSha1HashId, timeStamp, value, metric.getValueMeta(), id);

}