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:com.ziaconsulting.zoho.EditorController.java

private String generateDocumentId(String base) {
    byte messageDigest[] = {};
    try {/*from   w  ww.java2s .  c  o  m*/
        MessageDigest algorithm = MessageDigest.getInstance("MD5");
        algorithm.reset();
        algorithm.update(base.getBytes());
        messageDigest = algorithm.digest();
    } catch (NoSuchAlgorithmException nsae) {

    }

    String md5DocId;
    StringBuffer md5DocIdBuffer = new StringBuffer();
    for (byte msg : messageDigest) {
        md5DocIdBuffer.append(Byte.toString(msg));
    }

    // Changed this to invalidate the current documents
    // Id needs to be only integers, < 19 characters long
    md5DocId = "6" + md5DocIdBuffer.toString().replace("-", "").substring(0, 17);

    return md5DocId;
}

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

public synchronized boolean verify(String digest, String password) throws NoSuchAlgorithmException {

    String alg = null;/*from  w w w. j  ava 2 s  . c om*/
    int size = 0;

    if (digest.regionMatches(true, 0, "{CRYPT}", 0, 7)) {
        digest = digest.substring(7);
        return UnixCrypt.matches(digest, password);
    } else if (digest.regionMatches(true, 0, "{SHA}", 0, 5)) {
        digest = digest.substring(5); // ignore the label
        alg = "SHA-1";
        size = 20;
    } else if (digest.regionMatches(true, 0, "{SSHA}", 0, 6)) {
        digest = digest.substring(6); // ignore the label
        alg = "SHA-1";
        size = 20;
    } else if (digest.regionMatches(true, 0, "{MD5}", 0, 5)) {
        digest = digest.substring(5); // ignore the label
        alg = "MD5";
        size = 16;
    } else if (digest.regionMatches(true, 0, "{SMD5}", 0, 6)) {
        digest = digest.substring(6); // ignore the label
        alg = "MD5";
        size = 16;
    }

    // TODO: vrifier si le synchronized que j'ai ajout est ncessaire
    MessageDigest msgDigest = MessageDigest.getInstance(alg);

    byte[][] hs = split(Base64.decodeBase64(digest), size);
    byte[] hash = hs[0];
    byte[] salt = hs[1];

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

    byte[] pwhash = msgDigest.digest();

    return MessageDigest.isEqual(hash, pwhash);
}

From source file:pl.nask.hsn2.service.analysis.JSWekaAnalyzer.java

/**
 * Returns hex string representation of MD5 hash for given file.
 * /*w w w  .j  a v  a 2s .  c  o  m*/
 * @param fileName
 * @return
 * @throws IOException
 */
public final String md5hashFromFile(BufferedInputStream bufferedInputStream) throws IOException {
    bufferedInputStream.reset();
    String result = null;
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("MD5");
        md.reset();
        try (InputStream dis = new DigestInputStream(new WhiteListFileInputStream(bufferedInputStream), md)) {
            while (dis.read() != -1) { //NOPMD
                // Nothing to do.
            }
            char[] md5 = Hex.encodeHex(md.digest());
            result = String.valueOf(md5);
        }
    } catch (NoSuchAlgorithmException e) {
        LOGGER.error("Could not create MD5 hash for whitelisting.\n{}", e);
        result = "";
    }
    return result;
}

From source file:com.tourmaline.example.ExampleApplication.java

/**
 * Calculate the SHA256 digest of a string and return hexadecimal string
 * representation of digest.//  w ww  .  ja va 2  s.c o  m
 *
 * @param str String to be digested.
 * @return String digest as a hexadecimal string
 */
private String HashId(String str) {
    String result = "";
    try {
        final MessageDigest digester = MessageDigest.getInstance("SHA-256");
        digester.reset();
        byte[] dig = digester.digest(str.getBytes());
        result = String.format("%0" + (dig.length * 2) + "X", new BigInteger(1, dig)).toUpperCase();
    } catch (NoSuchAlgorithmException e) {
        Log.e(LOG_AREA, "No SHA 256 wtf");
    }
    return result;
}

From source file:org.jumpmind.security.SecurityService.java

public String nextSecureHexString(int len) {
    if (len <= 0)
        throw new IllegalArgumentException("length must be positive");
    SecureRandom secRan = getSecRan();
    MessageDigest alg = null;
    try {/* ww  w.  j  av  a  2s .co m*/
        alg = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException ex) {
        return null;
    }
    alg.reset();
    int numIter = len / 40 + 1;
    StringBuffer outBuffer = new StringBuffer();
    for (int iter = 1; iter < numIter + 1; iter++) {
        byte randomBytes[] = new byte[40];
        secRan.nextBytes(randomBytes);
        alg.update(randomBytes);
        byte hash[] = alg.digest();
        for (int i = 0; i < hash.length; i++) {
            Integer c = new Integer(hash[i]);
            String hex = Integer.toHexString(c.intValue() + 128);
            if (hex.length() == 1)
                hex = "0" + hex;
            outBuffer.append(hex);
        }

    }

    return outBuffer.toString().substring(0, len);
}

From source file:inti.ws.spring.resource.ByteWebResource.java

/**
 * Reads the file and stores it's content.
 *//*from  w ww  . j a v a2  s  .c  o  m*/
@Override
public void update() throws Exception {
    StringBuilder builder = new StringBuilder(32);
    MessageDigest digest = DIGESTS.get();
    InputStream inputStream = resource.getInputStream();

    try {
        lastModified = resource.lastModified();
        bytes = IOUtils.toByteArray(inputStream);
    } finally {
        inputStream.close();
    }

    digest.reset();
    builder.append(Hex.encodeHexString(digest.digest(bytes)));
    messageDigest = builder.toString();
    builder.delete(0, builder.length());

    DATE_FORMATTER.formatDate(lastModified, builder);
    lastModifiedString = builder.toString();
}

