Package org.beangle.security.codec

Source Code of org.beangle.security.codec.EncryptUtil

/* Copyright c 2005-2012.
* Licensed under GNU  LESSER General Public License, Version 3.
* http://www.gnu.org/licenses
*/
package org.beangle.security.codec;

import java.security.MessageDigest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* 加密工具
*
* @author chaostone
*/
public class EncryptUtil {
  private final static Logger logger = LoggerFactory.getLogger(EncryptUtil.class);

  public static String encode(String password) {
    return encode(password, "MD5");
  }

  /**
   * Encode a string using algorithm specified in web.xml and return the
   * resulting encrypted password. If exception, the plain credentials string
   * is returned
   *
   * @param password
   *            Password or other credentials to use in authenticating this
   *            username
   * @param algorithm
   *            Algorithm used to do the digest
   * @return encypted password based on the algorithm.
   */
  public static String encode(String password, String algorithm) {
    byte[] unencodedPassword = password.getBytes();

    MessageDigest md = null;

    try {
      // first create an instance, given the provider
      md = MessageDigest.getInstance(algorithm);
    } catch (Exception e) {
      logger.error("Exception:{}", e);
      return password;
    }

    md.reset();

    // call the update method one or more times
    // (useful when you don't know the size of your data, eg. stream)
    md.update(unencodedPassword);

    // now calculate the hash
    byte[] encodedPassword = md.digest();

    StringBuilder buf = new StringBuilder();

    for (int i = 0; i < encodedPassword.length; i++) {
      if ((encodedPassword[i] & 0xff) < 0x10) {
        buf.append("0");
      }

      buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
    }

    return buf.toString();
  }
}
TOP

Related Classes of org.beangle.security.codec.EncryptUtil

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.