Ejemplo n.º 1
0
  @Test
  public void shouldSetUpAPrivateLibraryIfGivenAMavenCoordWithoutDeps() throws Exception {
    resolver.resolve("com.example:no-deps:jar:1.0");

    Path groupDir = thirdParty.resolve("example");
    assertTrue(Files.exists(groupDir));

    Path original = repo.resolve("com/example/no-deps/1.0/no-deps-1.0.jar");
    HashCode expected = MorePaths.asByteSource(original).hash(Hashing.sha1());
    Path jarFile = groupDir.resolve("no-deps-1.0.jar");
    HashCode seen = MorePaths.asByteSource(jarFile).hash(Hashing.sha1());
    assertEquals(expected, seen);

    List<Map<String, Object>> rules = buildFileParser.getAll(groupDir.resolve("BUCK"));

    assertEquals(1, rules.size());
    Map<String, Object> rule = rules.get(0);
    // Name is derived from the project identifier
    assertEquals("no-deps", rule.get("name"));

    // The binary jar should be set
    assertEquals("no-deps-1.0.jar", rule.get("binaryJar"));

    // There was no source jar in the repo
    assertTrue(rule.containsKey("sourceJar"));
    assertNull(rule.get("sourceJar"));

    // Nothing depends on this, so it's not visible
    assertEquals(ImmutableList.of(), rule.get("visibility"));

    // And it doesn't depend on anything
    assertEquals(ImmutableList.of(), rule.get("deps"));
  }
Ejemplo n.º 2
0
 /**
  * Non-idempotent RuleKeys are normally output as strings of 'x' characters, but when comparing
  * two sets of RuleKeys in textual form it is necessary to mangle one of the two sets, so that
  * non-idempotent RuleKeys are never considered equal.
  */
 public String toString(boolean mangleNonIdempotent) {
   if (!isIdempotent()) {
     return new String(new char[Hashing.sha1().bits() / 4])
         .replace("\0", mangleNonIdempotent ? "y" : "x");
   }
   return hashCode.toString();
 }
  @Test
  public void testComputeAbiKey() {
    ImmutableSortedMap<String, HashCode> classNamesAndHashes =
        ImmutableSortedMap.of(
            "com/example/Foo", HashCode.fromString("e4fccb7520b7795e632651323c63217c9f59f72a"),
            "com/example/Bar", HashCode.fromString("087b7707a5f8e0a2adf5652e3cd2072d89a197dc"),
            "com/example/Baz", HashCode.fromString("62b1c2510840c0de55c13f66065a98a719be0f19"));
    String observedSha1 = DexProducedFromJavaLibrary.computeAbiKey(classNamesAndHashes).getHash();

    String expectedSha1 =
        Hashing.sha1()
            .newHasher()
            .putUnencodedChars("com/example/Bar")
            .putByte((byte) 0)
            .putUnencodedChars("087b7707a5f8e0a2adf5652e3cd2072d89a197dc")
            .putByte((byte) 0)
            .putUnencodedChars("com/example/Baz")
            .putByte((byte) 0)
            .putUnencodedChars("62b1c2510840c0de55c13f66065a98a719be0f19")
            .putByte((byte) 0)
            .putUnencodedChars("com/example/Foo")
            .putByte((byte) 0)
            .putUnencodedChars("e4fccb7520b7795e632651323c63217c9f59f72a")
            .putByte((byte) 0)
            .hash()
            .toString();
    assertEquals(expectedSha1, observedSha1);
  }
Ejemplo n.º 4
0
  @Override
  public void scrubFile(FileChannel file) throws IOException, ScrubException {
    if (!Machos.isMacho(file)) {
      return;
    }

    long size = file.size();
    MappedByteBuffer map = file.map(FileChannel.MapMode.READ_WRITE, 0, size);

    try {
      Machos.setUuid(map, ZERO_UUID);
    } catch (Machos.MachoException e) {
      throw new ScrubException(e.getMessage());
    }
    map.rewind();

    Hasher hasher = Hashing.sha1().newHasher();
    while (map.hasRemaining()) {
      hasher.putByte(map.get());
    }

    map.rewind();
    try {
      Machos.setUuid(map, Arrays.copyOf(hasher.hash().asBytes(), 16));
    } catch (Machos.MachoException e) {
      throw new ScrubException(e.getMessage());
    }
  }
Ejemplo n.º 5
0
 private Builder() {
   hasher = Hashing.sha1().newHasher();
   idempotent = true;
   if (logger.isLoggable(Level.INFO)) {
     logElms = Lists.newArrayList();
   }
   setBuckVersionUID();
 }
