Java Code Examples for com.google.common.hash.Hashing#sha1()

The following examples show how to use com.google.common.hash.Hashing#sha1() . 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: PreDex.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a unique File for the pre-dexed library, even
 * if there are 2 libraries with the same file names (but different
 * paths)
 * <p>
 * If multidex is enabled the return File is actually a folder.
 *
 * @param outFolder the output folder.
 * @param inputFile the library.
 */
@NonNull
static File getDexFileName(@NonNull File outFolder, @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 new File(outFolder, name + "-" + hashCode.toString() + SdkConstants.DOT_JAR);
}
 
Example 4
Source File: SerializableSaltedHasher.java    From CuckooFilter4J with Apache License 2.0 6 votes vote down vote up
private static HashFunction configureHash(Algorithm alg, long seedNSalt, long addlSipSeed) {
	switch (alg) {
	case xxHash64:
		return new xxHashFunction(seedNSalt);
	case Murmur3_128:
		return Hashing.murmur3_128((int) seedNSalt);
	case Murmur3_32:
		return Hashing.murmur3_32((int) seedNSalt);
	case sha256:
		return Hashing.sha1();
	case sipHash24:
		return Hashing.sipHash24(seedNSalt, addlSipSeed);
	default:
		throw new IllegalArgumentException("Invalid Enum Hashing Algorithm???");
	}
}
 
Example 5
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 6
Source File: HashingUtil.java    From datacollector with Apache License 2.0 6 votes vote down vote up
public static HashFunction getHasher(HashType hashType) {
  switch(hashType) {
    case MURMUR3_128:
      return Hashing.murmur3_128();
    case MURMUR3_32:
      return Hashing.murmur3_32();
    case SIPHASH24:
      return Hashing.sipHash24();
    case MD5:
      return Hashing.md5();
    case SHA1:
      return Hashing.sha1();
    case SHA256:
      return Hashing.sha256();
    case SHA512:
      return Hashing.sha512();
    case ADLER32:
      return Hashing.adler32();
    case CRC32:
      return Hashing.crc32();
    case CRC32C:
      return Hashing.crc32c();
    default:
      throw new IllegalArgumentException(Utils.format("Unsupported Hashing Algorithm: {}", hashType.name()));
  }
}
 
Example 7
Source File: Hasher.java    From datafu with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the HashFunction named by algorithm
 *
 * See the Hasher class docs for a list of algorithms and guidance on selection.
 *
 * @param algorithm the hash algorithm to use
 * @throws IllegalArgumentException for an invalid seed given the algorithm
 * @throws RuntimeException when the seed cannot be parsed
 */
private void makeHashFunc(String algorithm) throws IllegalArgumentException, RuntimeException
{
  if (hash_func != null) { throw new RuntimeException("The hash function should only be set once per instance"); }

  if (algorithm.startsWith("good-")) {
    int bits = Integer.parseInt(algorithm.substring(5));
    hash_func = Hashing.goodFastHash(bits);
  }
  else if (algorithm.equals("murmur3-32")) { hash_func = Hashing.murmur3_32();  }
  else if (algorithm.equals("murmur3-128")){ hash_func = Hashing.murmur3_128(); }
  else if (algorithm.equals("sip24"))      { hash_func = Hashing.sipHash24();   }
  else if (algorithm.equals("sha1"))       { hash_func = Hashing.sha1();        }
  else if (algorithm.equals("sha256"))     { hash_func = Hashing.sha256();      }
  else if (algorithm.equals("sha512"))     { hash_func = Hashing.sha512();      }
  else if (algorithm.equals("md5"))        { hash_func = Hashing.md5();         }
  else if (algorithm.equals("adler32"))    { hash_func = Hashing.adler32();     }
  else if (algorithm.equals("crc32"))      { hash_func = Hashing.crc32();       }
  else { throw new IllegalArgumentException("No hash function found for algorithm "+algorithm+". Allowed values include "+HASH_NAMES); }
}
 
Example 8
Source File: AndroidBinaryIntegrationTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testEditingPrimaryDexClassForcesRebuildForSimplePackage() throws IOException {
  BuildTarget buildTarget = BuildTargetFactory.newInstance(SIMPLE_TARGET);
  Path outputPath = BuildTargetPaths.getGenPath(filesystem, buildTarget, "%s.apk");
  HashFunction hashFunction = Hashing.sha1();
  String dexFileName = "classes.dex";

  workspace.runBuckdCommand("build", SIMPLE_TARGET).assertSuccess();
  ZipInspector zipInspector = new ZipInspector(workspace.getPath(outputPath));
  HashCode originalHash = hashFunction.hashBytes(zipInspector.getFileContents(dexFileName));

  workspace.replaceFileContents(
      "java/com/sample/app/MyApplication.java", "MyReplaceableName", "ChangedValue");

  workspace.resetBuildLogFile();
  ProcessResult result = workspace.runBuckdCommand("build", SIMPLE_TARGET);
  result.assertSuccess();
  BuckBuildLog buildLog = workspace.getBuildLog();
  buildLog.assertTargetBuiltLocally(SIMPLE_TARGET);

  HashCode hashAfterChange = hashFunction.hashBytes(zipInspector.getFileContents(dexFileName));
  assertThat(
      "MyApplication.java file has been edited. Final artifact hash must change as well",
      originalHash,
      is(not(equalTo(hashAfterChange))));
}
 
Example 9
Source File: SnakeYAML.java    From ServerListPlus with 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 10
Source File: WebSocketServerInputStream.java    From xtext-languageserver-example with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Perform the initial WebSocket handshake. WebSockets connect with an
 * HTTP Request to upgrade the connection to a WebSocket connection. This
 * method ensures that the request is correctly formed, and provides
 * the appropriate response to the client. After this method is called,
 * further communication is performed solely with WebSocket frames.
 * @throws IOException if anything goes wrong with the underlying stream
 */
