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:fi.okm.mpass.idp.authn.impl.AbstractSpringSocialOAuth2Identity.java

/**
 * Throws an error if state parameter is not the expected one.
 * //from www  . j  av  a 2  s.  c  om
 * @param httpRequest
 *            is the httpRequest we check for state.
 * @throws SocialUserAuthenticationException
 *             if the parameter is missing or mismatches.
 * */
private void validateState(HttpServletRequest httpRequest) throws SocialUserAuthenticationException {
    log.trace("Entering");
    String state = httpRequest.getParameter("state");
    if (state == null) {
        log.trace("Leaving");
        throw new SocialUserAuthenticationException("State parameter missing", SocialUserErrorIds.EXCEPTION);
    }
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        log.error("Unable to generate state");
        log.error("Something bad happened " + e.getMessage());
        log.trace("Leaving");
        throw new SocialUserAuthenticationException("Unable to hash, use some other method",
                SocialUserErrorIds.EXCEPTION);
    }
    md.reset();
    md.update(httpRequest.getSession().getId().getBytes());
    String cmpState = new String(Hex.encode(md.digest()));
    if (!state.equalsIgnoreCase(cmpState)) {
        log.error("state parameter mismatch");
        log.trace("Leaving");
        throw new SocialUserAuthenticationException("State parameter mismatch", SocialUserErrorIds.EXCEPTION);
    }
}

From source file:fr.aliacom.obm.ldap.PasswordHandler.java

public String generateDigest(String password, String saltHex, String algorithm)
        throws NoSuchAlgorithmException {

    if (algorithm.equalsIgnoreCase("crypt")) {
        return "{CRYPT}" + UnixCrypt.crypt(password);
    } else if (algorithm.equalsIgnoreCase("sha")) {
        algorithm = "SHA-1";
    } else if (algorithm.equalsIgnoreCase("md5")) {
        algorithm = "MD5";
    }/*from   w  w  w .  ja  v  a2s  . c o  m*/

    MessageDigest msgDigest = MessageDigest.getInstance(algorithm);

    byte[] salt = {};
    if (saltHex != null) {
        salt = fromHex(saltHex);
    }

    String label = null;

    if (algorithm.startsWith("SHA")) {
        label = (salt.length > 0) ? "{SSHA}" : "{SHA}";
    } else if (algorithm.startsWith("MD5")) {
        label = (salt.length > 0) ? "{SMD5}" : "{MD5}";
    } else {
        throw new IllegalArgumentException(String.format("Unknown algorithm: %s", algorithm));
    }

    msgDigest.reset();
    msgDigest.update(password.getBytes(Charsets.UTF_8));
    msgDigest.update(salt);

    byte[] pwhash = msgDigest.digest();

    StringBuffer digest = new StringBuffer(label);
    digest.append(Base64.encodeBase64String(concatenate(pwhash, salt)));

    return digest.toString();
}

From source file:org.bremersee.common.security.crypto.password.PasswordEncoderImpl.java

@Override
public byte[] createUserPassword(final String clearPassword) {

    if (clearPassword == null) {
        return null; // NOSONAR
    }//from w  w  w  . ja va 2  s  .  c om

    if (NO_ENCRYPTION.equalsIgnoreCase(algorithm)) {
        return CodingUtils.toBytesSilently(clearPassword, StandardCharsets.UTF_8);
    }

    final MessageDigest md = getMessageDigest(algorithm);

    final byte[] digest;
    if (isSaltedSha(algorithm)) {

        byte[] salt = getRandomSalt();

        md.reset();
        md.update(CodingUtils.toBytesSilently(clearPassword, StandardCharsets.UTF_8));
        md.update(salt);

        // Complete hash computation, this results in binary data
        byte[] pwhash = md.digest();

        digest = concatenate(pwhash, salt);

    } else {

        digest = md.digest(CodingUtils.toBytesSilently(clearPassword, StandardCharsets.UTF_8));
    }

    String result = "{" + algorithm + "}"
            + CodingUtils.toStringSilently(Base64.encodeBase64(digest), StandardCharsets.UTF_8);
    return CodingUtils.toBytesSilently(result, StandardCharsets.UTF_8);
}