Ejemplo n.º 6
0
 private String generateHashKey(StringBuilder hashSourceBuilder, String apiKey) {
   String hashSource = hashSourceBuilder.toString() + apiKey;
   HashCode hashCode = Hashing.sha1().hashString(hashSource, Charset.defaultCharset());
   Log.d(
       LOG_TAG,
       String.format("creating sha1 from [%s] resulted with hash [%s]", hashSource, hashCode));
   return hashCode.toString();
 }
Ejemplo n.º 7
0
 static {
   HASH_FUNCTIONS.put("md5", Hashing.md5());
   HASH_FUNCTIONS.put("sha1", Hashing.sha1());
   HASH_FUNCTIONS.put("sha256", Hashing.sha256());
   HASH_FUNCTIONS.put("sha512", Hashing.sha512());
   HASH_FUNCTIONS.put("murmur3_32", Hashing.murmur3_32());
   HASH_FUNCTIONS.put("murmur3_128", Hashing.murmur3_128());
 }
Ejemplo n.º 8
0
 /** Does not support symlinks. */
 @Override
 public String computeSha1(Path pathRelativeToProjectRootOrJustAbsolute) throws IOException {
   if (!exists(pathRelativeToProjectRootOrJustAbsolute)) {
     throw new FileNotFoundException(pathRelativeToProjectRootOrJustAbsolute.toString());
   }
   return Hashing.sha1()
       .hashBytes(getFileBytes(pathRelativeToProjectRootOrJustAbsolute))
       .toString();
 }
 @VisibleForTesting
 static Sha1HashCode computeAbiKey(ImmutableSortedMap<String, HashCode> classNames) {
   Hasher hasher = Hashing.sha1().newHasher();
   for (Map.Entry<String, HashCode> entry : classNames.entrySet()) {
     hasher.putUnencodedChars(entry.getKey());
     hasher.putByte((byte) 0);
     hasher.putUnencodedChars(entry.getValue().toString());
     hasher.putByte((byte) 0);
   }
   return Sha1HashCode.fromHashCode(hasher.hash());
 }
Ejemplo n.º 10
0
 private String generateHash(@Nonnull List<TableRow> rows) {
   List<HashCode> rowHashes = Lists.newArrayList();
   for (TableRow row : rows) {
     List<String> cellsInOneRow = Lists.newArrayList();
     for (TableCell cell : row.getF()) {
       cellsInOneRow.add(Objects.toString(cell.getV()));
       Collections.sort(cellsInOneRow);
     }
     rowHashes.add(Hashing.sha1().hashString(cellsInOneRow.toString(), StandardCharsets.UTF_8));
   }
   return Hashing.combineUnordered(rowHashes).toString();
 }
Ejemplo n.º 11
0
  private HashCode writeSimpleJarAndGetHash() throws Exception {
    try (FileOutputStream fileOutputStream = new FileOutputStream(output.toFile());
        ZipOutputStream out = new JarOutputStream(fileOutputStream)) {
      ZipEntry entry = new CustomZipEntry("test");
      out.putNextEntry(entry);
      out.write(new byte[0]);
      entry = new ZipEntry("test1");
      entry.setTime(ZipConstants.getFakeTime());
      out.putNextEntry(entry);
      out.write(new byte[0]);
    }

    return Hashing.sha1().hashBytes(Files.readAllBytes(output));
  }
  public void testHashTwice() {
    Hasher sha1 = Hashing.sha1().newHasher();

    assertEquals(
        "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12",
        sha1.putString("The quick brown fox jumps over the lazy dog", Charsets.UTF_8)
            .hash()
            .toString());
    try {
      sha1.hash();
      fail();
    } catch (IllegalStateException expected) {
    }
  }
  @Test
  public void
      testCreateServiceInstanceBinding_success_saveAndReturnsNewServiceInstanceBindingWithCredentials()
          throws Exception {

    CreateServiceInstanceBindingRequest request =
        getCreateServiceInstanceBindingRequest("serviceId", "bindingId");
    when(instanceBindingService.createServiceInstanceBinding(request))
        .thenReturn(getServiceInstanceBinding("id"));
    ServiceInstanceBinding instance = service.createServiceInstanceBinding(request);

    assertThat(instance.getCredentials().get("junit"), equalTo(CREDENTIALS.get("junit")));
    assertThat(
        instance.getCredentials().get(HBaseServiceInstanceBindingService.NAMESPACE),
        equalTo(Hashing.sha1().hashString("serviceId").toString()));
  }