From source file:net.lightbody.bmp.proxy.jetty.http.DigestAuthenticator.java

public String newNonce(HttpRequest request) {
    long ts = request.getTimeStamp();
    long sk = nonceSecret;

    byte[] nounce = new byte[24];
    for (int i = 0; i < 8; i++) {
        nounce[i] = (byte) (ts & 0xff);
        ts = ts >> 8;//from www  .j a v  a 2 s  .  co m
        nounce[8 + i] = (byte) (sk & 0xff);
        sk = sk >> 8;
    }

    byte[] hash = null;
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.reset();
        md.update(nounce, 0, 16);
        hash = md.digest();
    } catch (Exception e) {
        log.fatal(this, e);
    }

    for (int i = 0; i < hash.length; i++) {
        nounce[8 + i] = hash[i];
        if (i == 23)
            break;
    }

    return new String(B64Code.encode(nounce));
}

From source file:ch.bfh.srs.srv.entity.User.java

public String generateHash(String password, String salt) {
    MessageDigest md = null;
    try {//  w  ww . ja  va 2 s .c o  m
        md = MessageDigest.getInstance("SHA-256");
    } catch (Exception e) {
        log.error("The Environment doesn't support sha256", e);
    }
    try {
        md.reset();
        md.update(salt.getBytes("UTF-8"));
        String hash = String.valueOf(Hex.encodeHex(md.digest(password.getBytes("UTF-8"))));
        return hash;
    } catch (Exception e) {
        return "Hashing the password failed for mysterious Reasons";
    }
}

From source file:com.chinamobile.bcbsp.subgraph.SGAHashPartitioner.java

/**
 * Partitions a vertex according the id mapping to a partition.
 * /*from ww w.ja  v  a 2s  . c om*/
 * @return a number between 0 and numPartition that tells which partition it
 *         belongs to.
 * @param id
 *        the vertex id
 */
@Override
public int getPartitionID(IDT id) {

    if (migrateVertexPartition.size() != 0) {
        if (this.migrateVertexPartition.containsKey(id)) {
            return this.migrateVertexPartition.get(id);
        }
    }
    String url = id.toString();
    MessageDigest md5 = null;
    if (md5 == null) {
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("++++ no md5 algorythm found");
        }
    }
    md5.reset();
    md5.update(url.getBytes());
    byte[] bKey = md5.digest();
    long hashcode = ((long) (bKey[INDEX_3] & NUMBER) << OFFSET_3)
            | ((long) (bKey[INDEX_2] & NUMBER) << OFFSET_2) | ((long) (bKey[INDEX_1] & NUMBER) << OFFSET_1)
            | bKey[INDEX_0] & NUMBER;
    int result = (int) (hashcode % this.numPartition);
    if (result < 0) {
        result = result + this.numPartition;
    }
    return result;
}

From source file:com.redhat.rhn.common.util.MD5Crypt.java

/**
 * crypt/* w ww  .  j  a v  a2 s . com*/
 * Encodes a key using a salt (s) in the same manner as the
 * perl crypt() function.
 * This method will be called directly when checking passwords. It will
 * also be called from the crypt(key) function when setting a password.
 * @param key - The key to encode
 * @param s - The salt
 * @return Returns a string in the form of "$1$salt$encodedkey"
 * @throws MD5CryptException
 */
public static String crypt(String key, String s) {

    /**
     * If this method is called in order for a comparison, s may be
     * in the form of $1$salt$encodedkey. We'll need to extract
     * the salt from it.
     */
    String salt = CryptHelper.getSalt(s, CryptHelper.getMD5Prefix(), saltLength);

    MessageDigest md1;
    MessageDigest md2;
    try {
        md1 = MessageDigest.getInstance("MD5");
        md2 = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new MD5CryptException("Problem getting MD5 message digest " + "(NoSuchAlgorithm Exception).");
    }

    byte[] keyBytes = key.getBytes();
    byte[] saltBytes = salt.getBytes();
    byte[] prefixBytes = CryptHelper.getMD5Prefix().getBytes();
    int keylength = key.length();

    //Update first MessageDigest - key/prefix/salt
    md1.update(keyBytes);
    md1.update(prefixBytes);
    md1.update(saltBytes);

    //Update second MessageDigest - key/salt/key
    md2.update(keyBytes);
    md2.update(saltBytes);
    md2.update(keyBytes);

    byte[] md2Digest = md2.digest();
    int md2DigestLength = md2Digest.length;

    for (int i = keylength; i > 0; i -= md2DigestLength) {
        if (i > md2DigestLength) {
            md1.update(md2Digest, 0, md2DigestLength);
        } else {
            md1.update(md2Digest, 0, i);
        }
    }

    md2.reset();

    for (int i = keylength; i > 0; i >>= 1) {
        if ((i & 1) == 1) {
            md1.update((byte) 0);
        } else {
            md1.update(keyBytes[0]);
        }
    }

    byte[] md1Digest = md1.digest();

    for (int i = 0; i < 1000; i++) {
        md2.reset();
        if ((i & 1) == 1) {
            md2.update(keyBytes);
        } else {
            md2.update(md1Digest);
        }
        if ((i % 3) != 0) {
            md2.update(saltBytes);
        }
        if ((i % 7) != 0) {
            md2.update(keyBytes);
        }
        if ((i & 1) != 0) {
            md2.update(md1Digest);
        } else {
            md2.update(keyBytes);
        }
        md1Digest = md2.digest();
    }

    return generateEncodedKey(md1Digest, salt);
}