Example usage for java.security MessageDigest getDigestLength

List of usage examples for java.security MessageDigest getDigestLength

Introduction

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

Prototype

public final int getDigestLength() 

Source Link

Document

Returns the length of the digest in bytes, or 0 if this operation is not supported by the provider and the implementation is not cloneable.

Usage

From source file:org.apache.cloudstack.utils.security.DigestHelper.java

private static String getPaddedDigestString(MessageDigest digest, BigInteger pwInt) {
    String checksum;/*  w  ww . j a  va2  s  .co  m*/
    String pwStr = pwInt.toString(16);
    // we have half byte string representation, so
    int padding = 2 * digest.getDigestLength() - pwStr.length();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < padding; i++) {
        sb.append('0'); // make sure the MD5 password is 32 digits long
    }
    sb.append(pwStr);
    checksum = sb.toString();
    return checksum;
}

From source file:org.collectionspace.chain.csp.webui.misc.Generic.java

/**
 * Function to create a hash for the record traverser functionality
 * @param csid//from w  w w .  j  a  va  2s  . c  o  m
 * @return
 * @throws UIException 
 */
public static String createHash(String csid) throws UIException {
    try {
        byte[] buffer = csid.getBytes();
        byte[] result = null;
        StringBuffer buf = null;
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        result = new byte[md5.getDigestLength()];
        md5.reset();
        md5.update(buffer);
        result = md5.digest(tokensalt.getBytes());

        //create hex string from the 16-byte hash 
        buf = new StringBuffer(result.length * 2);
        for (int i = 0; i < result.length; i++) {
            int intVal = result[i] & 0xff;
            if (intVal < 0x10) {
                buf.append("0");
            }
            buf.append(Integer.toHexString(intVal).toUpperCase());
        }
        return buf.toString().substring(0, 32);
    } catch (NoSuchAlgorithmException e) {
        throw new UIException("There were problems with the algorithum");
    }
}

From source file:ch.cyberduck.core.sftp.openssh.OpenSSHHostKeyVerifier.java

/**
 * Generate the hashed representation of the given hostname. Useful for adding entries
 * with hashed hostnames to a known_hosts file. (see -H option of OpenSSH key-gen).
 *
 * @return the hashed representation, e.g., "|1|cDhrv7zwEUV3k71CEPHnhHZezhA=|Xo+2y6rUXo2OIWRAYhBOIijbJMA="
 *///from www.j a va  2 s  . c o  m
private static String hash(String hostname) throws IOException {
    MessageDigest sha1;
    try {
        sha1 = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    }
    byte[] salt = new byte[sha1.getDigestLength()];
    new SecureRandom().nextBytes(salt);
    byte[] hash;
    try {
        hash = hmacSha1Hash(salt, hostname);
    } catch (IOException e) {
        throw new IOException(e);
    }
    String base64_salt = new String(Base64.encodeBase64(salt));
    String base64_hash = new String(Base64.encodeBase64(hash));

    return String.format("|1|%s|%s", base64_salt, base64_hash);
}

From source file:cn.edu.zjnu.acm.judge.security.password.MessageDigestPasswordEncoder.java

MessageDigestPasswordEncoder(String algorithm) {
    this.algorithm = algorithm;
    MessageDigest prototype = getMessageDigest(algorithm);
    this.length = prototype.getDigestLength() << 1;
}

From source file:Cryptography.java

/**
 * Returns the type MessageDigest of the input text with the input salt.
 * @param type The type of the MessageDigest algorithm.
 * @param text The string to be converted.
 * @param salt The salt for the conversion.
 * @return The converted string.//w w  w .ja v a2 s .com
 * @throws NoSuchAlgorithmException
 * @throws UnsupportedEncodingException
 */
public String getHash(String type, String text, String salt)
        throws NoSuchAlgorithmException, UnsupportedEncodingException {
    MessageDigest md;
    md = MessageDigest.getInstance(type);
    byte[] hash = new byte[md.getDigestLength()];
    if (!salt.isEmpty()) {
        md.update(salt.getBytes("iso-8859-1"), 0, salt.length());
    }
    md.update(text.getBytes("iso-8859-1"), 0, text.length());
    hash = md.digest();
    return convertToHex(hash);
}

From source file:org.apache.metron.stellar.common.utils.hashing.DefaultHasher.java

/**
 * {@inheritDoc}/*from www  . j av  a2 s.com*/
 *
 * Returns a hash which has been encoded using the supplied encoder. If input is null then a string
 * containing all '0' will be returned. The length of the string is determined by the hashing algorithm
 * used.
 * @param toHash The value to hash.
 * @return A hash of {@code toHash} that has been encoded.
 * @throws EncoderException If unable to encode the hash then this exception occurs.
 * @throws NoSuchAlgorithmException If the supplied algorithm is not known.
 */