Ejemplo n.º 14
0
 @Test
 public void testImplicitDepsAreAddedCorrectly() throws NoSuchBuildTargetException {
   Description<GenruleDescription.Arg> genruleDescription = new GenruleDescription();
   Map<String, Object> instance =
       ImmutableMap.<String, Object>of(
           "srcs", ImmutableList.of(":baz", "//biz:baz"),
           "out", "AndroidManifest.xml",
           "cmd", "$(exe //bin:executable) $(location :arg)");
   ProjectFilesystem projectFilesystem = new AllExistingProjectFilesystem();
   BuildRuleFactoryParams params =
       new BuildRuleFactoryParams(projectFilesystem, BuildTargetFactory.newInstance("//foo:bar"));
   ConstructorArgMarshaller marshaller =
       new ConstructorArgMarshaller(
           new DefaultTypeCoercerFactory(ObjectMappers.newDefaultInstance()));
   ImmutableSet.Builder<BuildTarget> declaredDeps = ImmutableSet.builder();
   ImmutableSet.Builder<VisibilityPattern> visibilityPatterns = ImmutableSet.builder();
   GenruleDescription.Arg constructorArg = genruleDescription.createUnpopulatedConstructorArg();
   try {
     marshaller.populate(
         createCellRoots(projectFilesystem),
         projectFilesystem,
         params,
         constructorArg,
         declaredDeps,
         visibilityPatterns,
         instance);
   } catch (ConstructorArgMarshalException e) {
     fail("Expected constructorArg to be correctly populated.");
   }
   TargetNode<GenruleDescription.Arg> targetNode =
       new TargetNodeFactory(new DefaultTypeCoercerFactory(ObjectMappers.newDefaultInstance()))
           .create(
               Hashing.sha1().hashString(params.target.getFullyQualifiedName(), UTF_8),
               genruleDescription,
               constructorArg,
               params,
               declaredDeps.build(),
               visibilityPatterns.build(),
               createCellRoots(projectFilesystem));
   assertEquals(
       "SourcePaths and targets from cmd string should be extracted as extra deps.",
       ImmutableSet.of("//foo:baz", "//biz:baz", "//bin:executable", "//foo:arg"),
       FluentIterable.from(targetNode.getExtraDeps())
           .transform(Functions.toStringFunction())
           .toSet());
 }
Ejemplo n.º 15
0
  private String etag(MarkdownFile srcmd, @Nullable MarkdownFile navmd) {
    byte[] b = new byte[Constants.OBJECT_ID_LENGTH];
    Hasher h = Hashing.sha1().newHasher();
    h.putInt(ETAG_GEN);

    renderer.getTemplateHash(SOY_FILE).writeBytesTo(b, 0, b.length);
    h.putBytes(b);

    if (navmd != null) {
      navmd.id.copyRawTo(b, 0);
      h.putBytes(b);
    }

    srcmd.id.copyRawTo(b, 0);
    h.putBytes(b);
    return h.hash().toString();
  }
Ejemplo n.º 16
0
  protected ChangeInserter newChange(
      TestRepository<Repo> repo,
      @Nullable RevCommit commit,
      @Nullable String key,
      @Nullable Integer owner,
      @Nullable String branch)
      throws Exception {
    if (commit == null) {
      commit = repo.parseBody(repo.commit().message("message").create());
    }
    Account.Id ownerId = owner != null ? new Account.Id(owner) : userId;
    branch = MoreObjects.firstNonNull(branch, "refs/heads/master");
    if (!branch.startsWith("refs/heads/")) {
      branch = "refs/heads/" + branch;
    }
    Project.NameKey project =
        new Project.NameKey(repo.getRepository().getDescription().getRepositoryName());

    Change.Id id = new Change.Id(db.nextChangeId());
    if (key == null) {
      key =
          "I"
              + Hashing.sha1()
                  .newHasher()
                  .putInt(id.get())
                  .putString(project.get(), UTF_8)
                  .putString(commit.name(), UTF_8)
                  .putInt(ownerId.get())
                  .putString(branch, UTF_8)
                  .hash()
                  .toString();
    }

    Change change =
        new Change(
            new Change.Key(key),
            id,
            ownerId,
            new Branch.NameKey(project, branch),
            TimeUtil.nowTs());
    IdentifiedUser user = userFactory.create(Providers.of(db), ownerId);
    return changeFactory.create(projectControlFactory.controlFor(project, user), change, commit);
  }
