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

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

Introduction

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

Prototype

public static MessageDigest getSha256Digest() 

Source Link

Usage

From source file:com.continusec.client.ObjectHash.java

private static final byte[] hashBoolean(boolean b) throws ContinusecException {
    MessageDigest d = DigestUtils.getSha256Digest();
    d.update((byte) 'b');
    if (b) {//from   w ww  .  ja  v a 2  s. c  o  m
        d.update((byte) '1');
    } else {
        d.update((byte) '0');
    }
    return d.digest();
}

From source file:com.continusec.client.ObjectHash.java

private static final byte[] hashString(String s, String r) throws ContinusecException {
    if (r != null && s.startsWith(r)) {
        try {/*from  w  ww . j av a 2  s.c om*/
            return Hex.decodeHex(s.substring(r.length()).toCharArray());
        } catch (DecoderException e) {
            throw new InvalidObjectException(e);
        }
    } else {
        try {
            MessageDigest d = DigestUtils.getSha256Digest();
            d.update((byte) 'u');
            d.update(Normalizer.normalize(s, Normalizer.Form.NFC).getBytes("UTF8"));
            return d.digest();
        } catch (UnsupportedEncodingException e) {
            throw new InvalidObjectException(e);
        }
    }
}

From source file:com.continusec.client.ObjectHash.java

private static final byte[] hashDouble(double f) throws ContinusecException {
    MessageDigest d = DigestUtils.getSha256Digest();
    d.update((byte) 'f');
    if (f == 0.0) { // special case 0
        d.update((byte) '+');
        d.update((byte) '0');
        d.update((byte) ':');
    } else {/*from   w  w w.java  2s . co  m*/
        if (f < 0) {
            d.update((byte) '-');
            f = -f;
        } else {
            d.update((byte) '+');
        }
        int e = 0;
        while (f > 1) {
            f /= 2.0;
            e++;
        }
        while (f < 0.5) {
            f *= 2.0;
            e--;
        }
        d.update(Integer.toString(e).getBytes());
        d.update((byte) ':');
        if ((f > 1) || (f <= 0.5)) {
            throw new InvalidObjectException();
        }
        for (int cnt = 0; (f != 0) && (cnt < 1000); cnt++) {
            if (f >= 1) {
                d.update((byte) '1');
                f -= 1.0;
            } else {
                d.update((byte) '0');
            }
            if (f >= 1) {
                throw new InvalidObjectException();
            }
            f *= 2.0;
        }
        if (f != 0) { // we went too long
            throw new InvalidObjectException();
        }
    }
    return d.digest();
}

From source file:com.lightszentip.module.security.password.PasswordModuleImpl.java

private byte[] hashPwd(String password, AlgorithmType algorithm)
        throws NoSuchAlgorithmException, UnsupportedEncodingException {
    MessageDigest md = null;//from w  w w.  ja  va2  s. c o m
    if (AlgorithmType.MD5.equals(algorithm)) {
        md = DigestUtils.getMd5Digest();
    } else if (AlgorithmType.SHA_512.equals(algorithm)) {
        md = DigestUtils.getSha512Digest();
    } else if (AlgorithmType.SHA_384.equals(algorithm)) {
        md = DigestUtils.getSha384Digest();
    } else if (AlgorithmType.SHA_256.equals(algorithm)) {
        md = DigestUtils.getSha256Digest();
    } else if (AlgorithmType.SHA_1.equals(algorithm)) {
        md = DigestUtils.getSha1Digest();
    }
    md.update(password.getBytes());
    return md.digest();
}

From source file:com.inventage.nexusaptplugin.DebianIndexCreator.java

