Example usage for com.google.common.hash Hashing sha256

List of usage examples for com.google.common.hash Hashing sha256

Introduction

In this page you can find the example usage for com.google.common.hash Hashing sha256.

Prototype

public static HashFunction sha256() 

Source Link

Document

Returns a hash function implementing the SHA-256 algorithm (256 hash bits) by delegating to the SHA-256 MessageDigest .

Usage

From source file:org.apache.gobblin.data.management.conversion.hive.avro.AvroSchemaManager.java

/**
 * If url for schema already exists, return the url. If not create a new temporary schema file and return a the url.
 *///from   w w w . j a v  a  2  s  .c o  m
private Path getOrGenerateSchemaFile(Schema schema) throws IOException {

    Preconditions.checkNotNull(schema, "Avro Schema should not be null");

    String hashedSchema = Hashing.sha256().hashString(schema.toString(), StandardCharsets.UTF_8).toString();

    if (!this.schemaPaths.containsKey(hashedSchema)) {

        Path schemaFilePath = new Path(this.schemaDir, String.valueOf(System.currentTimeMillis() + ".avsc"));
        AvroUtils.writeSchemaToFile(schema, schemaFilePath, fs, true);

        this.schemaPaths.put(hashedSchema, schemaFilePath);
    }

    return this.schemaPaths.get(hashedSchema);
}

From source file:io.prestosql.operator.scalar.VarbinaryFunctions.java

@Description("compute sha256 hash")
@ScalarFunction/*from  w w  w.  j ava 2 s. com*/
@SqlType(StandardTypes.VARBINARY)
public static Slice sha256(@SqlType(StandardTypes.VARBINARY) Slice slice) {
    return Slices.wrappedBuffer(Hashing.sha256().hashBytes(slice.getBytes()).asBytes());
}

From source file:org.sonatype.nexus.yum.internal.MetadataProcessor.java

/**
 * Read and process all location entries using provided processor. If there are changes to locations will save the
 * new primary.xml./*from w w  w . ja va 2  s.co  m*/
 *
 * @param repository repository containing primary.xml
 * @param processor  location processor
 * @param repoMDDoc  parsed repomx.xml
 * @return path of primary.xml
 */
private static String processPrimary(final Repository repository, final Processor processor,
        final Document repoMDDoc) throws Exception {
    XPath xPath = XPathFactory.newInstance().newXPath();
    String primaryHref = xPath.compile("/repomd/data[@type='primary']/location/@href").evaluate(repoMDDoc);
    String primaryChecksum = xPath.compile("/repomd/data[@type='primary']/checksum").evaluate(repoMDDoc);

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

    StorageFileItem primaryItem = (StorageFileItem) repository.retrieveItem(false,
            new ResourceStoreRequest("/" + primaryHref));
    Document doc;
    boolean changed = false;
    try (InputStream primaryIn = new GZIPInputStream(new BufferedInputStream(primaryItem.getInputStream()))) {
        doc = documentBuilder.parse(primaryIn);
        NodeList locations = doc.getElementsByTagName("location");
        if (locations != null) {
            for (int i = 0; i < locations.getLength(); i++) {
                Element location = (Element) locations.item(i);
                if (processor.process(location)) {
                    changed = true;
                }
            }
        }
    }
    if (changed) {
        log.debug("Rewriting locations in {}:primary.xml", repository.getId());
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        transformer.transform(new DOMSource(doc), new StreamResult(out));
        byte[] primaryContent = compress(out.toByteArray());
        if (primaryHref.contains(primaryChecksum)) {
            repository.deleteItem(false, new ResourceStoreRequest("/" + primaryHref));
            primaryHref = primaryHref.replace(primaryChecksum,
                    Hashing.sha256().hashBytes(primaryContent).toString());
        }
        storeItem(repository, primaryHref, primaryContent, "application/x-gzip");
    }
    return primaryHref;
}

From source file:com.google.cloud.storage.spi.DefaultStorageRpc.java