Ejemplo n.º 17
0
 private static TargetNode<?> createTargetNode(
     BuildTarget buildTarget, ImmutableSet<Path> inputs) {
   Description<FakeDescription.FakeArg> description = new FakeDescription();
   FakeDescription.FakeArg arg = description.createUnpopulatedConstructorArg();
   arg.inputs = inputs;
   BuildRuleFactoryParams params =
       NonCheckingBuildRuleFactoryParams.createNonCheckingBuildRuleFactoryParams(buildTarget);
   try {
     return new TargetNode<>(
         Hashing.sha1().hashString(params.target.getFullyQualifiedName(), UTF_8),
         description,
         arg,
         new DefaultTypeCoercerFactory(),
         params,
         ImmutableSet.<BuildTarget>of(),
         ImmutableSet.<BuildTargetPattern>of(),
         createCellRoots(params.getProjectFilesystem()));
   } catch (NoSuchBuildTargetException | TargetNode.InvalidSourcePathInputException e) {
     throw new RuntimeException(e);
   }
 }
Ejemplo n.º 18
0
 private Builder setVal(@Nullable File file) {
   if (file != null) {
     // Compute a separate SHA-1 for the file contents and feed that into messageDigest rather
     // than the file contents, in order to avoid the overhead of escaping SEPARATOR in the file
     // content.
     try {
       byte[] fileBytes = Files.toByteArray(file);
       HashCode fileSha1 = Hashing.sha1().hashBytes(fileBytes);
       if (logElms != null) {
         logElms.add(
             String.format("file(path=\"%s\", sha1=%s):", file.getPath(), fileSha1.toString()));
       }
       feed(fileSha1.asBytes());
     } catch (IOException e) {
       // The file is nonexistent/unreadable; generate a RuleKey that prevents accidental
       // caching.
       if (logElms != null) {
         logElms.add(String.format("file(path=\"%s\", sha1=random):", file.getPath()));
       }
       nonIdempotent();
     }
   }
   return separate();
 }
/**
 * Creates a bill of materials for all installed artifacts.
 *
 * <p>This in the standard format for the <tt>sha1sum</tt> command including meta information:
 *
 * <pre>
 * # company:company-parent-pom:1.0-SNAPSHOT user=mirko
 * 2dcb20b977ff170dd802c30b804229264c97ebf6  company-parent-pom-1.0-SNAPSHOT.pom
 * # company:child1:1.0-SNAPSHOT user=mirko
 * ed5b932c3157b347d0f7a4ec773ae5d5890c1ada  child1-1.0-SNAPSHOT-sources.jar
 * 8294565e2a5d99b548b111fe6262719331436143  child1-1.0-SNAPSHOT.jar
 * 082fa2206c4a00e3f428e9100199a0337ad42fdb  child1-1.0-SNAPSHOT.pom
 * # company:child2:1.0-SNAPSHOT user=mirko
 * 05d419cf53e175c6e84ddc1cf2fccdc9dd109c6b  child2-1.0-SNAPSHOT-sources.jar
 * df633b963220ba124ffa80eb6ceab676934bb387  child2-1.0-SNAPSHOT.jar
 * 5661e9270a02c5359be47615bb6ed9911105d878  child2-1.0-SNAPSHOT.pom
 * </pre>
 *
 * @author Mirko Friedenhagen <*****@*****.**>
 */
@Mojo(name = "create", aggregator = false, defaultPhase = LifecyclePhase.INSTALL)
public class CreateBillOfMaterialsMojo extends AbstractBillOfMaterialsMojo {

  /** Logger. */
  private static final Logger LOG = LoggerFactory.getLogger(CreateBillOfMaterialsMojo.class);

  /** SHA1 hash function. */
  private final HashFunction sha1 = Hashing.sha1();

  /** Function to calculate the hash of a file. */
  private final Function<File, String> toBomStringFunction;

  /** Function to get the file from the artifact. */
  private final Function<Artifact, File> toFileFunction;

  /** Default constructor for maven. */
  CreateBillOfMaterialsMojo() {
    super();
    toFileFunction = new ToFileFunction();
    toBomStringFunction = new ToBomStringFunction(sha1);
  }

  /**
   * Just for tests.
   *
   * @param billOfMaterialsPath path to bom.
   * @param project current project
   */
  CreateBillOfMaterialsMojo(File billOfMaterialsPath, MavenProject project) {
    super(billOfMaterialsPath, project);
    toFileFunction = new ToFileFunction();
    toBomStringFunction = new ToBomStringFunction(sha1);
  }