From source file:eionet.gdem.utils.Utils.java

/**
 *
 * @param f//from w w w . j  a  va  2s  .c  o  m
 * @param algorithm
 * @return
 * @throws Exception
 */
public static String digest(File f, String algorithm) throws Exception {

    byte[] dstBytes = new byte[16];

    MessageDigest md;

    md = MessageDigest.getInstance(algorithm);

    BufferedInputStream in = null;

    int theByte = 0;
    try {
        in = new BufferedInputStream(new FileInputStream(f));
        while ((theByte = in.read()) != -1) {
            md.update((byte) theByte);
        }
    } finally {
        try {
            in.close();
        } catch (Exception e) {
        }
    }
    dstBytes = md.digest();
    md.reset();

    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < dstBytes.length; i++) {
        Byte byteWrapper = new Byte(dstBytes[i]);
        int k = byteWrapper.intValue();
        String s = Integer.toHexString(k);
        if (s.length() == 1) {
            s = "0" + s;
        }
        buf.append(s.substring(s.length() - 2));
    }

    return buf.toString();
}

From source file:org.apache.qpid.amqp_1_0.client.Filesender.java

private Message createMessageFromFile(MessageDigest md5, String fileName, File file) throws IOException {
    FileInputStream fis = new FileInputStream(file);
    byte[] data = new byte[(int) file.length()];

    int read = fis.read(data);

    fis.close();/*from  www  .jav  a2  s .  co  m*/

    Section applicationProperties = new ApplicationProperties(Collections.singletonMap("filename", fileName));
    Section amqpValue = new Data(new Binary(data));
    Message message = new Message(Arrays.asList(applicationProperties, amqpValue));
    Binary deliveryTag = new Binary(md5.digest(fileName.getBytes()));
    message.setDeliveryTag(deliveryTag);
    md5.reset();
    return message;
}

From source file:org.apache.ws.security.message.WSSecEncrypt.java

private String getSHA1(byte[] input) throws WSSecurityException {
    try {/*from  w  ww. j a v a2 s  .c  om*/
        MessageDigest sha = null;
        sha = MessageDigest.getInstance("SHA-1");
        sha.reset();
        sha.update(input);
        byte[] data = sha.digest();

        return Base64.encode(data);
    } catch (NoSuchAlgorithmException e) {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e);
    }
}

From source file:org.lockss.hasher.BlockHasher.java

private HashedInputStream.Hasher getStreamHasher(String alg) {
    // Either to create or to verify a hash in the properties we need to
    // hash this version's unfiltered content with the specified algorithm.
    // Do we already have a suitable MessageDigest?
    MessageDigest dig = localHashDigestMap.get(alg);
    if (dig != null) {
        // Yes, reset it
        dig.reset();
    } else {/*from  ww  w .j  av  a2 s . c  o  m*/
        // No, make one
        try {
            dig = MessageDigest.getInstance(alg);
            localHashDigestMap.put(alg, dig);
            if (isTrace) {
                log.debug3(
                        "Created MessageDigest " + alg + " for " + curVer.getUrl() + ":" + curVer.getVersion());
            }
        } catch (NoSuchAlgorithmException ex) {
            log.error(alg + " for " + curVer.getUrl() + ":" + curVer.getVersion() + " throws " + ex);
            return null;
        }
    }
    return new HashedInputStream.Hasher(dig);
}

From source file:org.apache.hadoop.hive.ql.exec.UserTask.java

private int createUser(CreateUserDesc createUserDesc) throws AuthorizeException {
    MessageDigest sha1 = null;
    try {//from  ww w .ja v a  2 s .  c om
        sha1 = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException nsae) {
        LOG.info("create user: " + StringUtils.stringifyException(nsae));
        errorMessage = "create user: " + StringUtils.stringifyException(nsae);
        return 2;
    }
    // FIXME: it isn't an atom operation
    List<String> names = createUserDesc.getUserNames();
    List<String> passwords = createUserDesc.getPasswords();
    int len = names.size();
    for (int i = 0; i < len; i++) {
        String name = names.get(i);
        String password = passwords.get(i);
        try {
            sha1.reset();
            byte[] buff = sha1.digest(password.getBytes());
            db.createUser(name, buff);
        } catch (HiveException he) {
            LOG.info("create user: " + StringUtils.stringifyException(he));
            errorMessage = "create user: " + StringUtils.stringifyException(he);
            return 1;
        }
    }
    return 0;
}

