MD5算法加密

来源:互联网 发布:xampp apache无法启动 编辑:程序博客网 时间:2024/04/30 02:37
package com.nml.roims.common;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * <p>Title: </p>
 * <p>Description: A password encryption helper.</p>
 *
 *  A cryptographically secure message digest takes arbitrary-sized input
 *  (a byte array), and generates a fixed-size output, called a digest or hash.
 *  A digest has two properties:
 *  - It should be computationally infeasible to find two messages that hashed
 *    to the same value.
 *  - The digest should not reveal anything about the input that was used to
 *    generate it.
 *  provided by "JavaTM Cryptography Architecture API Specification & Reference"
 * <p>Copyright:      Copyright (c) 2007</p>
 * <p>Company:        </p>
 * @author            nick  yu
 * @version           $Id: PasswordEncryptionHelper.java,v 1.2 2007/06/08 06:24:56 his_jack Exp $
 */

public class PasswordEncryptionHelper {
  public PasswordEncryptionHelper() {
  }

  public static String createHashCode(char[] passwordArr) throws
      NoSuchProviderException, NoSuchAlgorithmException {
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < passwordArr.length; i++) {
      buf.append(passwordArr[i]);
      passwordArr[i] = 0;
    }
    String encryptedPassword = createHashCode(buf.toString());
    for (int i = 0; i < passwordArr.length; i++) {
      buf.setCharAt(i, ' ');
    }
    return encryptedPassword;
  }

  public static String createHashCode(String password) throws
      NoSuchAlgorithmException, NoSuchProviderException {
    if (password != null) {
      if (!password.equals("")) {
        byte[] input = password.getBytes();
        byte[] digestedInput;
        StringBuffer buf = new StringBuffer();
        MessageDigest md = MessageDigest.getInstance("MD5", "SUN");
        digestedInput = md.digest(input);
        for (int i = 0; i < digestedInput.length; i++) {
          buf.append(Integer.toHexString(0x0100 + (digestedInput[i] & 0x00FF)).
                     substring(1));
//        buf.append(Integer.toHexString(digestedInput[i]));
        }
        return buf.toString();
      }
      else {
        // to work around the database constraint (NOT NULL)
        // there at least need to have a space.
        return " ";
      }
    }
    else { // password is null
      throw new NullPointerException("Password cannot be NULL.");
    }
  }

  public static void main(String[] args) {
    try {
      String text = args[0];
      String digest = createHashCode(text);
      System.out.println("Original Text: /"" + text + "/"");
      System.out.println("Digested Text: /"" + digest + "/"");
    }
    catch (Exception e) {
      e.printStackTrace();
      System.out.println("Usage: PasswordEncryptionHelper plain_text");
    }
  }

}