import java.security.MessageDigest;
import java.security.Security;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.MD2Digest;
import org.bouncycastle.crypto.digests.MD4Digest;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
public class MDDemo
{
public static void main(String[] args) throws Exception
{
System.out.println(jdkMD5("测试 test!"));
System.out.println(jdkMD2("测试 test!"));
System.out.println(jdkMD4("测试 test!"));
System.out.println(bcMD4("测试 test!"));
System.out.println(bcMD5("测试 test!"));
System.out.println(bcMD2("测试 test!"));
System.out.println(ccMD5("测试 test!"));
System.out.println(ccMD2("测试 test!"));
}
public static String jdkMD5(String srcString) throws Exception
{
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] encodeStr = md.digest(srcString.getBytes());
return Hex.toHexString(encodeStr);
}
public static String jdkMD2(String srcString) throws Exception
{
MessageDigest md = MessageDigest.getInstance("MD2");
byte[] encodeStr = md.digest(srcString.getBytes());
return Hex.toHexString(encodeStr);
}
public static String jdkMD4(String srcString) throws Exception
{
Security.addProvider(new BouncyCastleProvider());
MessageDigest md = MessageDigest.getInstance("MD4");
byte[] encodeStr = md.digest(srcString.getBytes());
return Hex.toHexString(encodeStr);
}
public static String bcMD4(String srcString) throws Exception
{
Digest digest = new MD4Digest();
digest.update(srcString.getBytes(),0,srcString.getBytes().length);
byte[] md4Bytes = new byte[digest.getDigestSize()];
digest.doFinal(md4Bytes, 0);
return Hex.toHexString(md4Bytes);
}
public static String bcMD5(String srcString) throws Exception
{
Digest digest = new MD5Digest();
digest.update(srcString.getBytes(),0,srcString.getBytes().length);
byte[] md5Bytes = new byte[digest.getDigestSize()];
digest.doFinal(md5Bytes, 0);
return Hex.toHexString(md5Bytes);
}
public static String bcMD2(String srcString) throws Exception
{
Digest digest = new MD2Digest();
digest.update(srcString.getBytes(),0,srcString.getBytes().length);
byte[] md2Bytes = new byte[digest.getDigestSize()];
digest.doFinal(md2Bytes, 0);
return Hex.toHexString(md2Bytes);
}
public static String ccMD5(String srcString) throws Exception
{
return DigestUtils.md5Hex(srcString);
}
public static String ccMD2(String srcString) throws Exception
{
return DigestUtils.md2Hex(srcString);
}
}
转载于:https://blog.51cto.com/881206524/1851393