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.playonlinux.core.utils.ChecksumCalculator.java

private byte[] getDigest(InputStream inputStream, MessageDigest messageDigest, long sizeInBytes)
        throws IOException {

    messageDigest.reset();
    byte[] bytes = new byte[BLOCK_SIZE];
    int numBytes;
    int readBytes = 0;
    while ((numBytes = inputStream.read(bytes)) != -1) {
        messageDigest.update(bytes, 0, numBytes);
        readBytes += numBytes;/*from   w w  w  .  j a  va2  s  .c  o  m*/
        if (sizeInBytes != 0L) {
            double percentage = (double) readBytes / (double) sizeInBytes * (double) 100;
            changeState(percentage);
        }
    }
    return messageDigest.digest();
}

From source file:org.sonar.batch.scan.filesystem.FileHashDigest.java

/**
 * Compute hash of a file ignoring line ends differences.
 * Maximum performance is needed./*from   w  ww .j a  v a2  s  .c o m*/
 */
String hash(File file, Charset charset) {
    Reader reader = null;
    try {
        MessageDigest md5Digest = DigestUtils.getMd5Digest();
        md5Digest.reset();
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
        int i = reader.read();
        boolean afterCR = true;
        while (i != -1) {
            char c = (char) i;
            if (afterCR) {
                afterCR = false;
                if (c == '\n') {
                    // Ignore
                    i = reader.read();
                    continue;
                }
            }
            if (c == '\r') {
                afterCR = true;
                c = '\n';
            }
            md5Digest.update(charToBytesUTF(c));
            i = reader.read();
        }
        return Hex.encodeHexString(md5Digest.digest());
    } catch (IOException e) {
        throw new IllegalStateException(String.format("Fail to compute hash of file %s with charset %s",
                file.getAbsolutePath(), charset), e);
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:dk.hlyh.hudson.plugins.mavenrepo.repo.ChecksumFile.java

@Override
public void sendResponse(StaplerRequest req, StaplerResponse rsp) throws IOException {
    FileInputStream fis = new FileInputStream(filename);
    try {// www. j  a  v a  2  s  .  co m
        MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
        messageDigest.reset();

        // Stream the file contents to the MessageDigest.
        byte[] buffer = new byte[STREAMING_BUFFER_SIZE];
        int size = fis.read(buffer, 0, STREAMING_BUFFER_SIZE);
        while (size >= 0) {
            messageDigest.update(buffer, 0, size);
            size = fis.read(buffer, 0, STREAMING_BUFFER_SIZE);
        }

        Hex encoder = new Hex();
        byte[] encodeded = encoder.encode(messageDigest.digest());

        rsp.setContentType("text/plain");
        rsp.getOutputStream().write(encodeded);

    } catch (NoSuchAlgorithmException ex) {
        log.warn("Could not generate '" + algorithm + "' checksum for: " + filename, ex);
        rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        try {
            fis.close();
        } catch (IOException e) {
            /* ignored */
        }
    }
}

From source file:lti.oauth.OAuthMessageSigner.java

/**
 * This method double encodes the parameter keys and values.
 * Thus, it expects the keys and values contained in the 'parameters' SortedMap
 * NOT to be encoded./*w w w . jav  a 2 s . c o  m*/
 * This method also generates oauth_body_hash parameter and adds it to 
 * 'parameters' SortedMap
 * 
 * @param secret
 * @param algorithm
 * @param method
 * @param url
 * @param parameters
 * @param requestBody
 * @return oauth signature
 * @throws Exception
 */
public String signWithBodyHash(String secret, String algorithm, String method, String url,
        SortedMap<String, String> parameters, String requestBody) throws Exception {

    byte[] bytes = requestBody.getBytes();

    MessageDigest sha = MessageDigest.getInstance("SHA-1");
    sha.reset();
    sha.update(bytes);
    byte[] encodedRequestBytes = Base64.encodeBase64(sha.digest());

    String oauthBodyHash = new String(encodedRequestBytes);

    parameters.put(OAuthUtil.OAUTH_POST_BODY_PARAMETER, oauthBodyHash);

    return sign(secret, algorithm, method, url, parameters);
}

From source file:com.noshufou.android.su.util.Util.java

public static String getHash(String pin) {
    MessageDigest digest;
    try {/*from  ww w . j  a  va 2  s  .  co  m*/
        digest = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        Log.e("Utils", "NoSuchAlgorithm, storing in plain text...", e);
        return pin;
    }
    digest.reset();
    try {
        byte[] input = digest.digest(pin.getBytes("UTF-8"));
        String base64 = Base64.encode(input);
        return base64;
    } catch (UnsupportedEncodingException e) {
        Log.e("Utils", "UnsupportedEncoding, storing in plain text...", e);
        return pin;
    }
}

From source file:org.apache.jena.reasoner.rulesys.builtins.MakeSkolem.java

/**
 * This method is invoked when the builtin is called in a rule body.
 * @param args the array of argument values for the builtin, this is an array 
 * of Nodes, some of which may be Node_RuleVariables.
 * @param length the length of the argument list, may be less than the length of the args array
 * for some rule engines//from w  w  w .  jav  a 2s.c o  m
 * @param context an execution context giving access to other relevant data
 * @return return true if the buildin predicate is deemed to have succeeded in
 * the current environment
 */
@Override
public boolean bodyCall(Node[] args, int length, RuleContext context) {
    StringBuilder key = new StringBuilder();
    for (int i = 1; i < length; i++) {
        Node n = getArg(i, args, context);
        if (n.isBlank()) {
            key.append("B");
            key.append(n.getBlankNodeLabel());
        } else if (n.isURI()) {
            key.append("U");
            key.append(n.getURI());
        } else if (n.isLiteral()) {
            key.append("L");
            key.append(n.getLiteralLexicalForm());
            if (n.getLiteralLanguage() != null)
                key.append("@" + n.getLiteralLanguage());
            if (n.getLiteralDatatypeURI() != null)
                key.append("^^" + n.getLiteralDatatypeURI());
        } else {
            key.append("O");
            key.append(n.toString());
        }
    }

    try {
        MessageDigest digester = MessageDigest.getInstance("MD5");
        digester.reset();
        byte[] digest = digester.digest(key.toString().getBytes());
        String label = Base64.encodeBase64String(digest);
        Node skolem = NodeFactory.createBlankNode(label);
        return context.getEnv().bind(args[0], skolem);
    } catch (NoSuchAlgorithmException e) {
        throw new JenaException(e);
    }
}

From source file:lydichris.smashbracket.services.UserService.java

public byte[] generatePasswordHash(String password)
        throws NoSuchAlgorithmException, UnsupportedEncodingException {
    if (password == null) {
        throw new UserCreationException(UserCreationExceptionEnum.PASSWORD_IS_BAD);
    }//from   w  ww . java  2  s  . co m
    MessageDigest digest = MessageDigest.getInstance("SHA-512");
    digest.reset();
    return digest.digest(password.getBytes("UTF-8"));
}

From source file:your.app.AuthenticationServlet.java

/**
 * Create JSFS token./*  w w w . java 2 s.  c o m*/
 * @param userName User name
 * @param remoteAddr Remote address
 * @return MD5 hash of user + address + secret
 */
private String createToken(String userName, String remoteAddr) {
    if (log.isDebugEnabled())
        log.debug("createToken(userName=" + userName + ", remoteAddr=" + remoteAddr);
    String token = null;
    if (userName != null && userName.length() != 0) {
        String plaintext = userName + "*" + remoteAddr + "*" + secret;

        try {
            MessageDigest m = MessageDigest.getInstance("MD5");
            m.reset();
            m.update(plaintext.getBytes());
            byte[] digest = m.digest();
            BigInteger bigInt = new BigInteger(1, digest);
            token = bigInt.toString(16);
        } catch (NoSuchAlgorithmException e) {
            log.error("Create token failed", e);
        }
    }
    if (log.isDebugEnabled())
        log.debug(")createToken=" + token);
    return token;
}

From source file:de.widone.services.UserService.java

public String encryptStringWithSalt(String password, String salt) {
    try {/*from  ww w.  j a  v a  2 s  .  co m*/
        MessageDigest digest = MessageDigest.getInstance("SHA-1");
        digest.reset();
        digest.update(decoder.decodeBuffer(salt));
        byte[] input = digest.digest(password.getBytes("UTF-8"));
        for (int count = 0; count < hashIterations; count++) {
            digest.reset();
            input = digest.digest(input);
        }
        return encoder.encode(input);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.cubeia.games.poker.CreateUser.java

private String getPassword() {
    if (hashPassword) {
        try {//  w  w w . ja v  a 2  s.  com
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.reset();
            md.update(password.getBytes("ISO-8859-1"));
            byte[] bytes = md.digest();
            return Hex.encodeHexString(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else {
        return password;
    }
}