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:hu.sch.vir.auth.password.HashTransform.java

/**
 * Hashes the input using the supplied algorithm. If the salt is null or
 * empty it will be ignored. Depends from value of the
 * {@link #SALT_AFTER_PASSWORD} option, the salt will be appended before or
 * after the password. The returned value is a base64 encoded string
 * representation of the hash./*from ww  w.  j  a  va 2s. c om*/
 *
 * @param algorithm The algorithm to use (e.g. MD5, SHA-256)
 * @param password The input to hash
 * @param salt The salt to prepend / append after the input (may be null)
 * @return Hashed input as base64 encoded string
 * @throws NoSuchAlgorithmException
 * @throws UnsupportedEncodingException
 */
private String hash(final String algorithm, final String input, final String salt)
        throws NoSuchAlgorithmException, UnsupportedEncodingException {

    final MessageDigest digest = MessageDigest.getInstance(algorithm);
    byte[] bytes = null;
    // Need to synchronize digest as it's succeptible to race
    // conditions
    synchronized (digest) {
        digest.reset();

        if (salt != null && salt.length() > 0) {
            if (isSaltAfterPassword()) {
                digest.update(input.getBytes("UTF-8"));
                digest.update(Base64.decodeBase64(salt));
            } else {
                digest.update(Base64.decodeBase64(salt));
                digest.update(input.getBytes("UTF-8"));
            }
        } else { //hash without salt
            digest.update(input.getBytes("UTF-8"));
        }

        bytes = digest.digest();
    }

    debug.message("hash() method returning=" + Base64.encodeBase64String(bytes).trim());

    return Base64.encodeBase64String(bytes).trim();
}

From source file:org.pieShare.pieTools.pieUtilities.service.security.hashService.MD5Service.java

@Override
public byte[] hashStream(InputStream stream) throws IOException {
    //todo: maybe the stream should be created in here instead outside
    //this way this function can close the stream in the end
    MessageDigest messageDigest = provider.getMessageDigest();

    byte[] buffer = new byte[1024];
    int read = 0;

    while ((read = stream.read(buffer)) != -1) {
        Validate.notNull(messageDigest);
        messageDigest.update(buffer, 0, read);
    }//from w  w w  .  j  a  v  a2  s .c  o m

    byte[] resultByte = messageDigest.digest();
    messageDigest.reset();
    return resultByte;
}

From source file:de.egore911.opengate.services.PilotService.java

private String hashPassword(String password) throws NoSuchAlgorithmException {
    MessageDigest messageDigest = MessageDigest.getInstance("MD5");
    messageDigest.reset();
    messageDigest.update(("Cheij3soo5ei" + password + "mohVaishei6e").getBytes());
    byte digest[] = messageDigest.digest();
    StringBuffer hexString = new StringBuffer();
    for (int i = 0; i < digest.length; i++) {
        hexString.append(Integer.toHexString(0xFF & digest[i]));
    }//from ww  w .  j  a v a  2  s.c  o m
    return hexString.toString();
}

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

/**
 * @param nonce/*from  w w w .ja  v  a  2 s. co m*/
 * @param request
 * @return -1 for a bad nonce, 0 for a stale none, 1 for a good nonce
 */
/* ------------------------------------------------------------ */
public int checkNonce(String nonce, HttpRequest request) {
    try {
        byte[] n = B64Code.decode(nonce.toCharArray());
        if (n.length != 24)
            return -1;

        long ts = 0;
        long sk = nonceSecret;
        byte[] n2 = new byte[16];
        for (int i = 0; i < 8; i++) {
            n2[i] = n[i];
            n2[8 + i] = (byte) (sk & 0xff);
            sk = sk >> 8;
            ts = (ts << 8) + (0xff & (long) n[7 - i]);
        }

        long age = request.getTimeStamp() - ts;
        if (log.isDebugEnabled())
            log.debug("age=" + age);

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

        for (int i = 0; i < 16; i++)
            if (n[i + 8] != hash[i])
                return -1;

        if (maxNonceAge > 0 && (age < 0 || age > maxNonceAge))
            return 0; // stale

        return 1;
    } catch (Exception e) {
        log.debug("", e);
    }
    return -1;
}

