Java Code Examples for com.google.common.hash.HashCode#toString()

The following examples show how to use com.google.common.hash.HashCode#toString() . 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: AtlasDataBindingMergeArtifactsTransform.java    From atlas with Apache License 2.0 6 votes vote down vote up
/**
 * Files exported from jars are exported into a certain folder so that we can rebuild them
 * when the related jar file changes.
 */
@NonNull
private static String getJarFilePrefix(@NonNull File inputFile) {
    // get the filename
    String name = inputFile.getName();
    // remove the extension
    int pos = name.lastIndexOf('.');
    if (pos != -1) {
        name = name.substring(0, pos);
    }

    // add a hash of the original file path.
    String input = inputFile.getAbsolutePath();
    HashFunction hashFunction = Hashing.sha1();
    HashCode hashCode = hashFunction.hashString(input, Charsets.UTF_16LE);

    return name + "-" + hashCode.toString();
}
 
Example 2
Source File: AwbDataBindingMergeArtifactsTask.java    From atlas with Apache License 2.0 6 votes vote down vote up
/**
 * Files exported from jars are exported into a certain folder so that we can rebuild them
 * when the related jar file changes.
 */
@NonNull
private static String getJarFilePrefix(@NonNull File inputFile) {
    // get the filename
    String name = inputFile.getName();
    // remove the extension
    int pos = name.lastIndexOf('.');
    if (pos != -1) {
        name = name.substring(0, pos);
    }

    // add a hash of the original file path.
    String input = inputFile.getAbsolutePath();
    HashFunction hashFunction = Hashing.sha1();
    HashCode hashCode = hashFunction.hashString(input, Charsets.UTF_16LE);

    return name + "-" + hashCode.toString();
}
 
Example 3
Source File: ConanHostedMetadataFacetSupport.java    From nexus-repository-conan with Eclipse Public License 1.0 6 votes vote down vote up
@Nullable
@TransactionalTouchBlob
public String getHash(final String path) {
  checkNotNull(path);

  StorageTx tx = UnitOfWork.currentTx();

  Asset asset = findAsset(tx, tx.findBucket(getRepository()), path);
  if (asset == null) {
    return null;
  }
  HashCode checksum = asset.getChecksum(HashAlgorithm.MD5);
  if (checksum == null) {
    return null;
  }
  return checksum.toString();
}
 
Example 4
Source File: FileUtils.java    From AnoleFix with MIT License 6 votes vote down vote up
/**
 * Chooses a directory name, based on a JAR file name, considering exploded-aar and classes.jar.
 */

public static String getDirectoryNameForJar(File inputFile) {
    // add a hash of the original file path.
    HashFunction hashFunction = Hashing.sha1();
    HashCode hashCode = hashFunction.hashString(inputFile.getAbsolutePath(), Charsets.UTF_16LE);

    String name = Files.getNameWithoutExtension(inputFile.getName());
    if (name.equals("classes") && inputFile.getAbsolutePath().contains("exploded-aar")) {
        // This naming scheme is coming from DependencyManager#computeArtifactPath.
        File versionDir = inputFile.getParentFile().getParentFile();
        File artifactDir = versionDir.getParentFile();
        File groupDir = artifactDir.getParentFile();

        name = Joiner.on('-').join(
                groupDir.getName(), artifactDir.getName(), versionDir.getName());
    }
    name = name + "_" + hashCode.toString();
    return name;
}
 
Example 5
Source File: AbstractQEmuExample.java    From qemu-java with GNU General Public License v2.0 5 votes vote down vote up
@Nonnull
private File download(@Nonnull URI source) throws IOException {
    File dir = new File("build/images/downloaded");
    HashCode hash = Hashing.md5().hashString(source.toString(), Charsets.UTF_8);
    File file = new File(dir, hash.toString());
    if (!file.exists()) {
        InputStream in = source.toURL().openStream();
        try {
            Files.asByteSink(file).writeFrom(in);
        } finally {
            Closeables.close(in, false);
        }
    }
    return file;
}
 
