Example usage for java.security MessageDigest reset

List of usage examples for java.security MessageDigest reset

Introduction

In this page you can find the example usage for java.security MessageDigest reset.

Prototype

public void reset() 

Source Link

Document

Resets the digest for further use.

Usage

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

private String calculateContentDigest(BackupResource rsrc, MessageDigest digest, byte[] buf,
        ObjectMetadata objectMetadata) throws IOException {
    // S3 client buffers to RAM unless content length set; so since we have to calculate the 
    // SHA256 digest of the content anyway, also calculate the content length at the same time
    long contentLength = 0;
    digest.reset();
    int len = 0;//w w w . j  a v  a2s.  c o m
    try (InputStream rsrcIn = rsrc.getInputStream()) {
        while ((len = rsrcIn.read(buf)) >= 0) {
            digest.update(buf, 0, len);
            contentLength += len;
        }
    }
    objectMetadata.setContentLength(contentLength);
    return new String(Hex.encodeHex(digest.digest()));
}

From source file:com.moss.simpledeb.core.action.DigestAction.java

@Override
public void run(DebState state) throws Exception {

    final StringBuilder sb = new StringBuilder();
    final MessageDigest digest = java.security.MessageDigest.getInstance("MD5");

    for (ArchivePath path : state.contentPaths) {

        if (path.entry().isDirectory()) {
            continue;
        }//w w  w  .j  a  v a2  s . c  om

        byte[] fileData;
        {
            InputStream in = path.read();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024 * 10]; //10k buffer
            for (int numRead = in.read(buffer); numRead != -1; numRead = in.read(buffer)) {
                out.write(buffer, 0, numRead);
            }
            in.close();
            out.close();
            fileData = out.toByteArray();
        }

        digest.update(fileData);
        byte[] hash = digest.digest();
        digest.reset();

        sb.append(HexUtil.toHex(hash).toLowerCase());
        sb.append("  ");
        sb.append(path.entry().getName());
        sb.append("\n");
    }

    byte[] data = sb.toString().getBytes();

    TarArchiveEntry tarEntry = new TarArchiveEntry("md5sum");
    tarEntry.setGroupId(0);
    tarEntry.setGroupName("root");
    tarEntry.setIds(0, 0);
    tarEntry.setModTime(System.currentTimeMillis());
    tarEntry.setSize(data.length);
    tarEntry.setUserId(0);
    tarEntry.setUserName("root");

    state.addPath(DebComponent.CONTROL, new BytesArchivePath(tarEntry, data));
}

From source file:tectonicus.raw.RawChunk.java

public byte[] calculateHash(MessageDigest hashAlgorithm) {
    hashAlgorithm.reset();

    for (Section s : sections) {
        if (s != null) {
            update(hashAlgorithm, s.blockIds);
            update(hashAlgorithm, s.blockData);
            update(hashAlgorithm, s.skylight);
            update(hashAlgorithm, s.blocklight);
        } else {/*from   w  w  w .  j av  a 2 s. c o m*/
            byte[][][] dummy = new byte[1][1][1];
            update(hashAlgorithm, dummy);
        }
    }

    for (RawSign sign : signs) {
        hashAlgorithm.update(Integer.toString(sign.x).getBytes());
        hashAlgorithm.update(Integer.toString(sign.y).getBytes());
        hashAlgorithm.update(Integer.toString(sign.z).getBytes());
        hashAlgorithm.update(sign.text1.getBytes());
        hashAlgorithm.update(sign.text2.getBytes());
        hashAlgorithm.update(sign.text3.getBytes());
        hashAlgorithm.update(sign.text4.getBytes());
    }

    return hashAlgorithm.digest();
}

From source file:com.abiquo.api.services.UserService.java