private static void setEncryptionHeaders(HttpHeaders headers, String headerPrefix, Map<Option, ?> options) {
    String key = CUSTOMER_SUPPLIED_KEY.getString(options);
    if (key != null) {
        BaseEncoding base64 = BaseEncoding.base64();
        HashFunction hashFunction = Hashing.sha256();
        headers.set(headerPrefix + "algorithm", "AES256");
        headers.set(headerPrefix + "key", key);
        headers.set(headerPrefix + "key-sha256",
                base64.encode(hashFunction.hashBytes(base64.decode(key)).asBytes()));
    }/* w w  w . java 2s. com*/
}

From source file:org.apache.james.mailrepository.MailRepositoryContract.java

@Test
default void retrieveBigMailShouldHaveSameHash() throws Exception {
    MailRepository testee = retrieveRepository();
    String bigString = Strings.repeat("my mail is big ?", 1_000_000);
    Mail mail = createMail(MAIL_1, bigString);
    testee.store(mail);/*w w  w .  j a v  a 2s . c o m*/

    Mail actual = testee.retrieve(MAIL_1);

    assertThat(Hashing.sha256().hashString((String) actual.getMessage().getContent(), StandardCharsets.UTF_8))
            .isEqualTo(Hashing.sha256().hashString(bigString, StandardCharsets.UTF_8));
}

From source file:io.dockstore.webservice.resources.UserResource.java

@POST
@Timed/*ww  w . j  ava  2 s . c o m*/
@UnitOfWork
@ApiOperation(value = "Add new user", notes = "Register a new user", response = User.class)
public User registerUser(@QueryParam("username") String username, @QueryParam("is_admin") boolean isAdmin) {
    final Random random = new Random();
    final int bufferLength = 1024;
    final byte[] buffer = new byte[bufferLength];
    random.nextBytes(buffer);
    String randomString = BaseEncoding.base64Url().omitPadding().encode(buffer);
    final String accessToken = Hashing.sha256().hashString(username + randomString, Charsets.UTF_8).toString();

    User user = new User();
    user.setUsername(username);
    user.setIsAdmin(isAdmin);
    long userId = userDAO.create(user);

    Token token = new Token();
    token.setTokenSource(TokenType.DOCKSTORE.toString());
    token.setContent(accessToken);
    token.setUsername(username);
    token.setUserId(userId);
    tokenDAO.create(token);

    return userDAO.findById(userId);
}

From source file:org.apache.james.mailrepository.file.MBoxMailRepository.java

/**
 * Generate a hex representation of a SHA-256 checksum on the email body
 *//*from   w w  w  .  jav  a  2 s. c  o  m*/
private String generateKeyValue(String emailBody) {
    return Hashing.sha256().hashUnencodedChars(emailBody).toString();
}

From source file:inflor.core.fcs.FCSFileReader.java

private HashMap<String, String> readHeader() throws IOException {
    // Delimiter is first UTF-8 character in the text section
    final byte[] delimiterBytes = new byte[1];
    fcsFile.seek(beginText);// w w  w. j av a 2  s.c o  m
    fcsFile.read(delimiterBytes);
    final String delimiter = new String(delimiterBytes);

    // Read the rest of the text bytes, this will contain the keywords
    final int textLength = endText - beginText + 1;
    final byte[] keywordBytes = new byte[textLength];

    fcsFile.read(keywordBytes);
    String rawKeywords = new String(keywordBytes, DEFAULT_ENCODING);
    if (rawKeywords.length() > 0 && rawKeywords.charAt(rawKeywords.length() - 1) == delimiter.charAt(0)) {
        rawKeywords = rawKeywords.substring(0, rawKeywords.length() - 1);
    }
    rawKeywords = scrubKeywords(rawKeywords, delimiter);

    final StringTokenizer s = new StringTokenizer(rawKeywords, delimiter);
    final HashMap<String, String> header = new HashMap<>();
    Boolean ok = true;
    while (s.hasMoreTokens() && ok) {
        final String key = s.nextToken().trim();
        if (key.trim().isEmpty()) {
            ok = false;
        } else {
            try {
                final String value = s.nextToken().trim();
                header.put(unScrubKeywords(key, delimiter), unScrubKeywords(value, delimiter));
            } catch (NoSuchElementException e) {
                String message = "Keyword value for: " + key
                        + " does not exist.  Header appears to be malformed, proceed with some caution.";
                LogFactory.createLogger(this.getClass().getName()).log(Level.FINE, message, e);
            }
        }
    }

    HashFunction md = Hashing.sha256();
    HashCode code = md.hashBytes(keywordBytes);
    header.put("SHA-256", code.toString());
    return header;
}