Example 6
Source File: SHA512PasswordEncryptor.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String encrypt(String password) {
  requireNonNull(password, "Required non-null password");
  // generate salt
  final byte[] salt = new byte[SALT_BYTES_LENGTH];
  SECURE_RANDOM.nextBytes(salt);
  // sha512(password + salt)
  final HashCode hash =
      Hashing.sha512().hashBytes(Bytes.concat(password.getBytes(PWD_CHARSET), salt));
  final HashCode saltHash = HashCode.fromBytes(salt);
  // add salt to the hash, result length (512 / 8) * 2 + (64 / 8) * 2 = 144
  return hash.toString() + saltHash.toString();
}
 
Example 7
Source File: ModernBuildRuleRemoteExecutionHelper.java    From buck with Apache License 2.0 5 votes vote down vote up
Node(AddsToRuleKey instance, byte[] data, HashCode hash, ImmutableSortedSet<Node> children) {
  this.instance = instance;
  this.data = data;
  this.dataRef = new WeakReference<>(data);
  this.dataLength = data.length;
  this.hash = hash.toString();
  this.children = children;
}
 
Example 8
Source File: MavenIOUtils.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
public static Map<HashType, Payload> hashesToPayloads(final Map<HashAlgorithm, HashCode> hashCodes)
{
  Map<HashType, Payload> payloadByHash = new EnumMap<>(HashType.class);
  for (HashType hashType : HashType.values()) {
    HashCode hashCode = hashCodes.get(hashType.getHashAlgorithm());
    if (hashCode != null) {
      Payload payload = new StringPayload(hashCode.toString(), CHECKSUM_CONTENT_TYPE);
      payloadByHash.put(hashType, payload);
    }
  }
  return payloadByHash;
}
 
Example 9
Source File: OrientPyPiHostedFacetImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private void validateMd5Hash(final Map<String, String> attributes, final TempBlob tempBlob) {
  if (attributes.containsKey("md5_digest")) {
    String expectedDigest = attributes.get("md5_digest");
    HashCode hashCode = tempBlob.getHashes().get(MD5);
    String hashValue = hashCode.toString();
    if (!expectedDigest.equalsIgnoreCase(hashValue)) {
      throw new IllegalOperationException(
          "Digests do not match, found: " + hashValue + ", expected: " + expectedDigest);
    }
  }
}
 