  @Override
  public void execute() throws MojoExecutionException, MojoFailureException {
    StaticLoggerBinder.getSingleton().setMavenLog(this.getLog());
    try {
      final List<Artifact> artifacts = getListOfArtifacts();
      LOG.debug("artifacts={}", artifacts);
      final ArrayList<File> files =
          new ArrayList<File>(Collections2.transform(artifacts, toFileFunction));
      final ArrayList<String> hashBaseNames =
          new ArrayList<String>(Collections2.transform(files, toBomStringFunction));
      addHashEntryForPom(hashBaseNames);
      writeResults(hashBaseNames);
    } catch (IOException ex) {
      throw new MojoExecutionException(ex.toString(), ex);
    }
  }

  /**
   * Creates a list of all artifacts for the build.
   *
   * @return a list of all artifacts for the build including the attached ones.
   */
  List<Artifact> getListOfArtifacts() {
    final MavenProject project = getProject();
    final List<Artifact> artifacts = new ArrayList<Artifact>(project.getAttachedArtifacts());
    final String packaging = project.getPackaging();
    // POMs return null as their artifact, which will crash the transformation lateron.
    if (!"pom".equals(packaging)) {
      artifacts.add(project.getArtifact());
    }
    return artifacts;
  }

  /**
   * Adds the hash entry for the POM.
   *
   * @param hashBaseNames to add the entry to.
   * @throws IOException when the POM could not be read.
   */
  void addHashEntryForPom(final List<String> hashBaseNames) throws IOException {
    final MavenProject project = getProject();
    // Files.copy(project.getFile(), new File(getTargetDirectory(), "pom.xml"));
    final HashCode sha1OfPom = Files.hash(project.getFile(), sha1);
    final String pomLine =
        String.format(
            Locale.ENGLISH,
            "%s  %s-%s.pom",
            sha1OfPom,
            project.getArtifactId(),
            project.getVersion());
    hashBaseNames.add(pomLine);
  }

  /**
   * Writes the resulting hash file to {@link CreateBillOfMaterialsMojo#billOfMaterialsPath}.
   *
   * @param hashBaseNames to write
   * @throws IOException when the parent directory could not be created or something went wrong
   *     while writing the result.
   */
  void writeResults(final List<String> hashBaseNames) throws IOException {
    final String hashBaseNamesAsString = Joiner.on("\n").join(hashBaseNames) + "\n";
    final String userName = System.getProperty("user.name");
    write(projectCommentToString(userName));
    write(hashBaseNamesAsString);
  }

  /**
   * Writes content to the bomFile creating intermediate directories.
   *
   * @param content to write
   * @throws IOException when the target directory could not be created or the content could not be
   *     written.
   */
  void write(final String content) throws IOException {
    final File bomFile = calculateBillOfMaterialsFile();
    final File parentDirectory = bomFile.getParentFile();
    if (!createParentDirectory(parentDirectory)) {
      throw new IOException("Could not create parent directory for " + bomFile);
    }
    Files.append(content, bomFile, Charsets.UTF_8);
  }

  /**
   * Returns a string representation for the comment.
   *
   * @param userName current user
   * @return string representation for the comment.
   */
  String projectCommentToString(final String userName) {
    final MavenProject project = getProject();
    return String.format(
        Locale.ENGLISH,
        "# %s:%s:%s user=%s\n",
        project.getGroupId(),
        project.getArtifactId(),
        project.getVersion(),
        userName);
  }