@Override
public void populateArtifactInfo(ArtifactContext ac) throws IOException {
    if (ac.getArtifact() != null && "deb".equals(ac.getArtifactInfo().packaging)) {
        List<String> control = GetControl.doGet(ac.getArtifact());
        ac.getArtifactInfo().getAttributes().putAll(DebControlParser.parse(control));
        ac.getArtifactInfo().getAttributes().put("Filename", getRelativeFileNameOfArtifact(ac));

        FileInputStream is = null;
        try {//from   w  w  w .  java  2  s  . c o  m
            is = new FileInputStream(ac.getArtifact());
            MessageDigest md5d = DigestUtils.getMd5Digest();
            MessageDigest sha256 = DigestUtils.getSha256Digest();
            MessageDigest sha512 = DigestUtils.getSha512Digest();

            int count;
            byte[] b = new byte[512];
            while ((count = is.read(b)) >= 0) {
                md5d.update(b, 0, count);
                sha256.update(b, 0, count);
                sha512.update(b, 0, count);
            }

            ac.getArtifactInfo().md5 = Hex.encodeHexString(md5d.digest());
            ac.getArtifactInfo().getAttributes().put(DEBIAN.SHA256.getFieldName(),
                    Hex.encodeHexString(sha256.digest()));
            ac.getArtifactInfo().getAttributes().put(DEBIAN.SHA512.getFieldName(),
                    Hex.encodeHexString(sha512.digest()));
        } finally {
            is.close();
        }
    }
}

From source file:net.solarnetwork.node.backup.s3.S3BackupService.java

private Backup performBackupInternal(final Iterable<BackupResource> resources, final Calendar now,
        Map<String, String> props) {
    if (resources == null) {
        return null;
    }/*w w w  .  j a  va2s .c o  m*/
    final Iterator<BackupResource> itr = resources.iterator();
    if (!itr.hasNext()) {
        log.debug("No resources provided, nothing to backup");
        return null;
    }
    S3Client client = this.s3Client;
    if (!status.compareAndSet(BackupStatus.Configured, BackupStatus.RunningBackup)) {
        // try to reset from error
        if (!status.compareAndSet(BackupStatus.Error, BackupStatus.RunningBackup)) {
            return null;
        }
    }
    S3BackupMetadata result = null;
    try {
        final Long nodeId = nodeId(props);
        final String metaName = String.format(META_NAME_FORMAT, now, nodeId);
        final String metaObjectKey = objectKeyForPath(META_OBJECT_KEY_PREFIX + metaName);
        log.info("Starting backup to archive {}", metaObjectKey);

        final Set<S3ObjectReference> allDataObjects = client
                .listObjects(objectKeyForPath(DATA_OBJECT_KEY_PREFIX));

        S3BackupMetadata meta = new S3BackupMetadata();
        meta.setNodeId(nodeId);
        MessageDigest digest = DigestUtils.getSha256Digest();
        byte[] buf = new byte[4096];
        for (BackupResource rsrc : resources) {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            if (rsrc.getModificationDate() > 0) {
                objectMetadata.setLastModified(new Date(rsrc.getModificationDate()));
            }
            String sha = calculateContentDigest(rsrc, digest, buf, objectMetadata);
            String objectKey = objectKeyForPath(DATA_OBJECT_KEY_PREFIX + sha);

            // see if already exists
            if (!allDataObjects.contains(new S3ObjectReference(objectKey))) {
                log.info("Saving resource to S3: {}", rsrc.getBackupPath());
                client.putObject(objectKey, rsrc.getInputStream(), objectMetadata);
            } else {
                log.info("Backup resource already saved to S3: {}", rsrc.getBackupPath());
            }
            meta.addBackupResource(rsrc, objectKey, sha);
        }

        // now save metadata
        meta.setComplete(true);
        meta.setDate(now.getTime());
        meta.setKey(metaName);
        byte[] metaJsonBytes = OBJECT_MAPPER.writeValueAsBytes(meta);
        try (ByteArrayInputStream in = new ByteArrayInputStream(metaJsonBytes)) {
            ObjectMetadata metaObjectMetadata = new ObjectMetadata();
            metaObjectMetadata.setContentType("application/json;charset=UTF-8");
            metaObjectMetadata.setContentLength(metaJsonBytes.length);
            metaObjectMetadata.setLastModified(meta.getDate());
            S3ObjectReference metaRef = client.putObject(metaObjectKey, in, metaObjectMetadata);
            result = new S3BackupMetadata(metaRef);
        }

        if (additionalBackupCount < 1) {
            // add this backup to the cached data
            CachedResult<List<Backup>> cached = cachedBackupList.get();
            if (cached != null) {
                List<Backup> list = cached.getResult();
                List<Backup> newList = new ArrayList<>(list);
                newList.add(0, result);
                updateCachedBackupList(newList);
            }
        } else {
            // clean out older backups
            List<Backup> knownBackups = getAvailableBackupsInternal();
            List<String> backupsForNode = knownBackups.stream().filter(b -> nodeId.equals(b.getNodeId()))
                    .map(b -> b.getKey()).collect(Collectors.toList());
            if (backupsForNode.size() > additionalBackupCount + 1) {
                Set<String> keysToDelete = backupsForNode.stream()
                        .limit(backupsForNode.size() - additionalBackupCount - 1).collect(Collectors.toSet());
                log.info("Deleting {} expired backups for node {}: {}", keysToDelete.size(), nodeId,
                        keysToDelete);
                client.deleteObjects(keysToDelete);

                // update cache
                knownBackups = knownBackups.stream().filter(b -> !keysToDelete.contains(b.getKey()))
                        .collect(Collectors.toList());
                updateCachedBackupList(knownBackups);
            }
        }
    } catch (IOException e) {
        log.error("IO error performing backup", e);
    } finally {
        status.compareAndSet(BackupStatus.RunningBackup, BackupStatus.Configured);
    }
    return result;
}