private void shakeHands() throws IOException {
    HttpRequest req = new HttpRequest(inputStream);
    String requestLine = req.get(HttpRequest.REQUEST_LINE);
    handshakeComplete = checkStartsWith(requestLine, "GET /")
        && checkContains(requestLine, "HTTP/")
        && req.get("Host") != null
        && checkContains(req.get("Upgrade"), "websocket")
        && checkContains(req.get("Connection"), "Upgrade")
        && "13".equals(req.get("Sec-WebSocket-Version"))
        && req.get("Sec-WebSocket-Key") != null;
    String nonce = req.get("Sec-WebSocket-Key");
    if (handshakeComplete) {
        byte[] nonceBytes = BaseEncoding.base64().decode(nonce);
        if (nonceBytes.length != HANDSHAKE_NONCE_LENGTH) {
            handshakeComplete = false;
        }
    }
    // if we have met all the requirements
    if (handshakeComplete) {
        outputPeer.write(asUTF8("HTTP/1.1 101 Switching Protocols\r\n"));
        outputPeer.write(asUTF8("Upgrade: websocket\r\n"));
        outputPeer.write(asUTF8("Connection: upgrade\r\n"));
        outputPeer.write(asUTF8("Sec-WebSocket-Accept: "));
        HashFunction hf = Hashing.sha1();
        HashCode hc = hf.newHasher()
            .putString(nonce, StandardCharsets.UTF_8)
            .putString(WEBSOCKET_ACCEPT_UUID, StandardCharsets.UTF_8)
            .hash();
        String acceptKey = BaseEncoding.base64().encode(hc.asBytes());
        outputPeer.write(asUTF8(acceptKey));
        outputPeer.write(asUTF8("\r\n\r\n"));
    }
    outputPeer.setHandshakeComplete(handshakeComplete);
}
 
Example 11
Source File: JPAUser.java    From james-project with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private static HashFunction chooseHashing(String algorithm) {
    switch (algorithm) {
        case "MD5":
            return Hashing.md5();
        case "SHA-256":
            return Hashing.sha256();
        case "SHA-512":
            return Hashing.sha512();
        default:
            return Hashing.sha1();
    }
}
 
Example 12
Source File: FileHash.java    From buck with Apache License 2.0 5 votes vote down vote up
/** Get the hash function for this type of hash */
public HashFunction getHashFunction() {
  if (sha1OrSha256.isLeft()) {
    return Hashing.sha1();
  } else {
    return Hashing.sha256();
  }
}
 
Example 13
Source File: TargetsCommand.java    From buck with Apache License 2.0 5 votes vote down vote up
private HashFunction getHashFunction() {
  switch (targetHashFunction) {
    case SHA1:
      return Hashing.sha1();
    case MURMUR_HASH3:
      return Hashing.murmur3_128();
  }
  throw new UnsupportedOperationException();
}
 
Example 14
Source File: KeyHasher.java    From EVCache with Apache License 2.0 4 votes vote down vote up
public static String getHashedKey(String key, String hashingAlgorithm) {
    final long start = System.nanoTime();
    HashFunction hf = null; 
    switch(hashingAlgorithm.toLowerCase()) {
        case "murmur3" :
            hf = Hashing.murmur3_128();
            break;

        case "adler32" :
            hf = Hashing.adler32();
            break;

        case "crc32" :
            hf = Hashing.crc32();
            break;

        case "sha1" :
            hf = Hashing.sha1();
            break;

        case "sha256" :
            hf = Hashing.sha256();
            break;

        case "siphash24" :
            hf = Hashing.sipHash24();
            break;

        case "goodfasthash" :
            hf = Hashing.goodFastHash(128);
            break;

        case "md5" :
        default :
            hf = Hashing.md5();
            break;
    }

    final HashCode hc = hf.newHasher().putString(key, Charsets.UTF_8).hash();
    final byte[] digest = hc.asBytes();
    if(log.isDebugEnabled()) log.debug("Key : " + key +"; digest length : " + digest.length + "; byte Array contents : " + Arrays.toString(digest) );
    final String hKey = encoder.encodeToString(digest);
    if(log.isDebugEnabled()) log.debug("Key : " + key +"; Hashed & encoded key : " + hKey + "; Took " + (System.nanoTime() - start) + " nanos");
    return hKey;
}
 
Example 15
Source File: ElementUtils.java    From antiquity with GNU General Public License v3.0 3 votes vote down vote up
/**
 * <p>
 * Calculate the private hash of an {@link Element}.
 * </p>
 * 
 * <p>
 * The private hash contains only the properties of the {@link Element},
 * without its associated elements.
 * </p>
 * 
 * <p>
 * The hash is calculated based on SHA1 algorithm
 * </p>
 * 
 * TODO Handle arrays values properly.
 * 
 * @param element The element to calculate the private hash for.
 * @param excludedKeys the keys to exclude when hash is calculated.
 * @return A string representation of the hash
 * @see HashCode#toString()
 */
public static String calculateElementPrivateHash(Element element, Set<String> excludedKeys) {
    Map<String, Object> props = ElementUtils.getPropertiesAsMap(element, excludedKeys);
    Joiner.MapJoiner propsJoiner = Joiner.on('&').withKeyValueSeparator("=");

    HashFunction hf = Hashing.sha1();
    Hasher h = hf.newHasher();

    //h.putString("[" + element.getId().toString() + "]");
    h.putString(propsJoiner.join(props), Charset.defaultCharset());

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