  /**
   * Creates directory for storage.
   *
   * @param parentDirectory
   * @return true when parentDirectory could not be created.
   */
  boolean createParentDirectory(final File parentDirectory) {
    return parentDirectory.exists() || parentDirectory.mkdirs();
  }
}
Ejemplo n.º 20
0
 private byte[] hashExtId(EventExtId extId) {
   HashCode hashCode = Hashing.sha1().hashString(extId.getExtId(), Charsets.US_ASCII);
   return hashCode.asBytes();
 }
  @SuppressWarnings({"rawtypes", "unchecked"})
  private TargetNode<?> createTargetNode(
      BuckEventBus eventBus,
      Cell cell,
      Path buildFile,
      BuildTarget target,
      Map<String, Object> rawNode,
      TargetNodeListener nodeListener) {
    BuildRuleType buildRuleType = parseBuildRuleTypeFromRawRule(cell, rawNode);

    // Because of the way that the parser works, we know this can never return null.
    Description<?> description = cell.getDescription(buildRuleType);

    if (target.isFlavored()) {
      if (description instanceof Flavored) {
        if (!((Flavored) description).hasFlavors(ImmutableSet.copyOf(target.getFlavors()))) {
          throw new HumanReadableException(
              "Unrecognized flavor in target %s while parsing %s%s.",
              target,
              UnflavoredBuildTarget.BUILD_TARGET_PREFIX,
              MorePaths.pathWithUnixSeparators(
                  target.getBasePath().resolve(cell.getBuildFileName())));
        }
      } else {
        LOG.warn(
            "Target %s (type %s) must implement the Flavored interface "
                + "before we can check if it supports flavors: %s",
            target.getUnflavoredBuildTarget(), buildRuleType, target.getFlavors());
        throw new HumanReadableException(
            "Target %s (type %s) does not currently support flavors (tried %s)",
            target.getUnflavoredBuildTarget(), buildRuleType, target.getFlavors());
      }
    }

    Cell targetCell = cell.getCell(target);
    BuildRuleFactoryParams factoryParams =
        new BuildRuleFactoryParams(
            targetCell.getFilesystem(),
            target.withoutCell(),
            new FilesystemBackedBuildFileTree(cell.getFilesystem(), cell.getBuildFileName()),
            targetCell.isEnforcingBuckPackageBoundaries());
    Object constructorArg = description.createUnpopulatedConstructorArg();
    try {
      ImmutableSet.Builder<BuildTarget> declaredDeps = ImmutableSet.builder();
      ImmutableSet.Builder<BuildTargetPattern> visibilityPatterns = ImmutableSet.builder();
      try (SimplePerfEvent.Scope scope =
          SimplePerfEvent.scope(
              eventBus, PerfEventId.of("MarshalledConstructorArg"), "target", target)) {
        marshaller.populate(
            targetCell.getCellRoots(),
            targetCell.getFilesystem(),
            factoryParams,
            constructorArg,
            declaredDeps,
            visibilityPatterns,
            rawNode);
      }
      try (SimplePerfEvent.Scope scope =
          SimplePerfEvent.scope(eventBus, PerfEventId.of("CreatedTargetNode"), "target", target)) {
        Hasher hasher = Hashing.sha1().newHasher();
        hasher.putString(BuckVersion.getVersion(), UTF_8);
        JsonObjectHashing.hashJsonObject(hasher, rawNode);
        synchronized (this) {
          targetsCornucopia.put(target.getUnflavoredBuildTarget(), target);
        }
        TargetNode<?> node =
            new TargetNode(
                hasher.hash(),
                description,
                constructorArg,
                typeCoercerFactory,
                factoryParams,
                declaredDeps.build(),
                visibilityPatterns.build(),
                targetCell.getCellRoots());
        nodeListener.onCreate(buildFile, node);
        return node;
      }
    } catch (NoSuchBuildTargetException | TargetNode.InvalidSourcePathInputException e) {
      throw new HumanReadableException(e);
    } catch (ConstructorArgMarshalException e) {
      throw new HumanReadableException("%s: %s", target, e.getMessage());
    } catch (IOException e) {
      throw new HumanReadableException(e.getMessage(), e);
    }
  }
/**
 * Tests for the MessageDigestHashFunction.
 *
 * @author Kurt Alfred Kluever
 */
public class MessageDigestHashFunctionTest extends TestCase {
  private static final ImmutableSet<String> INPUTS = ImmutableSet.of("", "Z", "foobar");

  // From "How Provider Implementations Are Requested and Supplied" from
  // http://docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html
  //  - Some providers may choose to also include alias names.
  //  - For example, the "SHA-1" algorithm might be referred to as "SHA1".
  //  - The algorithm name is not case-sensitive.
  private static final ImmutableMap<String, HashFunction> ALGORITHMS =
      new ImmutableMap.Builder<String, HashFunction>()
          .put("MD5", Hashing.md5())
          .put("SHA", Hashing.sha1()) // Not the official name, but still works
          .put("SHA1", Hashing.sha1()) // Not the official name, but still works
          .put("sHa-1", Hashing.sha1()) // Not the official name, but still works
          .put("SHA-1", Hashing.sha1())
          .put("SHA-256", Hashing.sha256())
          .put("SHA-512", Hashing.sha512())
          .build();

  public void testHashing() {
    for (String stringToTest : INPUTS) {
      for (String algorithmToTest : ALGORITHMS.keySet()) {
        assertMessageDigestHashing(HashTestUtils.ascii(stringToTest), algorithmToTest);
      }
    }
  }

