Example usage for org.apache.commons.codec.digest DigestUtils sha256Hex

List of usage examples for org.apache.commons.codec.digest DigestUtils sha256Hex

Introduction

In this page you can find the example usage for org.apache.commons.codec.digest DigestUtils sha256Hex.

Prototype

public static String sha256Hex(String data) 

Source Link

Usage

From source file:com.streamsets.lib.security.http.TestDisconnectedSecurityInfo.java

@Test
public void testInfoPopulation() {
    DisconnectedSecurityInfo info = new DisconnectedSecurityInfo();
    info.addEntry("user", "ph", ImmutableList.of("r"), ImmutableList.of("g"));
    String userSha = DigestUtils.sha256Hex("user");
    DisconnectedSecurityInfo.Entry entry = info.getEntry("user");
    Assert.assertEquals(userSha, entry.getUserNameSha());
    Assert.assertEquals("ph", entry.getPasswordHash());
    Assert.assertEquals(ImmutableList.of("r"), entry.getRoles());
}

From source file:com.yevster.spdxtra.TestFileOperations.java

@Test
public void testAddFileToPackage() {
    assertEquals("Newly-created package should have no files", 0, pkg.getFiles().count());
    final String fileName = "./foo/bar/whatevs.txt";
    final String expectedFileUrl = baseUrl + "#SPDXRef-myFile";
    final String mockSha1 = "abc135875aeffffff";
    final String mockMd5 = DigestUtils.md5Hex("My sum");
    final String mockSha256 = DigestUtils.sha256Hex("My sum");
    final String extractedLicense = "This is the extracting license. Once this was in a file. Now it is here.";
    final String copyrightText = "Copyright (C) 2016 Aweomsness Awesome, Inc.";
    final String comment = "No comment. Carry on. Wait, this is a comment. Curses!";
    final String artifactOfHomepage = "http://example.org/epic/fail";
    final String artifactOfName = "Epic Failure 1,9";
    final String licenseName = "El nombre";

    Write.applyUpdatesInOneTransaction(dataset,
            Write.Package.addFile(baseUrl, packageSpdxId, "SPDXRef-myFile", fileName),
            Write.File.fileTypes(expectedFileUrl, FileType.OTHER, FileType.APPLICATION),
            Write.File.concludedLicense(expectedFileUrl, License.NONE),
            Write.File.checksums(expectedFileUrl, mockSha1, Checksum.md5(mockMd5)),
            Write.File.addLicenseInfoInFile(expectedFileUrl,
                    License.extracted(extractedLicense, licenseName, baseUrl, "LicenseRef-el")),
            Write.File.artifactOf(expectedFileUrl, artifactOfName, null));
    reloadPackage();/*from ww  w  .j a va  2  s  . c  om*/
    List<SpdxFile> allFilesInPackage = pkg.getFiles().collect(Collectors.toList());
    assertEquals("Expected to one file in package after adding one file.", 1, allFilesInPackage.size());
    SpdxFile file = allFilesInPackage.get(0);

    assertEquals(expectedFileUrl, file.getUri());
    assertEquals(fileName, file.getFileName());
    assertEquals(Sets.newHashSet(FileType.OTHER, FileType.APPLICATION), file.getFileTypes());
    assertEquals(AbsentValue.NONE.getUri(),
            file.getPropertyAsResource(SpdxProperties.LICENSE_CONCLUDED).get().getURI());
    assertEquals(Sets.newHashSet(Checksum.md5(mockMd5), Checksum.sha1(mockSha1)), file.getChecksums());
    // Test default copyright - NOASSERTION
    assertEquals(SpdxUris.NO_ASSERTION, file.getCopyrightText().getLiteralOrUriValue());
    assertEquals("Empty optional not returned for uninitialized comment", Optional.empty(), file.getComment());
    assertEquals(Optional.empty(), file.getOptionalPropertyAsString(SpdxProperties.LICENSE_COMMENTS));
    assertEquals(Optional.empty(), file.getNoticeText());
    assertEquals(new HashSet<String>(), file.getContributors());

    Resource doapProject = file.rdfResource.getProperty(SpdxProperties.ARTIFACT_OF).getObject().asResource();
    // The spec supports a value of UNKNOWN, but as other tools validate
    // this field as a URL and it is optional
    // SpdXtra should omit it entirely if blank.
    Assert.assertEquals("When DOAP homepage not specified, should omit.", false,
            doapProject.listProperties(SpdxProperties.DOAP_HOMEPAGE).hasNext());
    Assert.assertEquals(artifactOfName, doapProject.getProperty(SpdxProperties.DOAP_NAME).getString());

    // Test overwrites
    Write.applyUpdatesInOneTransaction(dataset,
            Write.File.checksums(file.getUri(), mockSha1, Checksum.sha256(mockSha256)),
            Write.File.copyrightText(expectedFileUrl, NoneNoAssertionOrValue.of(copyrightText)),
            Write.File.comment(file.getUri(), comment),
            Write.File.artifactOf(expectedFileUrl, artifactOfName, artifactOfHomepage),
            Write.File.licenseComments(expectedFileUrl, "Nice file license!"),
            Write.File.noticeText(file.getUri(), "NOTICE THIS!"),
            Write.File.contributors(file.getUri(), "Larry", "Curly", "Moe"));

    // Reload
    Resource fileResource = Read.lookupResourceByUri(dataset, expectedFileUrl).get();
    file = new SpdxFile(fileResource);
    assertEquals(Sets.newHashSet(Checksum.sha256(mockSha256), Checksum.sha1(mockSha1)), file.getChecksums());
    assertEquals(baseUrl + "#LicenseRef-el",
            file.rdfResource.getPropertyResourceValue(SpdxProperties.LICENSE_INFO_IN_FILE).getURI());
    assertEquals(copyrightText, file.getCopyrightText().getValue().get());
    assertEquals(comment, file.getComment().get());
    assertEquals(Optional.of("Nice file license!"),
            file.getOptionalPropertyAsString(SpdxProperties.LICENSE_COMMENTS));
    assertEquals(Optional.of("NOTICE THIS!"), file.getNoticeText());
    assertEquals(Sets.newHashSet("Larry", "Curly", "Moe"), file.getContributors());

    List<Resource> doapProjects = MiscUtils
            .toLinearStream(fileResource.listProperties(SpdxProperties.ARTIFACT_OF)).map(Statement::getObject)
            .map(RDFNode::asResource).collect(Collectors.toList());
    Assert.assertEquals("Applying artifactOf update twice should produce two properties.", 2,
            doapProjects.size());
    Set<String> expectedHomepages = Sets.newHashSet(null, artifactOfHomepage);

    for (Resource dp : doapProjects) {
        Assert.assertNotNull(dp);
        Assert.assertEquals(artifactOfName, dp.getProperty(SpdxProperties.DOAP_NAME).getString());
        // Use a null value to represent the project with no homepage (which
        // in truth just won't have that property).
        String actualHomepage = dp.getProperty(SpdxProperties.DOAP_HOMEPAGE) != null
                ? dp.getProperty(SpdxProperties.DOAP_HOMEPAGE).getString()
                : null;
        Assert.assertTrue("Homepage has an unexpected value: " + actualHomepage,
                expectedHomepages.remove(actualHomepage));
        Assert.assertEquals("Unexpected type for DOAP Project resource", "http://usefulinc.com/ns/doap#Project",
                dp.getProperty(SpdxProperties.RDF_TYPE).getObject().asResource().getURI());
    }

}

