nov1
发贴: 0
积分: 0
|
于 2003-07-13 06:02
import java.security.*;
public class MMM { static private MessageDigest msgDigest; // if an algorithm does not exist, let caller to handle the NoSuchAlgorithmException // because this class has no knowledge about how to handle it public MMM(String alg) throws NoSuchAlgorithmException { msgDigest = MessageDigest.getInstance(alg); } // or you can catch it if you believe it will never happen public MMM() { try { msgDigest = MessageDigest.getInstance("MD5"); } catch(NoSuchAlgorithmException e) {} } public String calcHexDigest(String msg) { return bytes2hex(msgDigest.digest(msg.getBytes())); } public String bytes2hex(byte[] bytes) { StringBuffer buf = new StringBuffer(bytes.length * 2); for(int pos = 0; pos < bytes.length; pos++) { int n = bytes[pos] & 0xFF; buf.append(halfByte2hex((n >> 4) & 0xF)); buf.append(halfByte2hex(n & 0xF)); } return buf.toString(); } public char halfByte2hex(int n) // ensure: 0 <= n <= 15 { return (char)(n > 9 ? 'A' + n - 10 : '0' + n); } }
|