  public void testPutAfterHash() {
    Hasher sha1 = Hashing.sha1().newHasher();

    assertEquals(
        "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12",
        sha1.putString("The quick brown fox jumps over the lazy dog", Charsets.UTF_8)
            .hash()
            .toString());
    try {
      sha1.putInt(42);
      fail();
    } catch (IllegalStateException expected) {
    }
  }

  public void testHashTwice() {
    Hasher sha1 = Hashing.sha1().newHasher();

    assertEquals(
        "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12",
        sha1.putString("The quick brown fox jumps over the lazy dog", Charsets.UTF_8)
            .hash()
            .toString());
    try {
      sha1.hash();
      fail();
    } catch (IllegalStateException expected) {
    }
  }

  public void testToString() {
    assertEquals("Hashing.md5()", Hashing.md5().toString());
    assertEquals("Hashing.sha1()", Hashing.sha1().toString());
    assertEquals("Hashing.sha256()", Hashing.sha256().toString());
    assertEquals("Hashing.sha512()", Hashing.sha512().toString());
  }

  private static void assertMessageDigestHashing(byte[] input, String algorithmName) {
    try {
      MessageDigest digest = MessageDigest.getInstance(algorithmName);
      assertEquals(
          HashCode.fromBytes(digest.digest(input)), ALGORITHMS.get(algorithmName).hashBytes(input));
      for (int bytes = 4; bytes <= digest.getDigestLength(); bytes++) {
        assertEquals(
            HashCode.fromBytes(Arrays.copyOf(digest.digest(input), bytes)),
            new MessageDigestHashFunction(algorithmName, bytes, algorithmName).hashBytes(input));
      }
      try {
        int maxSize = digest.getDigestLength();
        new MessageDigestHashFunction(algorithmName, maxSize + 1, algorithmName);
        fail();
      } catch (IllegalArgumentException expected) {
      }
    } catch (NoSuchAlgorithmException nsae) {
      throw new AssertionError(nsae);
    }
  }
}
 public void testToString() {
   assertEquals("Hashing.md5()", Hashing.md5().toString());
   assertEquals("Hashing.sha1()", Hashing.sha1().toString());
   assertEquals("Hashing.sha256()", Hashing.sha256().toString());
   assertEquals("Hashing.sha512()", Hashing.sha512().toString());
 }
Ejemplo n.º 24
0
 private void updateSubmissionId(Change change) {
   Hasher h = Hashing.sha1().newHasher();
   h.putLong(Thread.currentThread().getId()).putUnencodedChars(MACHINE_ID);
   staticSubmissionId = h.hash().toString().substring(0, 8);
   submissionId = change.getId().get() + "-" + TimeUtil.nowMs() + "-" + staticSubmissionId;
 }
Ejemplo n.º 25
0
 @Override
 public String toString() {
   return Hashing.sha1().hashBytes(ByteBuffers.toByteArray(getBytes())).toString();
 }
Ejemplo n.º 26
0
 @Override
 public int hashCode() {
   return Hashing.sha1().hashCode();
 }
Ejemplo n.º 27
0
 public String computeSha1(Path pathRelativeToProjectRootOrJustAbsolute) throws IOException {
   Path fileToHash = getPathForRelativePath(pathRelativeToProjectRootOrJustAbsolute);
   return Hashing.sha1().hashBytes(Files.readAllBytes(fileToHash)).toString();
 }