@Override
public String getHash(final Object toHash) throws EncoderException, NoSuchAlgorithmException {
    final MessageDigest messageDigest = MessageDigest.getInstance(algorithm);

    if (toHash == null) {
        return StringUtils.repeat("00", messageDigest.getDigestLength());
    } else if (toHash instanceof String) {
        return getHash(messageDigest, toHash.toString().getBytes(charset));
    } else if (toHash instanceof Serializable) {
        final byte[] serialized = SerializationUtils.serialize((Serializable) toHash);
        return getHash(messageDigest, serialized);
    }

    return null;
}

From source file:org.alder.fotobuchconvert.ifolor.Decryptor.java

private byte[] loadCompressedBinaryData(InputStream is) throws IOException, UnsupportedEncodingException {

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    byte[] buffer = new byte[4096];

    int bytesRead;
    // load md5 sum
    MessageDigest md;
    try {//  w  w w  .  ja va  2  s . c  o  m
        md = MessageDigest.getInstance(DIGEST_MD52);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    byte[] md5 = new byte[md.getDigestLength()];
    bytesRead = is.read(md5, 0, md5.length);
    if (bytesRead != md.getDigestLength())
        throw new IOException(UNEXPECTED_END_OF_FILE);

    // load size
    bytesRead = is.read(buffer, 0, 4);
    if (bytesRead != 4)
        throw new IOException(UNEXPECTED_END_OF_FILE);
    int dataSize = (((int) buffer[3] & 0xFF) << 24) | (((int) buffer[2] & 0xFF) << 16)
            | (((int) buffer[1] & 0xFF) << 8) | ((int) buffer[0] & 0xFF);
    log.debug("uncompressed file size: " + dataSize);

    GZIPInputStream gzipIs = new GZIPInputStream(is);
    while ((bytesRead = gzipIs.read(buffer)) != -1) {
        md.update(buffer, 0, bytesRead);
        output.write(buffer, 0, bytesRead);
        if (dumpData)
            System.out.print(new String(buffer, 0, bytesRead, CHARSET_cp1252));
    }
    if (dumpData)
        System.out.println();

    buffer = md.digest();
    for (int i = 0; i < buffer.length; i++)
        if (buffer[i] != md5[i])
            throw new IOException("MD5 mismatch");

    if (output.size() != dataSize)
        throw new IOException(String.format("File size mismatch: %d instead of %d", output.size(), dataSize));

    log.debug("MD5 ok");

    return output.toByteArray();
}

From source file:com.nirima.jenkins.repo.build.MetadataChecksumRepositoryItem.java

protected String generateContent() {
    try {/*from w w  w  .ja v  a2s.  c om*/
        MessageDigest md = MessageDigest.getInstance(algorithm.toUpperCase());
        byte[] digest = md.digest(IOUtils.toByteArray(item.getContent()));
        String hex = new BigInteger(1, digest).toString(16);

        // Need to prepend with 0s if not the correct length
        int requiredNumberOfCharacters = md.getDigestLength() * 2;
        while (hex.length() < requiredNumberOfCharacters) {
            hex = "0" + hex;
        }

        return hex;
    } catch (Exception nsae) {
        return "ERROR: " + nsae.getMessage();
    }
}

From source file:eu.semlibproject.annotationserver.managers.UtilsManager.java

/**
 * Compute the HASH of a string using a specific digest.
 * //w w w. ja  v a2s .c om
 * @param text      the text from which the hash will be created
 * @param digest    a digest (SHA-1, MD5 or CRC32)
 * @return          the hash of the passed String
 */
public String computeHashWithDigest(String text, String digest)
        throws NoSuchAlgorithmException, UnsupportedEncodingException {

    if (digest.equalsIgnoreCase("CRC32")) {
        return CRC32(text);
    } else {
        MessageDigest md;
        md = MessageDigest.getInstance(digest);
        byte[] digestBytes = new byte[md.getDigestLength()];
        md.update(text.getBytes("iso-8859-1"), 0, text.length());
        digestBytes = md.digest();
        return convertToHex(digestBytes);
    }

}

From source file:org.collectionspace.chain.csp.webui.userdetails.UserDetailsReset.java

private String createHash(String csid) throws UIException {
    try {/*w  w  w.  ja  va  2 s.co  m*/
        byte[] buffer = csid.getBytes();
        byte[] result = null;
        StringBuffer buf = null;
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        result = new byte[md5.getDigestLength()];
        md5.reset();
        md5.update(buffer);
        result = md5.digest(tokensalt.getBytes());

        //create hex string from the 16-byte hash 
        buf = new StringBuffer(result.length * 2);
        for (int i = 0; i < result.length; i++) {
            int intVal = result[i] & 0xff;
            if (intVal < 0x10) {
                buf.append("0");
            }
            buf.append(Integer.toHexString(intVal).toUpperCase());
        }
        return buf.toString().substring(0, 5);
    } catch (NoSuchAlgorithmException e) {
        throw new UIException("There were problems with the algorithum");
    }
}