【代码积累-4】cal MD5

来源:互联网 发布:种植牙 知乎 疼 编辑:程序博客网 时间:2024/05/02 11:33
import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;//import org.apache.commons.codec.binary.Hex;public class CalMD5_Test {public static void main(String[] args) {// TODO Auto-generated method stubString rawString = new String((System.currentTimeMillis()*1000)+":"+generateSipRand());        System.out.println(calMD5(rawString).toLowerCase());        System.out.println(calMD5_2(rawString).toLowerCase());}public static String calMD5(String input)    {        byte[] inputByteArray = input.getBytes();        byte[] outputByteArray = null;                try        {            /*��ȡһ��MD5ת��������*/            MessageDigest messageDigest = MessageDigest.getInstance("MD5");            inputByteArray = input.getBytes();                        messageDigest.update(inputByteArray);            outputByteArray = messageDigest.digest();                        /*���ֽ�����ת�����ַ������*/            return byteArrayToHexString(outputByteArray);        }        catch (NoSuchAlgorithmException e)         {              return null;         }     }public static String calMD5_2(String input)    {        byte[] inputByteArray = input.getBytes();        byte[] outputByteArray = null;                try        {            /*��ȡһ��MD5ת��������*/            MessageDigest messageDigest = MessageDigest.getInstance("MD5");            inputByteArray = input.getBytes();                        messageDigest.update(inputByteArray);            outputByteArray = messageDigest.digest();                        String temp = new String(outputByteArray);                        /*���ֽ�����ת�����ַ������*/            return temp;        }        catch (NoSuchAlgorithmException e)         {              return null;         }     }public static String byteArrayToHexString(byte[] byteArray)     {          // ���ȳ�ʼ��һ���ַ����飬�������ÿ��16�����ַ�          char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F' };                // newһ���ַ����飬�������������ɽ���ַ����ģ�����һ�£�һ��byte�ǰ�λ�����ƣ�Ҳ����2λʮ�������ַ���2��8�η�����16��2�η�����          char[] resultCharArray =new char[byteArray.length * 2];         // �����ֽ����飬ͨ��λ���㣨λ����Ч�ʸߣ���ת�����ַ��ŵ��ַ�������ȥ            int index = 0;            for (byte b : byteArray)         {              resultCharArray[index++] = hexDigits[b>>> 4 & 0xf];              resultCharArray[index++] = hexDigits[b& 0xf];          }                  // �ַ�������ϳ��ַ�������         return new String(resultCharArray);    }private static int generateSipRand()    {        int random = (int)(Math.random()*Integer.MAX_VALUE);                return random;    }}

原创粉丝点击