java字符串加密

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class TestSHA {
 
 /**
  * 使用MD5算法加密
  * @param str
  * @param charset
  * @return
  * @throws Exception
  */
 public String encodeByMD5(String str,String charset) throws Exception {
  MessageDigest messageDigest = null;
  try {
   messageDigest = MessageDigest.getInstance("MD5");
   messageDigest.reset();
   messageDigest.update(str.getBytes(charset));
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
   throw new Exception("不能调用MD5加密算法。");
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
   throw new Exception("字符串不支持"+ charset +"的转换。");
  }
        return byteArrayToString(messageDigest.digest());
 }
 
 /**
  * 使用SHA算法加密
  * @param str
  * @param charset
  * @return
  * @throws Exception
  */
 public String encodeBySHA(String str,String charset) throws Exception {
  MessageDigest messageDigest = null;
  try {
   messageDigest = MessageDigest.getInstance("SHA");
   messageDigest.reset();
   messageDigest.update(str.getBytes(charset));

  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
   throw new Exception("不能调用指定的加密算法。");
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
   throw new Exception("字符串不支持"+ charset +"的转换。");
  }
  return byteArrayToString(messageDigest.digest());
 }

 /**
  * 将byte数组转化为16进制字符串
  * @param byteArray
  * @return
  */
 private String byteArrayToString(byte[] byteArray){
        StringBuilder strBuilder = new StringBuilder();  
        for (int i = 0; i < byteArray.length; i++) {  
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)  
             strBuilder.append("0").append(Integer.toHexString(0xFF & byteArray[i]));  
            else  
             strBuilder.append(Integer.toHexString(0xFF & byteArray[i]));  
        }
        return strBuilder.toString();
 }
 
 /**
  * 加密密码
  * @param password
  * @return
  * @throws Exception
  */
 public String getEencryptPassword(String password) throws Exception{
  String str = encodeByMD5(password,"utf-8");
  return encodeBySHA(str,"utf-8");
 }
 
 /**
  * 测试
  * @param args
  */
 public static void main(String[] args) {
  TestSHA testSHA = new TestSHA();
  try {
   System.out.println("MD5: " + testSHA.encodeByMD5("呵呵","utf-8"));
   System.out.println("SHA: " + testSHA.encodeBySHA("呵呵","utf-8"));
   System.out.println("MD5+SHA: " + testSHA.getEencryptPassword("呵呵"));
  } catch (Exception e) {
   e.printStackTrace();
  } 
 }
}

你可能感兴趣的:(java,算法,Security)