private String encrypt(final String toEncrypt) {
    MessageDigest messageDigest = null;
    try {/*  w  w w .  j av a  2  s .c o m*/
        messageDigest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        LOGGER.debug("cannot get the instance of messageDigest", e);
        // revise if the method is called from other method
        addUnexpectedErrors(APIError.STATUS_BAD_REQUEST);
        flushErrors();
    }
    messageDigest.reset();
    messageDigest.update(toEncrypt.getBytes(Charset.forName("UTF8")));
    final byte[] resultByte = messageDigest.digest();
    return new String(Hex.encodeHex(resultByte));
}

From source file:com.daon.identityx.controller.SimpleController.java

/***
 * Hash the password with the salt and for the given number of iterations
 * /*from   w w w .  j av  a  2s.  c  o  m*/
 * @param password
 * @param iterationCount
 * @param salt
 * @return
 */
protected byte[] hash(String password, int iterationCount, byte[] salt) {

    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.reset();
        digest.update(salt);
        byte[] input = digest.digest(password.getBytes("UTF-8"));
        for (int i = 0; i < iterationCount; i++) {
            digest.reset();
            input = digest.digest(input);
        }
        return input;
    } catch (Exception e) {
        logger.error("An exception occurred while attempting to hash the password", e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.ws.security.message.token.SecurityTokenReference.java

/**
 * Sets the KeyIdentifier Element as a Thumbprint.
 * /* w w  w.  ja v  a 2 s.  co  m*/
 * Takes a X509 certificate, computes its thumbprint using SHA-1, converts into base 64 and
 * inserts it into a <code>wsse:KeyIdentifier</code> element, which is placed in the
 * <code>wsse:SecurityTokenReference</code> element.
 * 
 * @param cert
 *            is the X509 certificate to get the thumbprint
 */
public void setKeyIdentifierThumb(X509Certificate cert) throws WSSecurityException {
    Document doc = this.element.getOwnerDocument();
    MessageDigest sha = null;
    try {
        sha = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e1) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "noSHA1availabe", null, e1);
    }
    sha.reset();
    try {
        sha.update(cert.getEncoded());
    } catch (CertificateEncodingException e1) {
        throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "encodeError", null, e1);
    }
    byte[] data = sha.digest();

    org.w3c.dom.Text text = doc.createTextNode(Base64.encode(data));
    createKeyIdentifier(doc, THUMB_URI, text, true);
}

From source file:org.dspace.eperson.PasswordHash.java

/**
 * Generate a salted hash of a string using a given algorithm.
 *
 * @param salt random bytes to salt the hash.
 * @param algorithm name of the digest algorithm to use.  Assume unsalted MD5 if null.
 * @param secret the string to be hashed.  Null is treated as an empty string ("").
 * @return hash bytes./*from  ww  w.j a  v a  2 s  .  com*/
 * @throws NoSuchAlgorithmException if algorithm is unknown.
 */
private byte[] digest(byte[] salt, String algorithm, String secret) throws NoSuchAlgorithmException {
    MessageDigest digester;

    if (null == secret)
        secret = "";

    // Special case:  old unsalted one-trip MD5 hash.
    if (null == algorithm) {
        digester = MessageDigest.getInstance("MD5");
        digester.update(secret.getBytes(UTF_8));
        return digester.digest();
    }

    // Set up a digest
    digester = MessageDigest.getInstance(algorithm);

    // Grind up the salt with the password, yielding a hash
    if (null != salt)
        digester.update(salt);

    digester.update(secret.getBytes(UTF_8)); // Round 0

    for (int round = 1; round < HASH_ROUNDS; round++) {
        byte[] lastRound = digester.digest();
        digester.reset();
        digester.update(lastRound);
    }

    return digester.digest();
}

From source file:org.apache.ws.security.components.crypto.CryptoBase.java

/**
 * Lookup a X509 Certificate in the keystore according to a given
 * Thumbprint./*from www. jav a 2  s . com*/
 * <p/>
 * The search gets all alias names of the keystore, then reads the certificate chain
 * or certificate for each alias. Then the thumbprint for each user certificate
 * is compared with the thumbprint parameter.
 *
 * @param thumb The SHA1 thumbprint info bytes
 * @return alias name of the certificate that matches the thumbprint
 *         or null if no such certificate was found.
 * @throws org.apache.ws.security.WSSecurityException
 *          if problems during keystore handling or wrong certificate
 */
