Example usage for java.security MessageDigest getInstance

List of usage examples for java.security MessageDigest getInstance

Introduction

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

Prototype

public static MessageDigest getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a MessageDigest object that implements the specified digest algorithm.

Usage

From source file:com.l2jfree.loginserver.tools.L2AccountManager.java

/**
 * Launches the interactive account manager.
 * //from www  . j  a  va2s  . c om
 * @param args ignored
 */
public static void main(String[] args) {
    // LOW rework this crap
    Util.printSection("Account Management");

    _log.info("Please choose:");
    //_log.info("list - list registered accounts");
    _log.info("reg - register a new account");
    _log.info("rem - remove a registered account");
    _log.info("prom - promote a registered account");
    _log.info("dem - demote a registered account");
    _log.info("ban - ban a registered account");
    _log.info("unban - unban a registered account");
    _log.info("quit - exit this application");

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    L2AccountManager acm = new L2AccountManager();

    String line;
    try {
        while ((line = br.readLine()) != null) {
            line = line.trim();
            Connection con = null;
            switch (acm.getState()) {
            case USER_NAME:
                line = line.toLowerCase();
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("SELECT superuser FROM account WHERE username LIKE ?");
                    ps.setString(1, line);
                    ResultSet rs = ps.executeQuery();
                    if (!rs.next()) {
                        acm.setUser(line);

                        _log.info("Desired password:");
                        acm.setState(ManagerState.PASSWORD);
                    } else {
                        _log.info("User name already in use.");
                        acm.setState(ManagerState.INITIAL_CHOICE);
                    }
                    rs.close();
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not access database!", e);
                    acm.setState(ManagerState.INITIAL_CHOICE);
                } finally {
                    L2Database.close(con);
                }
                break;
            case PASSWORD:
                try {
                    MessageDigest sha = MessageDigest.getInstance("SHA");
                    byte[] pass = sha.digest(line.getBytes("US-ASCII"));
                    acm.setPass(HexUtil.bytesToHexString(pass));
                } catch (NoSuchAlgorithmException e) {
                    _log.fatal("SHA1 is not available!", e);
                    Shutdown.exit(TerminationStatus.ENVIRONMENT_MISSING_COMPONENT_OR_SERVICE);
                } catch (UnsupportedEncodingException e) {
                    _log.fatal("ASCII is not available!", e);
                    Shutdown.exit(TerminationStatus.ENVIRONMENT_MISSING_COMPONENT_OR_SERVICE);
                }
                _log.info("Super user: [y/n]");
                acm.setState(ManagerState.SUPERUSER);
                break;
            case SUPERUSER:
                try {
                    if (line.length() != 1)
                        throw new IllegalArgumentException("One char required.");
                    else if (line.charAt(0) == 'y')
                        acm.setSuper(true);
                    else if (line.charAt(0) == 'n')
                        acm.setSuper(false);
                    else
                        throw new IllegalArgumentException("Invalid choice.");

                    _log.info("Date of birth: [yyyy-mm-dd]");
                    acm.setState(ManagerState.DOB);
                } catch (IllegalArgumentException e) {
                    _log.info("[y/n]?");
                }
                break;
            case DOB:
                try {
                    Date d = Date.valueOf(line);
                    if (d.after(new Date(System.currentTimeMillis())))
                        throw new IllegalArgumentException("Future date specified.");
                    acm.setDob(d);

                    _log.info("Ban reason ID or nothing:");
                    acm.setState(ManagerState.SUSPENDED);
                } catch (IllegalArgumentException e) {
                    _log.info("[yyyy-mm-dd] in the past:");
                }
                break;
            case SUSPENDED:
                try {
                    if (line.length() > 0) {
                        int id = Integer.parseInt(line);
                        acm.setBan(L2BanReason.getById(id));
                    } else
                        acm.setBan(null);

                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement(
                                "INSERT INTO account (username, password, superuser, birthDate, banReason) VALUES (?, ?, ?, ?, ?)");
                        ps.setString(1, acm.getUser());
                        ps.setString(2, acm.getPass());
                        ps.setBoolean(3, acm.isSuper());
                        ps.setDate(4, acm.getDob());
                        L2BanReason lbr = acm.getBan();
                        if (lbr == null)
                            ps.setNull(5, Types.INTEGER);
                        else
                            ps.setInt(5, lbr.getId());
                        ps.executeUpdate();
                        _log.info("Account " + acm.getUser() + " has been registered.");
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not register an account!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    acm.setState(ManagerState.INITIAL_CHOICE);
                } catch (NumberFormatException e) {
                    _log.info("Ban reason ID or nothing:");
                }
                break;
            case REMOVE:
                acm.setUser(line.toLowerCase());
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con.prepareStatement("DELETE FROM account WHERE username LIKE ?");
                    ps.setString(1, acm.getUser());
                    int cnt = ps.executeUpdate();
                    if (cnt > 0)
                        _log.info("Account " + acm.getUser() + " has been removed.");
                    else
                        _log.info("Account " + acm.getUser() + " does not exist!");
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not remove an account!", e);
                } finally {
                    L2Database.close(con);
                }
                acm.setState(ManagerState.INITIAL_CHOICE);
                break;
            case PROMOTE:
                acm.setUser(line.toLowerCase());
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("UPDATE account SET superuser = ? WHERE username LIKE ?");
                    ps.setBoolean(1, true);
                    ps.setString(2, acm.getUser());
                    int cnt = ps.executeUpdate();
                    if (cnt > 0)
                        _log.info("Account " + acm.getUser() + " has been promoted.");
                    else
                        _log.info("Account " + acm.getUser() + " does not exist!");
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not promote an account!", e);
                } finally {
                    L2Database.close(con);
                }
                acm.setState(ManagerState.INITIAL_CHOICE);
                break;
            case DEMOTE:
                acm.setUser(line.toLowerCase());
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("UPDATE account SET superuser = ? WHERE username LIKE ?");
                    ps.setBoolean(1, false);
                    ps.setString(2, acm.getUser());
                    int cnt = ps.executeUpdate();
                    if (cnt > 0)
                        _log.info("Account " + acm.getUser() + " has been demoted.");
                    else
                        _log.info("Account " + acm.getUser() + " does not exist!");
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not demote an account!", e);
                } finally {
                    L2Database.close(con);
                }
                acm.setState(ManagerState.INITIAL_CHOICE);
                break;
            case UNBAN:
                acm.setUser(line.toLowerCase());
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("UPDATE account SET banReason = ? WHERE username LIKE ?");
                    ps.setNull(1, Types.INTEGER);
                    ps.setString(2, acm.getUser());
                    int cnt = ps.executeUpdate();
                    if (cnt > 0)
                        _log.info("Account " + acm.getUser() + " has been unbanned.");
                    else
                        _log.info("Account " + acm.getUser() + " does not exist!");
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not demote an account!", e);
                } finally {
                    L2Database.close(con);
                }
                acm.setState(ManagerState.INITIAL_CHOICE);
                break;
            case BAN:
                line = line.toLowerCase();
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("SELECT superuser FROM account WHERE username LIKE ?");
                    ps.setString(1, line);
                    ResultSet rs = ps.executeQuery();
                    if (rs.next()) {
                        acm.setUser(line);

                        _log.info("Ban reason ID:");
                        acm.setState(ManagerState.REASON);
                    } else {
                        _log.info("Account does not exist.");
                        acm.setState(ManagerState.INITIAL_CHOICE);
                    }
                    rs.close();
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not access database!", e);
                    acm.setState(ManagerState.INITIAL_CHOICE);
                } finally {
                    L2Database.close(con);
                }
                break;
            case REASON:
                try {
                    int ban = Integer.parseInt(line);
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("UPDATE account SET banReason = ? WHERE username LIKE ?");
                    ps.setInt(1, ban);
                    ps.setString(2, acm.getUser());
                    ps.executeUpdate();
                    _log.info("Account " + acm.getUser() + " has been banned.");
                    ps.close();
                } catch (NumberFormatException e) {
                    _log.info("Ban reason ID:");
                } catch (SQLException e) {
                    _log.error("Could not ban an account!", e);
                } finally {
                    L2Database.close(con);
                }
                acm.setState(ManagerState.INITIAL_CHOICE);
                break;
            default:
                line = line.toLowerCase();
                if (line.equals("reg")) {
                    _log.info("Desired user name:");
                    acm.setState(ManagerState.USER_NAME);
                } else if (line.equals("rem")) {
                    _log.info("User name:");
                    acm.setState(ManagerState.REMOVE);
                } else if (line.equals("prom")) {
                    _log.info("User name:");
                    acm.setState(ManagerState.PROMOTE);
                } else if (line.equals("dem")) {
                    _log.info("User name:");
                    acm.setState(ManagerState.DEMOTE);
                } else if (line.equals("unban")) {
                    _log.info("User name:");
                    acm.setState(ManagerState.UNBAN);
                } else if (line.equals("ban")) {
                    _log.info("User name:");
                    acm.setState(ManagerState.BAN);
                } else if (line.equals("quit"))
                    Shutdown.exit(TerminationStatus.MANUAL_SHUTDOWN);
                else
                    _log.info("Incorrect command.");
                break;
            }
        }
    } catch (IOException e) {
        _log.fatal("Could not process input!", e);
    } finally {
        IOUtils.closeQuietly(br);
    }
}