Example 10
Source File: ArtifactManager.java    From Singularity with Apache License 2.0 5 votes vote down vote up
private String calculateMd5sum(Path path) {
  try {
    HashCode hc = com
      .google.common.io.Files.asByteSource(path.toFile())
      .hash(Hashing.md5());
    return hc.toString();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 11
Source File: AbstractStreamingFingerprintComputer.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public String computeFingerprint(final EObject object) {
  if (object == null) {
    return null;
  }
  Hasher hasher = HASH_FUNCTION.newHasher();
  fingerprint(object, hasher);
  HashCode export = hasher.hash();
  if (export.equals(NO_EXPORT)) {
    return null;
  }
  return export.toString();
}
 
Example 12
Source File: FeedController.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
MemoizedFeed(FeedResult feedResult)
{
	this.feedResult = feedResult;

	Hasher hasher = Hashing.sha256().newHasher();
	for (FeedItem itemPrice : feedResult.getItems())
	{
		hasher.putBytes(itemPrice.getTitle().getBytes()).putBytes(itemPrice.getContent().getBytes());
	}
	HashCode code = hasher.hash();
	hash = code.toString();
}
 
Example 13
Source File: FileUtils.java    From swift-explorer with Apache License 2.0 5 votes vote down vote up
public static String readAllAndgetMD5 (InputStream in) throws IOException
{
	com.google.common.hash.HashingInputStream his = null ;
	try
	{
		his = new com.google.common.hash.HashingInputStream (Hashing.md5(), in) ;
		
		final int bufferSize = 2097152 ;
		final ReadableByteChannel inputChannel = Channels.newChannel(his);
		final ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize);
		while (inputChannel.read(buffer) != -1) {
			buffer.clear();
		}
		/*
		byte[] bytesBuffer = new byte[bufferSize] ;
		int r = his.read(bytesBuffer, 0, bufferSize) ;
		while (r != -1)
			r = his.read(bytesBuffer) ;
		*/
		HashCode hc = his.hash() ;
		return (hc != null) ? (hc.toString()) : (null) ;
	}
	finally
	{
		if (his != null)
			his.close() ;
	}
}
 
Example 14
Source File: VerifyPayloadHandlingComponentTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
/**
 * @return The MD5 hash of the given payload. This can be used to verify correctness when sending payloads across the wire.
 */
private static String getHashForPayload(byte[] payloadBytes) {
    Hasher hasher = hashFunction.newHasher();

    hasher = hasher.putBytes(payloadBytes);

    HashCode hc = hasher.hash();
    return hc.toString();
}
 
Example 15
Source File: Launcher.java    From launcher with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static byte[] download(String path, String hash, IntConsumer progress) throws IOException, VerificationException
{
	HashFunction hashFunction = Hashing.sha256();
	Hasher hasher = hashFunction.newHasher();
	ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

	URL url = new URL(path);
	HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	conn.setRequestProperty("User-Agent", USER_AGENT);
	conn.getResponseCode();

	InputStream err = conn.getErrorStream();
	if (err != null)
	{
		err.close();
		throw new IOException("Unable to download " + path + " - " + conn.getResponseMessage());
	}

	int downloaded = 0;
	try (InputStream in = conn.getInputStream())
	{
		int i;
		byte[] buffer = new byte[1024 * 1024];
		while ((i = in.read(buffer)) != -1)
		{
			byteArrayOutputStream.write(buffer, 0, i);
			hasher.putBytes(buffer, 0, i);
			downloaded += i;
			progress.accept(downloaded);
		}
	}

	HashCode hashCode = hasher.hash();
	if (!hash.equals(hashCode.toString()))
	{
		throw new VerificationException("Unable to verify resource " + path + " - expected " + hash + " got " + hashCode.toString());
	}

	return byteArrayOutputStream.toByteArray();
}
 
Example 16
Source File: Tools.java    From torrenttunes-client with GNU General Public License v3.0 5 votes vote down vote up
public static String sha2FileChecksum(File file) {
	HashCode hc = null;
	try {
		hc = Files.hash(file, Hashing.sha256());
	} catch (IOException e) {
		e.printStackTrace();
	}
	return hc.toString();
}
 
Example 17
Source File: FileUtils.java    From swift-explorer with Apache License 2.0 5 votes vote down vote up
public static String getMD5 (File file) throws IOException
{
	if (file.isDirectory())
		return emptyMd5 ;
	HashCode hc = com.google.common.io.Files.hash(file, Hashing.md5());
	return (hc != null) ? (hc.toString()) : (null) ;
}
 
Example 18
Source File: OwlApiUtils.java    From SciGraph with Apache License 2.0 4 votes vote down vote up
static String hash(String input) {
  // TODO: This may negatively impact performance but will reduce hash collisions. #150
  HashCode code = HASHER.newHasher().putString(input, Charsets.UTF_8).hash();
  return code.toString();
}
 
Example 19
Source File: PasswordHasher.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public static String sha256(String salt, String password) {
    if (salt == null) salt = "";
    byte[] bytes = (salt + password).getBytes(Charsets.UTF_8);
    HashCode hash = Hashing.sha256().hashBytes(bytes);
    return hash.toString();
}
 
Example 20
Source File: Tools.java    From torrenttunes-client with GNU General Public License v3.0 3 votes vote down vote up
public static String getIPHash() {

		// IP address is mixed with the users home directory, 
		// so that it can't be decrypted by the server.

		String text = DataSources.EXTERNAL_IP + System.getProperty("user.home");

		HashFunction hf = Hashing.md5();
		HashCode hc = hf.hashString(text, Charsets.UTF_8);

		String ipHash = hc.toString();

		return ipHash;
	}