From source file:org.archive.modules.extractor.HTTPContentDigest.java

protected void innerProcess(CrawlURI curi) throws InterruptedException {
    // Ok, if we got this far we need to calculate the content digest. 
    // Get the regex
    String regex = getStripRegex();

    // Get a replay of the document character seq.
    ReplayCharSequence cs = null;// www  .jav  a  2 s  .  c  om
    try {
        cs = curi.getRecorder().getContentReplayCharSequence();
        // Create a MessageDigest 
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance(SHA1);
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
            return;
        }

        digest.reset();

        String s = null;

        if (StringUtils.isEmpty(regex)) {
            s = cs.toString();
        } else {
            // Process the document
            Matcher m = TextUtils.getMatcher(regex, cs);
            s = m.replaceAll(" ");
            TextUtils.recycleMatcher(m);
        }
        digest.update(s.getBytes());
        // Get the new digest value
        byte[] newDigestValue = digest.digest();
        // Save new digest value
        curi.setContentDigest(SHA1, newDigestValue);

    } catch (Exception e) {
        curi.getNonFatalFailures().add(e);
        logger.warning("Failed get of replay char sequence " + curi.toString() + " " + e.getMessage() + " "
                + Thread.currentThread().getName());
        return; // Can't proceed if this happens.
    }
}

From source file:org.OneEducation.HarvestClient.HarvestReporter.java

private String getUID() {
    String serial = Build.SERIAL;

    MessageDigest digest = null;

    try {/*  w  ww .ja  v a2s . c  o  m*/
        digest = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        Log.e("HarvestReporter", "getUID: no such algorithm");
        return null;
    }

    digest.reset();
    digest.update(serial.getBytes());

    String hash = new BigInteger(1, digest.digest()).toString(16);
    Log.d("HarvestReporter", hash);

    return hash;
}

From source file:ru.develgame.jflickrorganizer.LoginForm.java

private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOKActionPerformed
    if (jCheckBoxOfflineMode.isSelected()) {
        if (jTextFieldLogin.getText().isEmpty()) {
            // TODO
            return;
        }//from w w  w  .j  a  va  2  s  .  c o  m

        String pass = new String(jPassword.getPassword());
        if (pass.isEmpty()) {
            // TODO
            return;
        }

        User userByName = userRepository.findByName(jTextFieldLogin.getText());
        if (userByName == null) {
            // TODO
            return;
        }

        if (userByName.getPass() == null || userByName.getPass().isEmpty()) {
            // TODO
            return;
        }

        String hashedPass = "";
        try {
            MessageDigest m = MessageDigest.getInstance("SHA-1");
            m.reset();
            m.update(pass.getBytes());
            hashedPass = new String(m.digest());
        } catch (NoSuchAlgorithmException ex) {
            // TODO
            return;
        }

        if (!hashedPass.equals(userByName.getPass())) {
            // TODO
            return;
        }

        authorizer.setOfflineMode(true);
        authorizer.setUser(userByName);
    } else {
        if (jTextFieldToken.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this,
                    LocaleMessages.getMessage("LoginForm.Warning.TokenCannotBeEmpty"),
                    LocaleMessages.getMessage("WarningTitle"), JOptionPane.WARNING_MESSAGE);

            return;
        }

        if (!authorizer.doAuthorize(jTextFieldToken.getText())) {
            JOptionPane.showMessageDialog(this,
                    LocaleMessages.getMessage("LoginForm.Error.AuthorizationFailed"),
                    LocaleMessages.getMessage("ErrorTitle"), JOptionPane.ERROR_MESSAGE);

            return;
        }

        User userByName = userRepository.findByName(authorizer.getAuth().getUser().getUsername());
        if (userByName == null) {
            userByName = new User(authorizer.getAuth().getUser().getUsername());
            userRepository.save(userByName);
        }

        authorizer.setUser(userByName);
    }

    getMainForm().setVisible(true);

    this.setVisible(false);
    this.dispose();
}