From source file:ch.bfh.evoting.verifier.Verifier.java

/**
 * This program is a verifier for MobiVote application with HKRS12 protocol
 * You have to indicate the XML file exported from the application as argument for this program.
 * You can also indicate the files of different participants. In this case, there will be checked if all files contain the same values.
 * @param args the file(s) containing the values of the protocol
 *///from  ww  w.  j a v  a  2 s .co  m
public static void main(String[] args) {

    /*
     * Reading files given as parameters
     */
    if (args.length < 1) {
        //Not enough arguments
        System.out.println(
                "You must indicate the location of the XML file containing the data to verify! You can also indicate the files of different participants.");
        return;
    } else if (args.length > 1) {
        //Make a digest of all files and compare them
        List<byte[]> digests = new ArrayList<byte[]>();
        for (String s : args) {
            try {
                MessageDigest md = MessageDigest.getInstance("SHA-256");

                InputStream is = Files.newInputStream(Paths.get(s));
                DigestInputStream dis = new DigestInputStream(is, md);
                @SuppressWarnings("unused")
                int numBytes = -1;
                while ((numBytes = dis.read()) != -1) {
                    dis.read();
                }

                byte[] digest = md.digest();
                digests.add(digest);

            } catch (IOException e) {
                System.out.println("One of the given files does not exists!");
                return;
            } catch (NoSuchAlgorithmException e1) {
                System.out.println("Unable to compute the digest of the file!");
                return;
            }
        }
        System.out.print("Checking the similarity of the files...");
        for (byte[] b : digests) {
            for (byte[] b2 : digests) {
                if (!Arrays.equals(b, b2)) {
                    System.out.print("\t\t\t\t\t\t\t\t\t\tWRONG\n");
                    System.out.println(
                            "The given files are not all identical! This means the content received by the participants was not the same.");
                    return;
                }
            }
        }
        System.out.print("\t\t\t\t\t\t\t\t\t\tOK\n\n");
    } else if (args.length == 1) {
        //Print a warning
        System.out.println(
                "BE CAREFUL: checking only one file ensure that the cryptographic values of the protocol are correct.\n"
                        + "But, it does NOT ensure that all users have the same result. This could happen when a participant missed some messages.\n"
                        + "This case is only covered by this verifier by giving multiple files as argument.\n");
    }

    Serializer serializer = new Persister();
    File source = new File(args[0]);

    poll = null;
    System.out.print("Reading file...");
    try {
        poll = serializer.read(XMLPoll.class, source);
        System.out.print("\t\t\t\t\t\t\t\t\t\t\t\t\tOK\n");
    } catch (Exception e) {
        System.out.print("\t\t\t\t\t\t\t\t\t\t\t\t\tFAILED\n");
        e.printStackTrace();
        return;
    }

    /*
     * Create the initializations needed by the protocol
     */
    G_q = GStarModSafePrime.getInstance(new BigInteger(poll.getP()));
    Z_q = G_q.getZModOrder();
    Zgroup = Z.getInstance();
    generator = poll.getGenerator().getValue(G_q);

    representations = new Element[poll.getOptions().size()];
    int i = 0;
    for (XMLOption op : poll.getOptions()) {
        representations[i] = op.getRepresentation().getValue(Z_q);
        i++;
    }

    System.out.println();
    System.out.println("Verifying vote: \"" + poll.getQuestion() + "\"");

    /*
     * Verify the dependence between cryptographic values and the vote properties
     */
    //Not used anymore, implicitly done with otherInputs of proofs
    //verifyDependencyTextCrypto();

    /*
     * Verify the proofs for the user
     */
    System.out.println();
    System.out.println("Verifying the proof for the participants...");
    a = new Element[poll.getParticipants().size()];
    b = new Element[poll.getParticipants().size()];
    h = new Element[poll.getParticipants().size()];
    hHat = new Element[poll.getParticipants().size()];
    hHatPowX = new Element[poll.getParticipants().size()];
    proofForX = new Element[poll.getParticipants().size()];
    validityProof = new Element[poll.getParticipants().size()];
    equalityProof = new Element[poll.getParticipants().size()];
    Tuple pollTuple = preparePollOtherInput(poll, representations, generator);

    int k = 0;
    for (XMLParticipant p : poll.getParticipants()) {
        System.out.println("\tParticipant " + p.getIdentification() + " (" + p.getUniqueId() + ")");

        if (p.getAi() != null) {
            a[k] = p.getAi().getValue(G_q);
            if (DEBUG)
                System.out.println("Value a: " + a[k]);
        }
        if (p.getHi() != null) {
            h[k] = p.getHi().getValue(G_q);
            if (DEBUG)
                System.out.println("Value h: " + h[k]);
        }
        if (p.getBi() != null) {
            b[k] = p.getBi().getValue(G_q);
            if (DEBUG)
                System.out.println("Value b: " + b[k]);
        }
        if (p.getHiHat() != null) {
            hHat[k] = p.getHiHat().getValue(G_q);
            if (DEBUG)
                System.out.println("Value h hat: " + hHat[k]);
        }
        if (p.getHiHatPowXi() != null) {
            hHatPowX[k] = p.getHiHatPowXi().getValue(G_q);
            if (DEBUG)
                System.out.println("Value h hat ^ x: " + hHatPowX[k]);
        }

        if (p.getProofForXi() != null) {
            ProductGroup group = ProductGroup.getInstance(G_q, Zgroup, Z_q);

            proofForX[k] = p.getProofForXi().getValue(group);
        }

        if (p.getProofValidVote() != null) {

            Group[] tripleElement1Groups = new Group[poll.getOptions().size()];
            Group[] tripleElement2Groups = new Group[poll.getOptions().size()];
            Group[] tripleElement3Groups = new Group[poll.getOptions().size()];
            for (i = 0; i < poll.getOptions().size(); i++) {
                tripleElement1Groups[i] = ProductGroup.getInstance(G_q, G_q);
                tripleElement2Groups[i] = Zgroup;
                tripleElement3Groups[i] = Z_q;
            }
            ProductGroup tripleElement1 = ProductGroup.getInstance(tripleElement1Groups);
            ProductGroup tripleElement2 = ProductGroup.getInstance(tripleElement2Groups);
            ProductGroup tripleElement3 = ProductGroup.getInstance(tripleElement3Groups);
            ProductGroup group = ProductGroup.getInstance(tripleElement1, tripleElement2, tripleElement3);

            validityProof[k] = p.getProofValidVote().getValue(group);

            if (DEBUG)
                System.out.println("Proof of validity: " + validityProof[k]);
        }

        if (p.getProofForHiHat() != null) {
            recoveryNeeded = true;
            ProductGroup group = ProductGroup.getInstance(ProductGroup.getInstance(G_q, G_q), Zgroup, Z_q);

            equalityProof[k] = p.getProofForHiHat().getValue(group);
        }

        Tuple participantTuple = prepareParticipantOtherInput(p);
        otherInput = Tuple.getInstance(participantTuple, pollTuple);

        /*
         * Verify proof of knowledge 
         */
        System.out.print("\t\tVerifying proof of knowledge of x value...");
        verifyProofOfKnowledgeOfX(k);

        /*
         * Verify proof of validity 
         */
        if (validityProof[k] != null) {
            System.out.print("\t\tVerifying proof of valid vote...");
            verifyValidityProof(k);
        }

        /*
         * Verify proof of equality 
         */
        if (equalityProof[k] != null) {
            System.out.print("\t\tVerifying proof of equality between discrete logarithm g^x and h_hat^x...");
            verifyEqualityProof(k);
        }
        k++;
    }

    /**
     * Computing the result
     */
    System.out.println();
    System.out.print("Computing the result...");
    computeResult();

}