Ejemplo n.º 28
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String loginName = request.getParameter("loginName");
    String loginPassword = request.getParameter("loginPassword");

    boolean valid = validation.Validation.validate(loginName, loginPassword);
    HttpSession session = request.getSession();

    if (valid) {
      session.setAttribute("loginName", loginName);
      request.getSession().setMaxInactiveInterval(600);

      JSONObject json = new JSONObject().put("status", "ok");

      HashFunction hf = Hashing.sha1();
      // unique token !?
      Random rand = new Random();
      int randomNum = (rand.nextInt(9999999 - 1) + 1) + 1;
      HashCode hc = hf.newHasher().putString(loginName, Charsets.UTF_8).putInt(randomNum).hash();
      PlayerRequest.setTokenToPlayer(loginName, hc.toString());

      json.put("token", hc.toString());

      PrintWriter out = response.getWriter();
      out.println(json);
      out.println(
          "<!DOCTYPE html PUBLIC "
              + " // W3C//DTD HTML 4.01"
              + "	// Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\""
              + "<html>"
              + "	<head>"
              + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">"
              + "<title>Transactions</title>"
              + "	</head>"
              + "	<body>"
              + "<form method=\"POST\" action=\"Deposit\">"
              + "	<br>Deposit: <input type=\"text\" name=\"deposit\" />"
              + "<input type=\"hidden\" name=\"token\" value=\""
              + hc.toString()
              + "\"/> "
              + "<input type=\"hidden\" name=\"loginName\" value=\""
              + loginName
              + "\"/> "
              + "<input type=\"submit\" name=\"depositB\" value=\"Deposit\" />"
              + "	</form>"
              + "	<form method=\"POST\" action=\"Withdraw\">"
              + "	<br> Withdraw: <input type=\"text\" name=\"withdraw\" />"
              + "<input type=\"hidden\" name=\"token\" value=\""
              + hc.toString()
              + "\"/>"
              + "<input type=\"hidden\" name=\"loginName\" value=\""
              + loginName
              + "\"/> "
              + " <input type=\"submit\" name=\"withdrawB\" value=\"Withdraw\" />"
              + "</form>"
              + "<form method=\"POST\" action = \"Logout\">"
              + "<br><input type=\"hidden\" name=\"token\" value=\""
              + hc.toString()
              + "\"/>"
              + "<br><input type=\"hidden\" name=\"loginName\" value=\""
              + loginName
              + "\"/>"
              + "<input type=\"submit\" name=\"logout\" value=\"Logout\" />"
              + "</form>"
              + "	</body>"
              + "</html>");

    } else {
      JSONObject json = new JSONObject().put("status", "invalid");

      PrintWriter out = response.getWriter();
      out.println(json);
    }
  }
Ejemplo n.º 29
0
 @NotNull
 public static String getToken(String secretToken, long identity) {
   return Hashing.sha1().hashString(secretToken + identity, Charset.forName("UTF-8")).toString();
 }
Ejemplo n.º 30
0
  public ListenableFuture func_180601_a(String p_180601_1_, String p_180601_2_) {
    String s2;

    if (p_180601_2_.matches("^[a-f0-9]{40}$")) {
      s2 = p_180601_2_;
    } else {
      s2 = p_180601_1_.substring(p_180601_1_.lastIndexOf("/") + 1);

      if (s2.contains("?")) {
        s2 = s2.substring(0, s2.indexOf("?"));
      }

      if (!s2.endsWith(".zip")) {
        return Futures.immediateFailedFuture(
            new IllegalArgumentException("Invalid filename; must end in .zip"));
      }

      s2 = "legacy_" + s2.replaceAll("\\W", "");
    }

    final File file1 = new File(this.dirServerResourcepacks, s2);
    this.field_177321_h.lock();

    try {
      this.func_148529_f();

      if (file1.exists() && p_180601_2_.length() == 40) {
        try {
          String s3 = Hashing.sha1().hashBytes(Files.toByteArray(file1)).toString();

          if (s3.equals(p_180601_2_)) {
            ListenableFuture listenablefuture1 = this.func_177319_a(file1);
            return listenablefuture1;
          }

          logger.warn(
              "File "
                  + file1
                  + " had wrong hash (expected "
                  + p_180601_2_
                  + ", found "
                  + s3
                  + "). Deleting it.");
          FileUtils.deleteQuietly(file1);
        } catch (IOException ioexception) {
          logger.warn("File " + file1 + " couldn\'t be hashed. Deleting it.", ioexception);
          FileUtils.deleteQuietly(file1);
        }
      }

      final GuiScreenWorking guiscreenworking = new GuiScreenWorking();
      Map map = Minecraft.getSessionInfo();
      final Minecraft minecraft = Minecraft.getMinecraft();
      Futures.getUnchecked(
          minecraft.addScheduledTask(
              new Runnable() {
                private static final String __OBFID = "CL_00001089";

                public void run() {
                  minecraft.displayGuiScreen(guiscreenworking);
                }
              }));
      final SettableFuture settablefuture = SettableFuture.create();
      this.field_177322_i =
          HttpUtil.func_180192_a(
              file1, p_180601_1_, map, 52428800, guiscreenworking, minecraft.getProxy());
      Futures.addCallback(
          this.field_177322_i,
          new FutureCallback() {
            private static final String __OBFID = "CL_00002394";

            public void onSuccess(Object p_onSuccess_1_) {
              ResourcePackRepository.this.func_177319_a(file1);
              settablefuture.set((Object) null);
            }

            public void onFailure(Throwable p_onFailure_1_) {
              settablefuture.setException(p_onFailure_1_);
            }
          });
      ListenableFuture listenablefuture = this.field_177322_i;
      return listenablefuture;
    } finally {
      this.field_177321_h.unlock();
    }
  }