前段时间写过一篇文章。这年头啊。。MD5都靠不住了。。。,不过,我们可以按照自己的偏好,在md5的基础上再做点手脚。
首先,还是调用md5生成加密串。
String data="Test digest" MessageDigest md = MessageDigest.getInstance(ALGORITHM); byte[] dat = data.getBytes(); md.update(dat); byte[] digest = md.digest();
再看看我自己的算法:
StringBuffer buf = new StringBuffer(); for (int i = 0; i < digest.length; i++) { int d = digest<i>; if (d < 0) { d += 256; } if (d < 16) { buf.append(ZERO); } buf.append(Integer.toString(d, 16)); } String retStr = buf.toString();
整合起来就是:
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Digest { private static final String ALGORITHM = "MD5"; private static final String ZERO = "0"; private String makeStringDigest(byte[] digest) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < digest.length; i++) { int d = digest<i>; if (d < 0) { d += 256; } if (d < 16) { buf.append(ZERO); } buf.append(Integer.toString(d, 16)); } String retStr = buf.toString(); return retStr; } public String getStringDigest(String data) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance(ALGORITHM); byte[] dat = data.getBytes(); md.update(dat); return this.makeStringDigest(md.digest()); } }