public String getAliasForX509CertThumb(byte[] thumb) throws WSSecurityException {
    Certificate cert = null;
    MessageDigest sha = null;

    if (keystore == null) {
        return null;
    }

    try {
        sha = MessageDigest.getInstance("SHA-1");
        sha.reset();
    } catch (NoSuchAlgorithmException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "noSHA1availabe", null, e);
    }
    try {
        for (Enumeration e = keystore.aliases(); e.hasMoreElements();) {
            String alias = (String) e.nextElement();
            Certificate[] certs = keystore.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a  result.
                cert = keystore.getCertificate(alias);
                if (cert == null) {
                    continue;
                }
            } else {
                cert = certs[0];
            }
            if (!(cert instanceof X509Certificate)) {
                continue;
            }
            try {
                sha.update(cert.getEncoded());
            } catch (CertificateEncodingException ex) {
                throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "encodeError",
                        null, ex);
            }
            byte[] data = sha.digest();

            if (Arrays.equals(data, thumb)) {
                return alias;
            }
        }
    } catch (KeyStoreException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e);
    }
    return null;
}

From source file:stargate.drivers.recipe.sha1fixed.SHA1FixedChunkRecipeGeneratorDriver.java

@Override
public synchronized Recipe getRecipe(DataObjectMetadata metadata, InputStream is) throws IOException {
    if (metadata == null || metadata.isEmpty()) {
        throw new IllegalArgumentException("metadata is null or empty");
    }/*  w w w .  j  av  a2  s  . co  m*/

    if (is == null) {
        throw new IllegalArgumentException("is is null");
    }

    List<RecipeChunk> chunk = new ArrayList<RecipeChunk>();

    int bufferSize = Math.min(this.chunkSize, BUFFER_SIZE);
    byte[] buffer = new byte[bufferSize];

    try {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
        DigestInputStream dis = new DigestInputStream(is, messageDigest);

        long chunkOffset = 0;

        while (chunkOffset < metadata.getObjectSize()) {
            int chunkLength = 0;
            int nread = 0;
            int toread = this.chunkSize;

            while ((nread = dis.read(buffer, 0, Math.min(toread, bufferSize))) > 0) {
                chunkLength += nread;
                toread -= nread;
                if (toread == 0) {
                    break;
                }
            }

            byte[] digest = messageDigest.digest();
            chunk.add(new RecipeChunk(chunkOffset, chunkLength, digest));
            messageDigest.reset();

            if (nread <= 0) {
                //EOF
                break;
            }

            chunkOffset += chunkLength;
        }

        dis.close();
    } catch (NoSuchAlgorithmException ex) {
        throw new IOException(ex);
    }

    return new Recipe(metadata, HASH_ALGORITHM, this.chunkSize, chunk);
}

From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java

/**
 * Compute a hash of the input stream using the configured algorithm
 * //from   w w  w  . ja v a2 s .  c o m
 * @param contentSteam
 * @return a hash of the content stream
 */
public byte[] computeHash(InputStream contentStream) {

    String alg = config.getProperty(RepositoryManagedSignatureProviderFactory.HASH_ALGORITHM);

    MessageDigest messageDigest = null;
    try {
        messageDigest = MessageDigest.getInstance(alg);
    } catch (NoSuchAlgorithmException e) {
        logger.error("Unable to process algorithm type: " + alg);
        return null;
    }
    messageDigest.reset();
    byte[] buffer = new byte[1024];
    int bytesRead = -1;
    try {
        while ((bytesRead = contentStream.read(buffer)) > -1) {
            messageDigest.update(buffer, 0, bytesRead);
        }
    } catch (IOException e) {
        logger.error("Unable to read content stream.", e);
        return null;
    } finally {
        try {
            contentStream.close();
        } catch (IOException e) {
        }
    }
    byte[] digest = messageDigest.digest();
    return convertByteArrayToHex(digest).getBytes();
}