Java Digest digestString(String pass, String algorithm)

Here you can find the source of digestString(String pass, String algorithm)

Description

Calculate digest of given String using given algorithm.

License

Apache License

Parameter

Parameter Description
pass the String to be hashed
algorithm the algorithm to be used

Exception

Parameter Description
NoSuchAlgorithmException if the algorithm passed in cannot be found

Return

String Base-64 encoding of digest

Declaration

public static String digestString(String pass, String algorithm) throws NoSuchAlgorithmException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import javax.mail.MessagingException;
import javax.mail.internet.MimeUtility;
import java.io.ByteArrayOutputStream;

import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    /***//w w w. j  a  v a 2  s .com
     * Calculate digest of given String using given algorithm.
     * Encode digest in MIME-like base64.
     *
     * @param pass the String to be hashed
     * @param algorithm the algorithm to be used
     * @return String Base-64 encoding of digest
     *
     * @throws NoSuchAlgorithmException if the algorithm passed in cannot be found
     */
    public static String digestString(String pass, String algorithm) throws NoSuchAlgorithmException {

        MessageDigest md;
        ByteArrayOutputStream bos;

        try {
            md = MessageDigest.getInstance(algorithm);
            byte[] digest = md.digest(pass.getBytes("iso-8859-1"));
            bos = new ByteArrayOutputStream();
            OutputStream encodedStream = MimeUtility.encode(bos, "base64");
            encodedStream.write(digest);
            return bos.toString("iso-8859-1");
        } catch (IOException ioe) {
            throw new RuntimeException("Fatal error: " + ioe);
        } catch (MessagingException me) {
            throw new RuntimeException("Fatal error: " + me);
        }
    }
}

Related

  1. digestOperation(String algo, byte[]... content)
  2. digestStream(MessageDigest digest, InputStream is)
  3. digestString(MessageDigest md, String s)
  4. digestString(String input)
  5. digestString(String pass, String algorithm)
  6. digestThenEncodePasswordForLDAP(String algorithm, String credentials)
  7. digestWithSalt(String password, byte[] salt, String algorithm)