From source file:mobac.mapsources.loader.MapPackManager.java

/**
 * Calculate the md5sum on all files in the map pack file (except those in META-INF) and their filenames inclusive
 * path in the map pack file)./*from  w ww  .j  av  a 2 s. c o m*/
 * 
 * @param mapPackFile
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
public String generateMappackMD5(File mapPackFile) throws IOException, NoSuchAlgorithmException {
    ZipFile zip = new ZipFile(mapPackFile);
    try {
        Enumeration<? extends ZipEntry> entries = zip.entries();
        MessageDigest md5Total = MessageDigest.getInstance("MD5");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();

            if (entry.isDirectory())
                continue;
            // Do not hash files from META-INF
            String name = entry.getName();
            if (name.toUpperCase().startsWith("META-INF"))
                continue;
            md5.reset();
            InputStream in = zip.getInputStream(entry);
            byte[] data = Utilities.getInputBytes(in);
            in.close();
            // name = name.replaceAll("\\\\", "/");
            byte[] digest = md5.digest(data);
            log.trace("Hashsum " + Hex.encodeHexString(digest) + " includes \"" + name + "\"");
            md5Total.update(digest);
            md5Total.update(name.getBytes());
        }
        String md5sum = Hex.encodeHexString(md5Total.digest());
        log.trace("md5sum of " + mapPackFile.getName() + ": " + md5sum);
        return md5sum;
    } finally {
        zip.close();
    }
}

From source file:org.opencms.security.CmsDefaultPasswordHandler.java

/**
 * @see org.opencms.security.I_CmsPasswordHandler#digest(java.lang.String, java.lang.String, java.lang.String)
 *//*from   w w  w .j  ava 2s.  co m*/
public String digest(String password, String digestType, String inputEncoding)
        throws CmsPasswordEncryptionException {

    MessageDigest md;
    String result;

    try {
        if (DIGEST_TYPE_PLAIN.equals(digestType.toLowerCase())) {

            result = password;

        } else if (DIGEST_TYPE_SSHA.equals(digestType.toLowerCase())) {

            byte[] salt = new byte[4];
            byte[] digest;
            byte[] total;

            if (m_secureRandom == null) {
                m_secureRandom = SecureRandom.getInstance("SHA1PRNG");
            }
            m_secureRandom.nextBytes(salt);

            md = MessageDigest.getInstance(DIGEST_TYPE_SHA);
            md.reset();
            md.update(password.getBytes(inputEncoding));
            md.update(salt);

            digest = md.digest();
            total = new byte[digest.length + salt.length];
            System.arraycopy(digest, 0, total, 0, digest.length);
            System.arraycopy(salt, 0, total, digest.length, salt.length);

            result = new String(Base64.encodeBase64(total));

        } else {

            md = MessageDigest.getInstance(digestType);
            md.reset();
            md.update(password.getBytes(inputEncoding));
            result = new String(Base64.encodeBase64(md.digest()));

        }
    } catch (NoSuchAlgorithmException e) {
        CmsMessageContainer message = Messages.get().container(Messages.ERR_UNSUPPORTED_ALGORITHM_1,
                digestType);
        if (LOG.isErrorEnabled()) {
            LOG.error(message.key(), e);
        }
        throw new CmsPasswordEncryptionException(message, e);
    } catch (UnsupportedEncodingException e) {
        CmsMessageContainer message = Messages.get().container(Messages.ERR_UNSUPPORTED_PASSWORD_ENCODING_1,
                inputEncoding);
        if (LOG.isErrorEnabled()) {
            LOG.error(message.key(), e);
        }
        throw new CmsPasswordEncryptionException(message, e);
    }

    return result;
}