MD2,MD5算法,加密算法,算法加密,SHA-1,SHA-256,SHA-512,检查文件完整度

一个由老紫竹群dgqbcht的提供,还有一个由不想要昵称提供,感谢

MD5加密一

package test;

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

public class MD5 {

 public static void main(String[] args)
 {
  MD5 md5 = new MD5();
  System.out.println(md5.md5("heisetoufa"));
//  System.out.println(md5.md5("heisetoufa").length());
 }

 public String md5(String source) {
  String dest = null;
  try {
   MessageDigest md5 = MessageDigest.getInstance("MD5");
   char[] charArray = source.toCharArray();
   byte[] byteArray = new byte[charArray.length];
   for (int i = 0; i < charArray.length; i++)
    byteArray[i] = (byte) charArray[i];
   byte[] md5Bytes = md5.digest(byteArray);
   StringBuffer hexValue = new StringBuffer();
   for (int i = 0; i < md5Bytes.length; i++) {
    int val = ((int) md5Bytes[i]) & 0xff;
    if (val < 16)
     hexValue.append("0");
    hexValue.append(Integer.toHexString(val));
   }
   dest = hexValue.toString();

  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }
  return dest;
 }


}

 加密算法二,可自定义某种算法

package test;

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

public class MD {

 public static void main(String[] args) {
  MD md = new MD();
  System.out.println(md.encrypte("heisetoufa", "SHA-1"));// SHA-1算法
  System.out.println(md.encrypte("heisetoufa", "SHA-256"));// SHA-256算法
  System.out.println(md.encrypte("heisetoufa", "SHA-512"));// SHA-512算法
  
  System.out.println(MD.encrypte("heisetoufa", "MD2"));//MD2算法
  System.out.println(MD.encrypte("heisetoufa", "MD5"));//MD5算法
 }

 /**
  * encrypted password based on JCA algorithm of message digest
  * 
  * @param plainText
  *            orginal password text
  * @param algorithm
  *            name of algorithm
  * @return encrypted password
  */
 private static String encrypte(String plainText, String algorithm) {
  MessageDigest md = null;
  try {
   md = MessageDigest.getInstance(algorithm);
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }
  md.update(plainText.getBytes());
  byte[] b = md.digest();
  StringBuilder output = new StringBuilder(32);
  for (int i = 0; i < b.length; i++) {
   String temp = Integer.toHexString(b[i] & 0xff);
   if (temp.length() < 2) {
    output.append("0");
   }
   output.append(temp);
  }
  return output.toString();
 }
}

 

黑色头发  http://heisetoufa.iteye.com

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