From source file:academiavisual.FormPrincipal.java

private void jButtonLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLoginActionPerformed
    try {/*from   ww w .  j  a  v a 2 s.  co  m*/
        permissao = new Permissao();
        if (jComboBoxLogin.getSelectedIndex() == 0) {
            EntityManagerFactory emf = Persistence.createEntityManagerFactory("AcademiaVisualPU");
            AlunoJpaController alunoJpaController = new AlunoJpaController(emf);
            Aluno alunoLogin = (Aluno) alunoJpaController.findLogin(jTextFieldLogin.getText());
            if (alunoLogin != null) {
                String senha1 = alunoLogin.getSenha();
                String senha2 = Hashing.sha256().hashString(jPasswordFieldLogin.getText(), Charsets.UTF_8)
                        .toString();
                if (senha1.equals(senha2)) {
                    permissao.setPermissaoUsuario(Permissao.P_ALUNO);
                    ALUNOID = alunoLogin.getId();
                    dispose();
                    JOptionPane.showMessageDialog(null, "Login realizado com sucesso !");
                    new TelaInicial(permissao).setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(null, "Senha incorreta!");
                    jPasswordFieldLogin.setText("");
                    jPasswordFieldLogin.grabFocus();
                    contadorAcessoAluno++;
                    if (contadorAcessoAluno == 3) {
                        JOptionPane.showMessageDialog(null, "Quantidade de tentativas excedidas (3)!");
                        System.exit(0);
                    }
                }
            } else {
                JOptionPane.showMessageDialog(null, "Login incorreto !");
                jTextFieldLogin.setText("");
                jPasswordFieldLogin.setText("");
                jTextFieldLogin.grabFocus();
            }
        } else {
            if (jComboBoxLogin.getSelectedIndex() == 1) {
                EntityManagerFactory emf = Persistence.createEntityManagerFactory("AcademiaVisualPU");
                TreinadorJpaController treinadorJpaController = new TreinadorJpaController(emf);
                Treinador treinadorLogin = (Treinador) treinadorJpaController
                        .findLogin(jTextFieldLogin.getText());
                if (treinadorLogin != null) {
                    String senha1 = treinadorLogin.getSenha();
                    String senha2 = Hashing.sha256().hashString(jPasswordFieldLogin.getText(), Charsets.UTF_8)
                            .toString();
                    if (senha1.equals(senha2)) {
                        if (treinadorLogin.getAdministrador() == 1) {
                            permissao.setPermissaoUsuario(Permissao.P_ADMINISTRADOR);
                        } else {
                            permissao.setPermissaoUsuario(Permissao.P_TREINADOR);
                        }
                        TREINADORID = treinadorLogin.getId();
                        dispose();
                        JOptionPane.showMessageDialog(null, "Login realizado com sucesso !");
                        new TelaInicial(permissao).setVisible(true);
                    } else {
                        JOptionPane.showMessageDialog(null, "Senha incorreta!");
                        jPasswordFieldLogin.setText("");
                        jPasswordFieldLogin.grabFocus();
                        contadorAcessoTreinador++;
                        if (contadorAcessoTreinador == 3) {
                            JOptionPane.showMessageDialog(null, "Quantidade de tentativas excedidas (3)!");
                            System.exit(0);
                        }
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "Login incorreto !");
                    jTextFieldLogin.setText("");
                    jPasswordFieldLogin.setText("");
                    jTextFieldLogin.grabFocus();
                }
            }
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(rootPane, e);
    }
}

From source file:com.hubrick.vertx.s3.signature.AWS4SignatureBuilder.java

private String makeCanonicalRequestContentHash() {
    if (!canonicalHeaders.containsKey("host")) {
        throw new AWS4SignatureException("Headers must include the host header");
    }//from ww w  .j  a  va2  s.c o m

    final String signatureBase = makeCanonicalRequest();

    return Hashing.sha256().hashString(signatureBase, Charsets.UTF_8).toString();
}