简易的加密处理,支持MD5,SHA,SHA1等算法,不支持的算法会抛出NoSuchAlgorithmException异常
package secret;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SecurityTest {
public static void main(String[] args) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");// SHA SHA1
md.reset();
md.update("password".getBytes());
byte[] digest = md.digest();
System.out.println(parseHexStr(digest).toUpperCase());
}
/* generate an unique string contains 32/40 character */
private static String parseHexStr(byte[] digest) {
StringBuffer buffer = new StringBuffer(digest.length * 2);
for (byte b : digest) {
int v = b & 0xff;
if (v < 16)
buffer.append("0");
else
buffer.append(Integer.toHexString(v));
}
return buffer.toString();
}
}
测试加密字符"password",得到结果如下:
MD5 : 5F4DCC3B5AA765D61D8327DEB882CF99 (32位)
SHA : 5BAA61E4C9B93F3F0822506CF8331B7EE68FD8 (40位)
SHA1 : 5BAA61E4C9B93F3F0822506CF8331B7EE68FD8 (和SHA加密后一样)
可以使用在一些小应用中!