package test;
import java.security.*;
import org.apache.commons.codec.binary.Base64;
public class DigestExample {
private static String toHexString(byte[] buf) {
StringBuffer s = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
int n = buf[i] & 0xff;
s.append(" " + ((n < 16) ? "0" : "") + Integer.toHexString(n).toUpperCase());
}
return s.toString();
}
public static void main(String[] args) throws NoSuchAlgorithmException {
String src = "Hello, World-20040524";
byte[] srcb = src.getBytes();
MessageDigest sha = MessageDigest.getInstance("SHA");
MessageDigest md5 = MessageDigest.getInstance("MD5");
sha.update(srcb);
md5.update(srcb);
byte[] shab = sha.digest();
byte[] md5b = md5.digest();
System.out.println("SHA =" + toHexString(shab));
System.out.println("MD5 =" + toHexString(md5b));
String shad = new String(Base64.encodeBase64(shab));
String md5d = new String(Base64.encodeBase64(md5b));
System.out.println("SHA =" + shad);
System.out.println("MD5 =" + md5d);
byte[] shab2 = Base64.decodeBase64(shad.getBytes());
byte[] md5b2 = Base64.decodeBase64(md5d.getBytes());
System.out.println("SHA =" + toHexString(shab2));
System.out.println("MD5 =" + toHexString(md5b2));
}
}
|