From source file:io.apiman.gateway.engine.policies.auth.JDBCIdentityValidator.java

/**
 * @see io.apiman.gateway.engine.policies.auth.IIdentityValidator#validate(java.lang.String, java.lang.String, io.apiman.gateway.engine.beans.ServiceRequest, io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object, io.apiman.gateway.engine.async.IAsyncHandler)
 *//* w  w  w  .jav  a  2 s.c  om*/
@Override
public void validate(String username, String password, ServiceRequest request, IPolicyContext context,
        JDBCIdentitySource config, IAsyncResultHandler<Boolean> handler) {
    DataSource ds = lookupDatasource(config);
    String sqlPwd = password;
    switch (config.getHashAlgorithm()) {
    case MD5:
        sqlPwd = DigestUtils.md5Hex(password);
        break;
    case SHA1:
        sqlPwd = DigestUtils.shaHex(password);
        break;
    case SHA256:
        sqlPwd = DigestUtils.sha256Hex(password);
        break;
    case SHA384:
        sqlPwd = DigestUtils.sha384Hex(password);
        break;
    case SHA512:
        sqlPwd = DigestUtils.sha512Hex(password);
        break;
    case None:
    default:
        break;
    }
    String query = config.getQuery();
    Connection conn = null;
    boolean validated = false;
    try {
        conn = ds.getConnection();
        conn.setReadOnly(true);
        PreparedStatement statement = conn.prepareStatement(query);
        statement.setString(1, username);
        statement.setString(2, sqlPwd);
        ResultSet resultSet = statement.executeQuery();
        if (resultSet.next()) {
            validated = true;
        }
        resultSet.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
    }

    handler.handle(AsyncResultImpl.create(validated));
}