From source file:MD5.java

public static void main(String[] args) {

    //String password = args[0];
    String password = "test";

    MessageDigest digest = null;//from   ww w  . j a  v a  2 s . c om

    try {
        digest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    try {
        digest.update(password.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    }

    byte[] rawData = digest.digest();
    StringBuffer printable = new StringBuffer();

    for (int i = 0; i < rawData.length; i++) {
        printable.append(carr[((rawData[i] & 0xF0) >> 4)]);
        printable.append(carr[(rawData[i] & 0x0F)]);
    }
    String phpbbPassword = printable.toString();

    System.out.println("PHPBB           : " + phpbbPassword);
    System.out.println("MVNFORUM        : " + getMD5_Base64(password));
    System.out.println("PHPBB->MVNFORUM : " + getBase64FromHEX(phpbbPassword));
}

From source file:net.sf.jsignpdf.InstallCert.java

/**
 * The main - whole logic of Install Cert Tool.
 * /*w  w  w  . j a v a2s .  c o m*/
 * @param args
 * @throws Exception
 */
public static void main(String[] args) {
    String host;
    int port;
    char[] passphrase;

    System.out.println("InstallCert - Install CA certificate to Java Keystore");
    System.out.println("=====================================================");

    final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    try {
        if ((args.length == 1) || (args.length == 2)) {
            String[] c = args[0].split(":");
            host = c[0];
            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
            String p = (args.length == 1) ? "changeit" : args[1];
            passphrase = p.toCharArray();
        } else {
            String tmpStr;
            do {
                System.out.print("Enter hostname or IP address: ");
                tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null);
            } while (tmpStr == null);
            host = tmpStr;
            System.out.print("Enter port number [443]: ");
            tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null);
            port = tmpStr == null ? 443 : Integer.parseInt(tmpStr);
            System.out.print("Enter keystore password [changeit]: ");
            tmpStr = reader.readLine();
            String p = "".equals(tmpStr) ? "changeit" : tmpStr;
            passphrase = p.toCharArray();
        }

        char SEP = File.separatorChar;
        final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
        final File file = new File(dir, "cacerts");

        System.out.println("Loading KeyStore " + file + "...");
        InputStream in = new FileInputStream(file);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, passphrase);
        in.close();

        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory factory = context.getSocketFactory();

        System.out.println("Opening connection to " + host + ":" + port + "...");
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            System.out.println("Starting SSL handshake...");
            socket.startHandshake();
            socket.close();
            System.out.println();
            System.out.println("No errors, certificate is already trusted");
        } catch (SSLException e) {
            System.out.println();
            System.out.println("Certificate is not yet trusted.");
            //        e.printStackTrace(System.out);
        }

        X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.out.println("Could not obtain server certificate chain");
            return;
        }

        System.out.println();
        System.out.println("Server sent " + chain.length + " certificate(s):");
        System.out.println();
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        for (int i = 0; i < chain.length; i++) {
            X509Certificate cert = chain[i];
            System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN());
            System.out.println("   Issuer  " + cert.getIssuerDN());
            sha1.update(cert.getEncoded());
            System.out.println("   sha1    " + toHexString(sha1.digest()));
            md5.update(cert.getEncoded());
            System.out.println("   md5     " + toHexString(md5.digest()));
            System.out.println();
        }

        System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: ");
        String line = reader.readLine().trim();
        int k = -1;
        try {
            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
        } catch (NumberFormatException e) {
        }

        if (k < 0 || k >= chain.length) {
            System.out.println("KeyStore not changed");
        } else {
            try {
                System.out.println("Creating keystore backup");
                final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                final File backupFile = new File(dir,
                        CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date()));
                final FileInputStream fis = new FileInputStream(file);
                final FileOutputStream fos = new FileOutputStream(backupFile);
                IOUtils.copy(fis, fos);
                fis.close();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Installing certificate...");

            X509Certificate cert = chain[k];
            String alias = host + "-" + (k + 1);
            ks.setCertificateEntry(alias, cert);

            OutputStream out = new FileOutputStream(file);
            ks.store(out, passphrase);
            out.close();

            System.out.println();
            System.out.println(cert);
            System.out.println();
            System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'");
        }
    } catch (Exception e) {
        System.out.println();
        System.out.println("----------------------------------------------");
        System.out.println("Problem occured during installing certificate:");
        e.printStackTrace();
        System.out.println("----------------------------------------------");
    }
    System.out.println("Press Enter to finish...");
    try {
        reader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static byte[] md5Byte(String encryptStr) throws Exception {
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(encryptStr.getBytes("UTF-8"));
    return md.digest();
}

From source file:Main.java

public static String md5(String str) throws Exception {
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(str.getBytes());//from w ww  . j  a  va  2  s .  c o m

    byte byteData[] = md.digest();

    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < byteData.length; i++) {
        sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
    }

    return sb.toString();
}

