Java Code Examples for com.google.common.hash.Hashing

The following examples show how to use com.google.common.hash.Hashing. These examples are extracted from open source projects. 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 Project: onos   Source File: DefaultPiPipeconf.java    License: Apache License 2.0 6 votes vote down vote up
private long generateFingerprint(Collection<URL> extensions) {
    Collection<Integer> hashes = new ArrayList<>();
    for (URL extUrl : extensions) {
        try {
            HashingInputStream hin = new HashingInputStream(
                    Hashing.crc32(), extUrl.openStream());
            //noinspection StatementWithEmptyBody
            while (hin.read() != -1) {
                // Do nothing. Reading all input stream to update hash.
            }
            hashes.add(hin.hash().asInt());
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    }
    //  FIXME: how to include behaviours in the hash?
    int low = Arrays.hashCode(hashes.toArray());
    int high = pipelineModel.hashCode();
    return ByteBuffer.allocate(8).putInt(high).putInt(low).getLong(0);
}
 
Example 2
Source Project: buck   Source File: Manifest.java    License: Apache License 2.0 6 votes vote down vote up
/** Hash the files pointed to by the source paths. */
@VisibleForTesting
static HashCode hashSourcePathGroup(
    FileHashLoader fileHashLoader,
    SourcePathResolverAdapter resolver,
    ImmutableList<SourcePath> paths)
    throws IOException {
  if (paths.size() == 1) {
    return hashSourcePath(paths.get(0), fileHashLoader, resolver);
  }
  Hasher hasher = Hashing.md5().newHasher();
  for (SourcePath path : paths) {
    hasher.putBytes(hashSourcePath(path, fileHashLoader, resolver).asBytes());
  }
  return hasher.hash();
}
 
Example 3
@Test
   public void simpleDownloadTest() throws InstantiationException,
           IllegalAccessException, IllegalArgumentException,
		InvocationTargetException, NoSuchFieldException, SecurityException, OneDriveException, IOException, InterruptedException {
	OneDriveSDK api = TestSDKFactory.getInstance();

	OneFolder folder = api.getFolderByPath("/IntegrationTesting/FolderForDownload");
	List<OneFile> files = folder.getChildFiles();


	for (OneFile file : files){
		File localCopy = File.createTempFile(file.getName(), ".bin");

		OneDownloadFile f = file.download(localCopy);
		f.startDownload();

		HashCode code = Files.hash(localCopy, Hashing.sha1());
           assertEquals(file.getName() + " mismatch", code.toString().toUpperCase(), file.getSHA1Hash());
       }
}
 
Example 4
/**
 * Uploads a byte array using FileResource and ExternalFileResource
 *
 * @param name  name of the file to be stored
 * @param bytes the byte array representing the file to be stored
 * @return url pointing to the uploaded resource
 */
private String uploadImage( String name, byte[] bytes )
    throws IOException
{
    FileResource fileResource = new FileResource(
        name,
        MimeTypeUtils.IMAGE_PNG.toString(), // All files uploaded from PushAnalysis is PNG.
        bytes.length,
        ByteSource.wrap( bytes ).hash( Hashing.md5() ).toString(),
        FileResourceDomain.PUSH_ANALYSIS
    );

    String accessToken = saveFileResource( fileResource, bytes );

    return dhisConfigurationProvider.getServerBaseUrl() + "/api/externalFileResources/" + accessToken;

}
 
Example 5
Source Project: webdsl   Source File: CachedResourceFileNameHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static String getNameWithHash(String resourceDirName, String name) {
  String hashname = resources.get(name);
  if (hashname == null) {
    if (resourcePathRoot == null) {
      if (!warningShown) {
        Logger.warn(CachedResourceFileNameHelper.class.getName()
            + " is not initialized by the servlet context or the servlet is not deployed in an exploded way (e.g. when serving directly from war-file). It won't add file-hashes to resource file names.");
        warningShown = true;
      }
      hashname = name;
    } else {
      String nameNoSuffix = name.replaceAll("(\\?.*)$", "");
      String realPath = resourcePathRoot + File.separator + resourceDirName + File.separator + nameNoSuffix;
      try {
        String hashStr = Files.asByteSource(new File(realPath)).hash(Hashing.md5()).toString();
        hashname = nameNoSuffix + "?" + hashStr;
      } catch (IOException e) {
        Logger.error(e);
        hashname = name;
      }
      resources.put(name, hashname);
    }
  }
  return hashname;
}
 
Example 6
Source Project: kylin-on-parquet-v2   Source File: CubeSamplingTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {

    baseCuboidId = (1L << ROW_LENGTH) - 1;
    List<Long> allCuboids = Lists.newArrayList();
    List<Integer[]> allCuboidsBitSetList = Lists.newArrayList();
    for (long i = 1; i < baseCuboidId; i++) {
        allCuboids.add(i);
        addCuboidBitSet(i, allCuboidsBitSetList);
    }

    allCuboidsBitSet = allCuboidsBitSetList.toArray(new Integer[allCuboidsBitSetList.size()][]);
    System.out.println("Totally have " + allCuboidsBitSet.length + " cuboids.");
    allCuboidsHLL = new HLLCounter[allCuboids.size()];
    for (int i = 0; i < allCuboids.size(); i++) {
        allCuboidsHLL[i] = new HLLCounter(14);
    }

    //  hf = Hashing.goodFastHash(32);
    //        hf = Hashing.md5();
    hf = Hashing.murmur3_32();
}
 
Example 7
Source Project: ServerListPlus   Source File: SnakeYAML.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static Path load(Path pluginFolder) throws IOException {
    Path libFolder = pluginFolder.resolve("lib");
    Path path = libFolder.resolve(SNAKE_YAML_JAR);

    if (Files.notExists(path)) {
        Files.createDirectories(libFolder);

        URL url = new URL(SNAKE_YAML);

        String hash;

        try (HashingInputStream his = new HashingInputStream(Hashing.sha1(), url.openStream());
             ReadableByteChannel source = Channels.newChannel(his);
             FileChannel out = FileChannel.open(path, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) {
            out.transferFrom(source, 0, Long.MAX_VALUE);
            hash = his.hash().toString();
        }

        if (!hash.equals(EXPECTED_HASH)) {
            Files.delete(path);
            throw new IOException("Hash mismatch in " + SNAKE_YAML_JAR + ": expected " + EXPECTED_HASH);
        }
    }

    return path;
}
 
Example 8
Source Project: buck   Source File: HeaderSearchPaths.java    License: Apache License 2.0 6 votes vote down vote up
private HashCode getHeaderSymlinkTreeHashCode(
    ImmutableSortedMap<Path, Path> contents,
    boolean shouldCreateHeadersSymlinks,
    boolean shouldCreateHeaderMap) {
  Hasher hasher = Hashing.sha1().newHasher();
  hasher.putBytes(ruleKeyConfiguration.getCoreKey().getBytes(Charsets.UTF_8));
  String symlinkState = shouldCreateHeadersSymlinks ? "symlinks-enabled" : "symlinks-disabled";
  byte[] symlinkStateValue = symlinkState.getBytes(Charsets.UTF_8);
  hasher.putInt(symlinkStateValue.length);
  hasher.putBytes(symlinkStateValue);
  String hmapState = shouldCreateHeaderMap ? "hmap-enabled" : "hmap-disabled";
  byte[] hmapStateValue = hmapState.getBytes(Charsets.UTF_8);
  hasher.putInt(hmapStateValue.length);
  hasher.putBytes(hmapStateValue);
  hasher.putInt(0);
  for (Map.Entry<Path, Path> entry : contents.entrySet()) {
    byte[] key = entry.getKey().toString().getBytes(Charsets.UTF_8);
    byte[] value = entry.getValue().toString().getBytes(Charsets.UTF_8);
    hasher.putInt(key.length);
    hasher.putBytes(key);
    hasher.putInt(value.length);
    hasher.putBytes(value);
  }
  return hasher.hash();
}
 
Example 9
Source Project: nifi   Source File: CorrelationAttributePartitioner.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public QueuePartition getPartition(final FlowFileRecord flowFile, final QueuePartition[] partitions,  final QueuePartition localPartition) {
    final int hash = hash(flowFile);

    // The consistentHash method appears to always return a bucket of '1' if there are 2 possible buckets,
    // so in this case we will just use modulo division to avoid this. I suspect this is a bug with the Guava
    // implementation, but it's not clear at this point.
    final int index;
    if (partitions.length < 3) {
        index = Math.floorMod(hash, partitions.length);
    } else {
        index = Hashing.consistentHash(hash, partitions.length);
    }

    if (logger.isDebugEnabled()) {
        final List<String> partitionDescriptions = new ArrayList<>(partitions.length);
        for (final QueuePartition partition : partitions) {
            partitionDescriptions.add(partition.getSwapPartitionName());
        }

        logger.debug("Assigning Partition {} to {} based on {}", index, flowFile.getAttribute(CoreAttributes.UUID.key()), partitionDescriptions);
    }

    return partitions[index];
}
 
Example 10
@Test
public void testNioUpload() throws Exception {
    if (log.isInfoEnabled()) log.info("TestCase: " + testCase);

    FileUploadClient fileUploadClient = new FileUploadClient();

    Metadata metadata = new Metadata();
    FileMetadata fileMetadata = new FileMetadata();
    fileMetadata.setFile(testCase.testFile.getAbsolutePath());
    fileMetadata.setSize(testCase.testFile.length());
    fileMetadata.setChecksum(Files.hash(testCase.testFile, Hashing.sha256()).toString());
    metadata.setFilesMetadata(Collections.singletonList(fileMetadata));

    VerificationItems verificationItems = fileUploadClient.uploadFile(testCase.testFile, metadata, testCase.url);

    List<VerificationItem> verificationItemList = verificationItems.getVerificationItems();
    for (VerificationItem verificationItem : verificationItemList){
        Assert.assertEquals("Not matching " + verificationItem, "MATCHING", verificationItem.getStatus());
    }

}
 
Example 11
boolean isValid()
{
	File file = getJarFile();

	try
	{
		if (file.exists())
		{
			String hash = Files.asByteSource(file).hash(Hashing.sha256()).toString();
			if (this.hash.equals(hash))
			{
				return true;
			}
		}
	}
	catch (IOException e)
	{
	}
	return false;
}
 
Example 12
Source Project: che   Source File: SHA512PasswordEncryptor.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean test(String password, String passwordHash) {
  requireNonNull(password, "Required non-null password");
  requireNonNull(passwordHash, "Required non-null password's hash");
  // retrieve salt from the hash
  final int passwordHashLength = ENCRYPTED_PASSWORD_BYTES_LENGTH * 2;
  if (passwordHash.length() < passwordHashLength + SALT_BYTES_LENGTH * 2) {
    return false;
  }
  final HashCode saltHash = HashCode.fromString(passwordHash.substring(passwordHashLength));
  // sha1(password + salt)
  final HashCode hash =
      Hashing.sha512()
          .hashBytes(Bytes.concat(password.getBytes(PWD_CHARSET), saltHash.asBytes()));
  // test sha1(password + salt) + salt == passwordHash
  return (hash.toString() + saltHash.toString()).equals(passwordHash);
}
 
Example 13
Source Project: buck   Source File: PathHashingTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void hashDoesNotDependOnFilesystemIterationOrder() throws IOException {
  SettableFakeClock clock = new SettableFakeClock(1000, 0);
  FakeProjectFilesystem filesystem1 = new FakeProjectFilesystem(clock);
  filesystem1.touch(Paths.get("foo/foo.txt"));
  filesystem1.touch(Paths.get("foo/bar.txt"));
  filesystem1.touch(Paths.get("foo/baz.txt"));

  FakeProjectFilesystem filesystem2 = new FakeProjectFilesystem(clock);
  filesystem2.touch(Paths.get("foo/bar.txt"));
  filesystem2.touch(Paths.get("foo/baz.txt"));
  filesystem2.touch(Paths.get("foo/foo.txt"));

  Hasher hasher1 = Hashing.sha1().newHasher();
  PathHashing.hashPath(hasher1, fileHashCache, filesystem1, Paths.get("foo"));

  Hasher hasher2 = Hashing.sha1().newHasher();
  PathHashing.hashPath(hasher2, fileHashCache, filesystem2, Paths.get("foo"));

  assertThat(hasher1.hash(), equalTo(hasher2.hash()));
}
 
Example 14
Source Project: pulsar   Source File: ResourceQuotaCacheTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeMethod
public void setup() throws Exception {
    pulsar = mock(PulsarService.class);
    executor = OrderedScheduler.newSchedulerBuilder().numThreads(1).name("test").build();
    zkc = MockZooKeeper.newInstance();
    zkCache = new LocalZooKeeperCache(zkc, 30, executor);
    localCache = new LocalZooKeeperCacheService(zkCache, null);

    // set mock pulsar localzkcache
    LocalZooKeeperCacheService localZkCache = mock(LocalZooKeeperCacheService.class);
    ZooKeeperDataCache<LocalPolicies> poilciesCache = mock(ZooKeeperDataCache.class);
    when(pulsar.getLocalZkCacheService()).thenReturn(localZkCache);
    when(localZkCache.policiesCache()).thenReturn(poilciesCache);
    doNothing().when(poilciesCache).registerListener(any());
    bundleFactory = new NamespaceBundleFactory(pulsar, Hashing.crc32());

    doReturn(zkCache).when(pulsar).getLocalZkCache();
    doReturn(localCache).when(pulsar).getLocalZkCacheService();
}
 
Example 15
Source Project: soabase   Source File: StandardComponents.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)
{
    String id = UUID.randomUUID().toString();
    for ( int i = 1; i <= 100; ++i )
    {
        System.out.println(Hashing.consistentHash(Hashing.sha256().hashString(id, Charsets.UTF_8), i));
    }
}
 
Example 16
Source Project: intellij   Source File: BlazeEditProjectViewControl.java    License: Apache License 2.0 5 votes vote down vote up
public void update(BlazeNewProjectBuilder builder) {
  this.workspaceData = builder.getWorkspaceData();
  this.projectViewOption = builder.getProjectViewOption();
  WorkspaceRoot workspaceRoot = workspaceData.workspaceRoot();
  WorkspacePath workspacePath = projectViewOption.getSharedProjectView();
  String initialProjectViewText = projectViewOption.getInitialProjectViewText();
  boolean allowAddDefaultValues =
      projectViewOption.allowAddDefaultProjectViewValues()
          && allowAddprojectViewDefaultValues.getValue();
  WorkspacePathResolver workspacePathResolver = workspaceData.workspacePathResolver();

  HashCode hashCode =
      Hashing.md5()
          .newHasher()
          .putUnencodedChars(workspaceRoot.toString())
          .putUnencodedChars(workspacePath != null ? workspacePath.toString() : "")
          .putUnencodedChars(initialProjectViewText != null ? initialProjectViewText : "")
          .putBoolean(allowAddDefaultValues)
          .hash();

  // If any params have changed, reinit the control
  if (!hashCode.equals(paramsHash)) {
    this.paramsHash = hashCode;
    this.isInitialising = true;
    init(
        workspaceData.buildSystem(),
        workspacePathResolver,
        workspacePath,
        initialProjectViewText,
        allowAddDefaultValues);
    this.isInitialising = false;
  }
}
 
Example 17
Source Project: buck   Source File: WorkerProcessPoolTest.java    License: Apache License 2.0 5 votes vote down vote up
private static WorkerProcessPool createPool(
    int maxWorkers, ThrowingSupplier<WorkerProcess, IOException> startWorkerProcess) {
  return new WorkerProcessPool(
      maxWorkers,
      Hashing.sha1().hashLong(0),
      () -> {
        WorkerProcess workerProcess = startWorkerProcess.get();
        workerProcess.ensureLaunchAndHandshake();
        return workerProcess;
      });
}
 
Example 18
Source Project: hawkular-metrics   Source File: MetricsServiceLifecycle.java    License: Apache License 2.0 5 votes vote down vote up
private void persistAdminToken() {
    if (adminToken != null && !adminToken.trim().isEmpty()) {
        String hashedAdminToken = Hashing.sha256().newHasher().putString(adminToken, Charsets.UTF_8).hash()
                .toString();
        configurationService.save("org.hawkular.metrics", "admin.token", hashedAdminToken);
    }
}
 
Example 19
Source Project: presto   Source File: HmacFunctions.java    License: Apache License 2.0 5 votes vote down vote up
@Description("Compute HMAC with MD5")
@ScalarFunction
@SqlType(StandardTypes.VARBINARY)
public static Slice hmacMd5(@SqlType(StandardTypes.VARBINARY) Slice slice, @SqlType(StandardTypes.VARBINARY) Slice key)
{
    return computeHash(Hashing.hmacMd5(key.getBytes()), slice);
}
 
Example 20
Source Project: hawkular-metrics   Source File: AdminFilter.java    License: Apache License 2.0 5 votes vote down vote up
private boolean validAdminToken(String adminToken) {
    if (savedAdminToken == null) {
        savedAdminToken = configurationService.load("org.hawkular.metrics", "admin.token").toBlocking()
                .firstOrDefault("");
    }

    adminToken = Hashing.sha256().newHasher().putString(adminToken, Charsets.UTF_8).hash().toString();

    if (adminToken.equals(savedAdminToken)) {
        return true;
    }

    return false;
}
 
Example 21
Source Project: spider   Source File: CommonWebpagePipeline.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void process(ResultItems resultItems, Task task) {
    SpiderInfo spiderInfo = resultItems.get("spiderInfo");
    Webpage webpage = convertResultItems2Webpage(resultItems);
    try {
        client.prepareIndex(INDEX_NAME, TYPE_NAME)
                .setId(Hashing.md5().hashString(webpage.getUrl(), Charset.forName("utf-8")).toString())
                .setSource(gson.toJson(webpage))
                .get();
    } catch (Exception e) {
        LOG.error("索引 Webpage 出错," + e.getLocalizedMessage());
    }
}
 
Example 22
Source Project: buck   Source File: CustomJarOutputStreamTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void manifestContainsEntryHashesOfEmptyHashedEntries() throws IOException {
  String entryName = "A";
  InputStream contents = new ByteArrayInputStream(new byte[0]);
  try (HashingInputStream hashingContents =
      new HashingInputStream(Hashing.murmur3_128(), contents)) {
    writer.putNextEntry(new CustomZipEntry(entryName));
    writer.closeEntry();
    writer.close();

    String expectedHash = hashingContents.hash().toString();
    assertEntryHash(entryName, expectedHash);
  }
}
 
Example 23
Source Project: quilt   Source File: AesGcmStreamEncryptionService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>Decrypts {@code cipherMessage} using the standard byte arrangement of the embedded ciphertext where the
 * AuthTag goes last, as specified by NIST.</p>
 *
 * @param sharedSecret  A {@link SharedSecret} used for encryption.
 * @param cipherMessage A byte-array to decrypt.
 *
 * @return A byte-array containing decrypted plaintext.
 *
 * @see "https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf"
 */
private byte[] standardModeDecrypt(final SharedSecret sharedSecret, final byte[] cipherMessage) {
  Objects.requireNonNull(cipherMessage);

  byte[] encryptionKey = Hashing.hmacSha256(sharedSecret.key()).hashBytes(ENCRYPTION_KEY_STRING).asBytes();
  final SecretKey typedEncryptionKey = new SecretKeySpec(encryptionKey, "AES");

  // First, deconstruct the message
  try {
    ByteBuffer byteBuffer = ByteBuffer.wrap(cipherMessage);
    byte[] iv = new byte[AES_GCM_NONCE_IV_LENGTH];
    byteBuffer.get(iv);
    byte[] cipherText = new byte[byteBuffer.remaining()];
    byteBuffer.get(cipherText);

    final Cipher cipher = Cipher.getInstance(CIPHER_ALGO);
    cipher.init(Cipher.DECRYPT_MODE, typedEncryptionKey, new GCMParameterSpec(AUTH_TAG_LENGTH_BITS, iv));
    byte[] plainText = cipher.doFinal(cipherText);

    // It is best practice to try to wipe sensible data like a cryptographic key or IV from memory as fast as
    // possible. Since Java is a language with automatic memory management, we don’t have any guarantees that the
    // following works as intended, but it should in most cases:
    Arrays.fill(iv, (byte) 0); //overwrite the content of key with zeros
    Arrays.fill(encryptionKey, (byte) 0);

    return plainText;
  } catch (Exception e) {
    throw new EncryptionException(e.getMessage(), e);
  }
}
 
Example 24
Source Project: Flashtool   Source File: AESOutputStream.java    License: GNU General Public License v3.0 5 votes vote down vote up
public AESOutputStream(OutputStream out) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, NoSuchProviderException, InvalidAlgorithmParameterException {
       if (Security.getProvider("BC") == null) {
           Security.addProvider(new BouncyCastleProvider());
       }
       SecretKeySpec secretKeySpec = new SecretKeySpec(Hashing.sha256().hashBytes(OS.AESKey.getBytes("UTF-8")).asBytes(), "AES");
   	IvParameterSpec ivParameterSpec = new IvParameterSpec(BaseEncoding.base16().decode(OS.AESIV));
   	Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
   	cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
   	localCipherOutputStream = new CipherOutputStream(out, cipher);
}
 
Example 25
Source Project: spork   Source File: LogicalPlan.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the signature of the LogicalPlan. The signature is a unique identifier for a given
 * plan generated by a Pig script. The same script run multiple times with the same version of
 * Pig is guaranteed to produce the same signature, even if the input or output locations differ.
 *
 * @return a unique identifier for the logical plan
 * @throws FrontendException if signature can't be computed
 */
public String getSignature() throws FrontendException {

    // Use a streaming hash function. We use a murmur_32 function with a constant seed, 0.
    HashFunction hf = Hashing.murmur3_32(0);
    HashOutputStream hos = new HashOutputStream(hf);
    PrintStream ps = new PrintStream(hos);

    LogicalPlanPrinter printer = new LogicalPlanPrinter(this, ps);
    printer.visit();

    return Integer.toString(hos.getHashCode().asInt());
}
 
Example 26
Source Project: buck   Source File: FileHashTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void returnsCorrectHashCodeAndHashFunctionForSha256() {
  FileHash hash =
      FileHash.ofSha256(
          HashCode.fromString(
              "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"));
  Assert.assertEquals(Hashing.sha256(), hash.getHashFunction());
  Assert.assertEquals(
      HashCode.fromString("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"),
      hash.getHashCode());
}
 
Example 27
public long computeMD5() throws IOException {
  InputSupplier<InputStream> supplier = new InputSupplier<InputStream>() {
    public InputStream getInput() throws IOException {
      return newInputStream();
    }
  };
  return ByteStreams.hash(supplier, Hashing.md5()).asLong();
}
 
Example 28
Source Project: nakadi   Source File: HashGenerator.java    License: MIT License 5 votes vote down vote up
public String generateSubscriptionKeyFieldsHash(final SubscriptionBase subscription) {
    final Hasher hasher = Hashing.md5()
            .newHasher()
            .putString(subscription.getOwningApplication(), UTF_8)
            .putString(subscription.getConsumerGroup(), UTF_8);
    subscription.getEventTypes()
            .stream()
            .sorted()
            .forEach(et -> hasher.putString(et, UTF_8));
    return hasher.hash().toString();
}
 
Example 29
Source Project: xyz-hub   Source File: Hasher.java    License: Apache License 2.0 5 votes vote down vote up
public static final String getHash(String toBeHashed) {
  //noinspection UnstableApiUsage
  return Hashing.murmur3_128().newHasher()
      .putString(toBeHashed, Charset.defaultCharset())
      .hash()
      .toString();
}
 
Example 30
Source Project: servicecomb-java-chassis   Source File: SignatureUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String genSignature(HttpServletResponseEx responseEx) {
  Hasher hasher = Hashing.sha256().newHasher();
  byte[] bytes = responseEx.getBodyBytes();
  if (bytes != null) {
    hasher.putBytes(bytes, 0, responseEx.getBodyBytesLength());
  }

  return hasher.hash().toString();
}