From source file:de.fosd.jdime.artifact.Artifact.java

/**
 * Returns a hash of the tree rooted in this {@code Artifact}.
 *
 * @return the tree hash//from   w  ww .ja v a  2s .c o  m
 */
public String getTreeHash() {

    if (hashValid) {
        return hash;
    }

    MessageDigest digest = DigestUtils.getSha256Digest();
    DigestUtils.updateDigest(digest, hashId());

    if (hasChildren()) {
        children.forEach(c -> DigestUtils.updateDigest(digest, c.getTreeHash()));
        hash = "1" + Hex.encodeHexString(digest.digest());
    } else {
        hash = "0" + Hex.encodeHexString(digest.digest());
    }

    hashValid = true;
    return hash;
}

From source file:org.apache.nifi.registry.service.extension.StandardExtensionService.java

@Override
public ExtensionBundleVersion createExtensionBundleVersion(final String bucketIdentifier,
        final ExtensionBundleType bundleType, final InputStream inputStream, final String clientSha256)
        throws IOException {
    if (StringUtils.isBlank(bucketIdentifier)) {
        throw new IllegalArgumentException("Bucket identifier cannot be null or blank");
    }/*from w ww  .ja  va 2s .c o m*/

    if (bundleType == null) {
        throw new IllegalArgumentException("Bundle type cannot be null");
    }

    if (inputStream == null) {
        throw new IllegalArgumentException("Extension bundle input stream cannot be null");
    }

    if (!extractors.containsKey(bundleType)) {
        throw new IllegalArgumentException(
                "No metadata extractor is registered for bundle-type: " + bundleType);
    }

    // ensure the bucket exists
    final BucketEntity existingBucket = metadataService.getBucketById(bucketIdentifier);
    if (existingBucket == null) {
        LOGGER.warn("The specified bucket id [{}] does not exist.", bucketIdentifier);
        throw new ResourceNotFoundException("The specified bucket ID does not exist in this registry.");
    }

    // ensure the extensions directory exists and we can read and write to it
    FileUtils.ensureDirectoryExistAndCanReadAndWrite(extensionsWorkingDir);

    final String extensionWorkingFilename = UUID.randomUUID().toString();
    final File extensionWorkingFile = new File(extensionsWorkingDir, extensionWorkingFilename);
    LOGGER.debug("Writing bundle contents to working directory at {}",
            new Object[] { extensionWorkingFile.getAbsolutePath() });

    try {
        // write the contents of the input stream to a temporary file in the extensions working directory
        final MessageDigest sha256Digest = DigestUtils.getSha256Digest();
        try (final DigestInputStream digestInputStream = new DigestInputStream(inputStream, sha256Digest);
                final OutputStream out = new FileOutputStream(extensionWorkingFile)) {
            IOUtils.copy(digestInputStream, out);
        }

        // get the hex of the SHA-256 computed by the server and compare to the client provided SHA-256, if one was provided
        final String sha256Hex = Hex.encodeHexString(sha256Digest.digest());
        final boolean sha256Supplied = !StringUtils.isBlank(clientSha256);
        if (sha256Supplied && !sha256Hex.equalsIgnoreCase(clientSha256)) {
            LOGGER.error("Client provided SHA-256 of '{}', but server calculated '{}'",
                    new Object[] { clientSha256, sha256Hex });
            throw new IllegalStateException(
                    "The SHA-256 of the received extension bundle does not match the SHA-256 provided by the client");
        }

        // extract the details of the bundle from the temp file in the working directory
        final BundleDetails bundleDetails;
        try (final InputStream in = new FileInputStream(extensionWorkingFile)) {
            final BundleExtractor extractor = extractors.get(bundleType);
            bundleDetails = extractor.extract(in);
        }

        final BundleCoordinate bundleCoordinate = bundleDetails.getBundleCoordinate();
        final Set<BundleCoordinate> dependencyCoordinates = bundleDetails.getDependencyBundleCoordinates();

        final String groupId = bundleCoordinate.getGroupId();
        final String artifactId = bundleCoordinate.getArtifactId();
        final String version = bundleCoordinate.getVersion();

        final boolean isSnapshotVersion = version.endsWith(SNAPSHOT_VERSION_SUFFIX);
        final boolean overwriteBundleVersion = isSnapshotVersion
                || existingBucket.isAllowExtensionBundleRedeploy();

        LOGGER.debug("Extracted bundle details - '{}' - '{}' - '{}'",
                new Object[] { groupId, artifactId, version });

        // a bundle with the same group, artifact, and version can exist in multiple buckets, but only if it contains the same binary content, or if its a snapshot version
        // we can determine that by comparing the SHA-256 digest of the incoming bundle against existing bundles with the same group, artifact, version
        final List<ExtensionBundleVersionEntity> allExistingVersions = metadataService
                .getExtensionBundleVersionsGlobal(groupId, artifactId, version);
        for (final ExtensionBundleVersionEntity existingVersionEntity : allExistingVersions) {
            if (!existingVersionEntity.getSha256Hex().equals(sha256Hex) && !isSnapshotVersion) {
                throw new IllegalStateException(
                        "Found existing extension bundle with same group, artifact, and version, but different SHA-256 checksums");
            }
        }

        // get the existing extension bundle entity, or create a new one if one does not exist in the bucket with the group + artifact
        final long currentTime = System.currentTimeMillis();
        final ExtensionBundleEntity extensionBundle = getOrCreateExtensionBundle(bucketIdentifier, groupId,
                artifactId, bundleType, currentTime);

        // check if the version of incoming bundle already exists in the bucket
        // if it exists and it is a snapshot version or the bucket allows redeploying, then first delete the row in the extension_bundle_version table so we can create a new one
        // otherwise we throw an exception because we don't allow the same version in the same bucket
        final ExtensionBundleVersionEntity existingVersion = metadataService
                .getExtensionBundleVersion(bucketIdentifier, groupId, artifactId, version);
        if (existingVersion != null) {
            if (overwriteBundleVersion) {
                metadataService.deleteExtensionBundleVersion(existingVersion);
            } else {
                LOGGER.warn("The specified version [{}] already exists for extension bundle [{}].",
                        new Object[] { version, extensionBundle.getId() });
                throw new IllegalStateException(
                        "The specified version already exists for the given extension bundle");
            }
        }

        // create the version metadata instance and validate it has all the required fields
        final String userIdentity = NiFiUserUtils.getNiFiUserIdentity();
        final ExtensionBundleVersionMetadata versionMetadata = new ExtensionBundleVersionMetadata();
        versionMetadata.setId(UUID.randomUUID().toString());
        versionMetadata.setExtensionBundleId(extensionBundle.getId());
        versionMetadata.setBucketId(bucketIdentifier);
        versionMetadata.setVersion(version);
        versionMetadata.setTimestamp(currentTime);
        versionMetadata.setAuthor(userIdentity);
        versionMetadata.setSha256(sha256Hex);
        versionMetadata.setSha256Supplied(sha256Supplied);
        versionMetadata.setContentSize(extensionWorkingFile.length());

        validate(versionMetadata, "Cannot create extension bundle version");

        // create the version dependency instances and validate they have the required fields
        final Set<ExtensionBundleVersionDependency> versionDependencies = new HashSet<>();
        for (final BundleCoordinate dependencyCoordinate : dependencyCoordinates) {
            final ExtensionBundleVersionDependency versionDependency = new ExtensionBundleVersionDependency();
            versionDependency.setGroupId(dependencyCoordinate.getGroupId());
            versionDependency.setArtifactId(dependencyCoordinate.getArtifactId());
            versionDependency.setVersion(dependencyCoordinate.getVersion());

            validate(versionDependency, "Cannot create extension bundle version dependency");
            versionDependencies.add(versionDependency);
        }

        // create the bundle version in the metadata db
        final ExtensionBundleVersionEntity versionEntity = DataModelMapper.map(versionMetadata);
        metadataService.createExtensionBundleVersion(versionEntity);

        // create the bundle version dependencies in the metadata db
        for (final ExtensionBundleVersionDependency versionDependency : versionDependencies) {
            final ExtensionBundleVersionDependencyEntity versionDependencyEntity = DataModelMapper
                    .map(versionDependency);
            versionDependencyEntity.setId(UUID.randomUUID().toString());
            versionDependencyEntity.setExtensionBundleVersionId(versionEntity.getId());
            metadataService.createDependency(versionDependencyEntity);
        }

        // persist the content of the bundle to the persistence provider
        final ExtensionBundleContext context = new StandardExtensionBundleContext.Builder()
                .bundleType(getProviderBundleType(bundleType)).bucketId(existingBucket.getId())
                .bucketName(existingBucket.getName()).bundleId(extensionBundle.getId())
                .bundleGroupId(extensionBundle.getGroupId()).bundleArtifactId(extensionBundle.getArtifactId())
                .bundleVersion(versionMetadata.getVersion()).author(versionMetadata.getAuthor())
                .timestamp(versionMetadata.getTimestamp()).build();

        try (final InputStream in = new FileInputStream(extensionWorkingFile);
                final InputStream bufIn = new BufferedInputStream(in)) {
            bundlePersistenceProvider.saveBundleVersion(context, bufIn, overwriteBundleVersion);
            LOGGER.debug("Bundle saved to persistence provider - '{}' - '{}' - '{}'",
                    new Object[] { groupId, artifactId, version });
        }

        // get the updated extension bundle so it contains the correct version count
        final ExtensionBundleEntity updatedBundle = metadataService.getExtensionBundle(bucketIdentifier,
                groupId, artifactId);

        // create the full ExtensionBundleVersion instance to return
        final ExtensionBundleVersion extensionBundleVersion = new ExtensionBundleVersion();
        extensionBundleVersion.setVersionMetadata(versionMetadata);
        extensionBundleVersion.setExtensionBundle(DataModelMapper.map(existingBucket, updatedBundle));
        extensionBundleVersion.setBucket(DataModelMapper.map(existingBucket));
        extensionBundleVersion.setDependencies(versionDependencies);
        return extensionBundleVersion;

    } finally {
        if (extensionWorkingFile.exists()) {
            try {
                extensionWorkingFile.delete();
            } catch (Exception e) {
                LOGGER.warn("Error removing temporary extension bundle file at {}",
                        new Object[] { extensionWorkingFile.getAbsolutePath() });
            }
        }
    }
}

From source file:org.ligoj.app.plugin.prov.aws.auth.AWS4SignerBase.java

/**
 * Hashes the string contents (assumed to be UTF-8) using the SHA-256 algorithm.
 * //from   w  ww. j av a2 s . com
 * @param text
 *            Text to hash.
 * @return Hashed text.
 */
public String hash(final String text) {
    return Hex.encodeHexString(DigestUtils.getSha256Digest()
            .digest(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(text)));
}

From source file:yoyo.framework.standard.shared.commons.codec.DigestUtilsTest.java

@Test
public void test() {
    assertThat(DigestUtils.getMd2Digest(), is(not(nullValue())));
    assertThat(DigestUtils.getMd5Digest(), is(not(nullValue())));
    assertThat(DigestUtils.getSha1Digest(), is(not(nullValue())));
    assertThat(DigestUtils.getSha256Digest(), is(not(nullValue())));
    assertThat(DigestUtils.getSha384Digest(), is(not(nullValue())));
    assertThat(DigestUtils.getSha512Digest(), is(not(nullValue())));
    assertThat(DigestUtils.md2Hex(new byte[] {}), is(not(nullValue())));
}