From source file:Main.java

public static String generateMd5Hash(String str) {
    try {//from   w ww.j  a  va 2  s .c om
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(str.getBytes("UTF8"));
        byte s[] = m.digest();
        String result = "";
        for (int i = 0; i < s.length; i++) {
            result += Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6);
        }
        return result;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static String md5(String str) {
    try {/*from   ww w .ja  va2 s  .  c o m*/
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes());

        byte[] b = md.digest();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            int v = (int) b[i];
            v = v < 0 ? 0x100 + v : v;
            String cc = Integer.toHexString(v);
            if (cc.length() == 1)
                sb.append('0');
            sb.append(cc);
        }

        return sb.toString();
    } catch (Exception e) {
    }
    return "";
}

From source file:Main.java

public static byte[] md5Digest(byte[] password) throws Exception {
    try {//  w w  w . j  av a 2  s  .com
        MessageDigest alg = MessageDigest.getInstance("MD5");
        alg.update(password);
        byte[] digest = alg.digest();
        return digest;
    } catch (Exception e) {
        throw new Exception(e);
    }
}

From source file:Main.java

static public String digest(String input) {
    try {/*w  w  w  . ja  v  a  2  s.  c  o  m*/
        MessageDigest md = MessageDigest.getInstance("MD5");
        return new BigInteger(1, md.digest(input.getBytes())).toString(16).toUpperCase();
    } catch (Exception e) {
        return null;
    }
}