From source file:gov.nih.nci.cacis.nav.DefaultDocumentReferenceValidator.java

@Override
public void validate(Node reference, XDSDocumentResolver resolver) throws DocumentReferenceValidationException {

    // Pull out the necessary information
    final String alg;
    final String digestValue;
    final String documentId;
    try {// w  ww.  j  a v  a2  s . c  o m
        alg = NAVUtils.getDigestAlgorithm(reference);
        digestValue = NAVUtils.getDigestValue(reference);
        documentId = NAVUtils.getDocumentId(reference);
        // CHECKSTYLE:OFF - All NAVUtils errors handled the same way.
    } catch (Exception ex) {
        // CHECKSTYLE:ON
        throw new DocumentReferenceValidationException(
                "Error extracting info from Reference: " + ex.getMessage(), ex);
    }

    if (!getSupportedAlgorithms().containsKey(alg)) {
        throw new DocumentReferenceValidationException("Unsupported digest algorithm: " + alg);
    }
    if (digestValue == null) {
        throw new DocumentReferenceValidationException("No DigestValue provided.");
    }

    // Resolve the document
    final InputStream in;
    try {
        in = resolver.resolve(documentId);
    } catch (XDSDocumentResolutionException ex) {
        throw new DocumentReferenceValidationException(ex);
    }

    // Generate the digest
    final byte[] bytes;
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    final byte[] data = new byte[16384];
    int nRead;
    try {
        while ((nRead = in.read(data, 0, data.length)) != -1) { // NOPMD
            buffer.write(data, 0, nRead);
        }
        buffer.flush();
        bytes = buffer.toByteArray();
    } catch (IOException ex) {
        throw new DocumentReferenceValidationException(ex);
    }

    final MessageDigest digest;
    try {
        digest = MessageDigest.getInstance(getSupportedAlgorithms().get(alg));
    } catch (NoSuchAlgorithmException ex) {
        throw new DocumentReferenceValidationException(ex);
    }
    digest.reset();
    final byte[] out = digest.digest(bytes);

    // BASE64 encode it
    final String outEnc = new String(Base64.encodeBase64(out));

    // Compare it
    if (!outEnc.equals(digestValue)) {
        throw new DocumentReferenceValidationException("Digests do not match.");
    }
}

From source file:org.n2.app.beans.RegisterBean.java

/**
 * From a password, a number of iterations and a salt,
 * returns the corresponding digest// w  w  w .j  a va  2  s  .co m
 * @param iterationNb int The number of iterations of the algorithm
 * @param password String The password to encrypt
 * @param salt byte[] The salt
 * @return byte[] The digested password
 * @throws NoSuchAlgorithmException If the algorithm doesn't exist
 * @throws UnsupportedEncodingException 
 */
public byte[] getHash(int iterationNb, String password, byte[] salt)
        throws NoSuchAlgorithmException, UnsupportedEncodingException {
    MessageDigest digest = MessageDigest.getInstance("SHA-1");
    digest.reset();
    digest.update(salt);
    byte[] input = digest.digest(password.getBytes("UTF-8"));
    for (int i = 0; i < iterationNb; i++) {
        digest.reset();
        input = digest.digest(input);
    }
    return input;
}

From source file:org.qxsched.doc.afp.GenericAfpRecord.java

public boolean writeMd(BufferedWriter out, AfpReadWriteProperties props, String prefix, byte[] data)
        throws IOException, AfpException {

    try {//from   w w  w . j  a  v a  2s . c  o m
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.reset();
        messageDigest.update(data);
        byte[] digest = messageDigest.digest();

        // Write digext
        AfpDump.dumpData(out, props, "MD5: ", prefix, digest);

    } catch (NoSuchAlgorithmException e) {
        LOG.error("No MD5 MessageDigest", e);
        return false;
    }

    return true;
}