From source file:com.jslsolucoes.tagria.lib.servlet.Tagria.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String uri = request.getRequestURI().replaceAll(";jsessionid=.*", "");
    String etag = DigestUtils.sha256Hex(uri);

    if (uri.endsWith("blank")) {
        response.setStatus(HttpServletResponse.SC_OK);
        return;/*w ww  . j  ava2s .  c o m*/
    }

    if (uri.endsWith("locale")) {
        Config.set(request.getSession(), Config.FMT_LOCALE,
                Locale.forLanguageTag(request.getParameter("locale")));
        response.setStatus(HttpServletResponse.SC_OK);
        return;
    }

    if (request.getHeader("If-None-Match") != null && etag.equals(request.getHeader("If-None-Match"))) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    String charset = "utf-8";
    if (TagUtil.getInitParam(TagriaConfigParameter.ENCODING) != null) {
        charset = TagUtil.getInitParam(TagriaConfigParameter.ENCODING);
    }
    response.setCharacterEncoding(charset);
    try {

        DateTime today = new DateTime();
        DateTime expires = new DateTime().plusDays(CACHE_EXPIRES_DAY);

        if (uri.endsWith(".css")) {
            response.setContentType("text/css");
        } else if (uri.endsWith(".js")) {
            response.setContentType("text/javascript");
        } else if (uri.endsWith(".png")) {
            response.setContentType("image/png");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss 'GMT'", Locale.ENGLISH);

        if (Boolean.valueOf(TagUtil.getInitParam(TagriaConfigParameter.CDN_ENABLED))) {
            response.setHeader(HttpHeaderParameter.ACCESS_CONTROL_ALLOW_ORIGIN.getName(), "*");
        }

        response.setHeader(HttpHeaderParameter.ETAG.getName(), etag);
        response.setHeader(HttpHeaderParameter.EXPIRES.getName(), sdf.format(expires.toDate()));
        response.setHeader(HttpHeaderParameter.CACHE_CONTROL.getName(),
                "public,max-age=" + Seconds.secondsBetween(today, expires).getSeconds());

        String url = "/com/jslsolucoes"
                + uri.replaceFirst(request.getContextPath(), "").replaceAll(";jsessionid=.*", "");
        InputStream in = getClass().getResourceAsStream(url);
        IOUtils.copy(in, response.getOutputStream());
        in.close();

    } catch (Exception exception) {
        logger.error("Could not load resource", exception);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.ibm.stocator.fs.cos.COSLocalDirAllocator.java

public File createTmpFileForWrite(String pathStr, long size, Configuration conf) throws IOException {
    String sha256hex = DigestUtils.sha256Hex(pathStr);
    Path path = getLocalPathForWrite(sha256hex, size, conf, true);
    File tmpDir = new File(path.getParent().toUri().getPath());
    File tmpFile = new File(tmpDir, sha256hex + UUID.randomUUID().toString());
    return tmpFile;
}

From source file:io.springagora.core.domain.Customer.java

@Transactional
public void persist() {
    if (password != null && password.length() <= 20) {
        password = DigestUtils.sha256Hex(password);
    }/*from w w  w  .  jav a  2  s . c  o m*/
    repository.save(this);
}

From source file:com.petalmd.armor.authentication.backend.simple.SettingsBasedAuthenticationBackend.java

@Override
public User authenticate(final com.petalmd.armor.authentication.AuthCredentials authCreds)
        throws AuthException {
    final String user = authCreds.getUsername();
    final String clearTextPassword = authCreds.getPassword() == null ? null
            : new String(authCreds.getPassword());
    authCreds.clear();/*  www.j av a  2s  . c o m*/

    String digest = settings.get(ConfigConstants.ARMOR_AUTHENTICATION_SETTINGSDB_DIGEST, null);
    final String storedPasswordOrDigest = settings
            .get(ConfigConstants.ARMOR_AUTHENTICATION_SETTINGSDB_USER + user, null);

    if (!StringUtils.isEmpty(clearTextPassword) && !StringUtils.isEmpty(storedPasswordOrDigest)) {

        String passwordOrHash = clearTextPassword;

        if (digest != null) {

            digest = digest.toLowerCase();

            switch (digest) {

            case "sha":
            case "sha1":
                passwordOrHash = DigestUtils.sha1Hex(clearTextPassword);
                break;
            case "sha256":
                passwordOrHash = DigestUtils.sha256Hex(clearTextPassword);
                break;
            case "sha384":
                passwordOrHash = DigestUtils.sha384Hex(clearTextPassword);
                break;
            case "sha512":
                passwordOrHash = DigestUtils.sha512Hex(clearTextPassword);
                break;

            default:
                passwordOrHash = DigestUtils.md5Hex(clearTextPassword);
                break;
            }

        }

        if (storedPasswordOrDigest.equals(passwordOrHash)) {
            return new User(user);
        }

    }

    throw new AuthException("No user " + user + " or wrong password (digest: "
            + (digest == null ? "plain/none" : digest) + ")");
}

From source file:com.migo.service.impl.UserServiceImpl.java

@Override
public long login(String mobile, String password) {
    UserEntity user = queryByMobile(mobile);
    Assert.isNull(user, "??");

    //?/*from   w  w w.java  2s.co  m*/
    if (!user.getPassword().equals(DigestUtils.sha256Hex(password))) {
        throw new RRException("??");
    }

    return user.getUserId();
}

From source file:co.com.mobick.operaciones.UsuarioLoginFacade.java

public void actualizarElUsuarioRecuperado(UsuarioLogin us, String pw) {

    try {/*from  ww w .j a  va  2  s.  c  o  m*/
        UsuarioLogin actualizado = new UsuarioLogin();
        actualizado.setUsuarioLogin(us.getUsuarioLogin());
        actualizado.setUsuario(us.getUsuario());
        actualizado.setRolIdrol(us.getRolIdrol());
        actualizado.setContrasena(DigestUtils.sha256Hex(pw));
        actualizado.setEstadoContrasena(false);

        int query = em.createQuery(
                "UPDATE UsuarioLogin u SET u.contrasena=:contrasena, u.estadoContrasena=TRUE WHERE u.usuarioLogin=:id")
                .setParameter("contrasena", actualizado.getContrasena())
                .setParameter("id", actualizado.getUsuarioLogin()).executeUpdate();

    } catch (Exception e) {
        System.out.println("error en actulizar");
        e.printStackTrace();
    }
}

From source file:com.bg.ebank.entity.User.java

public User(String firstName, String lastName, String email, String password) {
    this();//from www.  j a  v  a 2  s.  c  o  m
    this.firstname = firstName;
    this.lastname = lastName;
    this.email = email;
    this.password = DigestUtils.sha256Hex(password);
}