?? digest.java
字號:
package com.iplan.portal.framework.utils;
import java.security.MessageDigest;
/**
* 常用的MD5和SHA-1
* MD5是麻省理工大學推出的,而SHA-1是美國技術協會標準
*
* 簡單的單項散列函數消息處理。
* <p>
* http://www.hao-se.cn
* </p>
*
* @author ws
*/
public class Digest {
/**
* 信息顯示
*
* 二行制轉字符串
*
* param b return
*
*/
private static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
if (n < b.length - 1)
hs = hs + ":";
}
return hs.toUpperCase();
}
/**
*
* 用MD5校驗信息是否更改.
*
* @param myInfo
* @param digestInfo
* @return
*/
public static boolean checkMD5Digest(String myInfo, String digestInfo) {
if (myInfo == null || digestInfo == null)
return false;
try {
MessageDigest alga = MessageDigest.getInstance("MD5");
alga.update(myInfo.getBytes());
byte[] digesta = alga.digest();
return digestInfo.equals(byte2hex(digesta));
} catch (java.security.NoSuchAlgorithmException ex) {
System.out.println("非法摘要算法");
throw new RuntimeException();
}
}
// /**
// *
// * 用SHA-1校驗信息是否更改.
// *
// * @param myInfo
// * @param digestInfo
// * @return
// */
// public static boolean checkSHA1Digest(String myInfo, String digestInfo) {
//
// if (myInfo == null || digestInfo == null)
// return false;
//
// try {
// MessageDigest alga = MessageDigest.getInstance("SHA-1");
//
// alga.update(myInfo.getBytes());
//
// byte[] digesta = alga.digest();
//
// return digestInfo.equals(byte2hex(digesta));
//
// } catch (java.security.NoSuchAlgorithmException ex) {
// System.out.println("非法摘要算法");
// throw new RuntimeException();
// }
// }
/**
*
* 根據字符信息用MD5加密,返回
*
* @param myInfo
* @return
* @throws Exception
*/
public static String getMD5Digest(String myInfo) throws Exception {
if (myInfo == null)
return "";
try {
MessageDigest alg = MessageDigest.getInstance("MD5");
alg.update(myInfo.getBytes());
byte[] digesta = alg.digest();
return byte2hex(digesta);
} catch (java.security.NoSuchAlgorithmException ex) {
System.out.println("非法摘要算法");
throw new RuntimeException();
}
}
// /**
// *
// * 根據字符信息用SHA-1加密,返回
// *
// * @param myInfo
// * @return
// */
//
// if (myInfo == null)
// return "";
//
// try {
// MessageDigest alg = MessageDigest.getInstance("SHA-1");
//
// alg.update(myInfo.getBytes());
//
// byte[] digesta = alg.digest();
//
// return byte2hex(digesta);
//
// } catch (java.security.NoSuchAlgorithmException ex) {
// System.out.println("非法摘要算法");
// throw new RuntimeException();
// }
// }
public static void main(String args[]) throws Exception {
String a = Digest.getMD5Digest("xy419");
System.out.println(a);
System.out.println(a.length());
System.out.println(Digest.checkMD5Digest("aaaa", a));
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -