在应用程序中主要是为数据计算消息摘要与校验消息摘要,下面就看看在Java中是如何使用的,其入口类也称为引擎类为:java.security.MessageDigest但使用MAC算法时引擎类为:javax.crypto.Mac。
一、MD与SHA系列
public class DigestTest { @Test public void test() throws Exception { String myInfo = "我的测试信息"; //参数为消息摘要算法,在Java中默认支持的算法有:MD2、MD5、SHA-1、SHA-256、SHA-384、SHA-512 MessageDigest digest = MessageDigest.getInstance("SHA-1"); //更新待计算摘要的数据,该方法可以调用多次,例如一个文件很大,需要分多次更新 digest.update(myInfo.getBytes()); //得到摘要结果 byte[] result = digest.digest(); //摘要其实是一段二进制数据,但为了方便人们查看,一般会将其用16进制字符串表示 System.out.println("本信息摘要为:" + toHexString(result)); MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(myInfo.getBytes()); //isEqual方法用于判断两摘要值是否一致 if(MessageDigest.isEqual(result, md.digest())) { System.out.println("摘要检查正常"); } else { System.out.println("非法摘要"); } } // 二行制数据转为16进制字符串 public static String toHexString(byte[] data) { StringBuilder builder = new StringBuilder(); String stmp = ""; for (int n = 0; n < data.length; n++) { stmp = (java.lang.Integer.toHexString(data[n] & 0XFF)); if (stmp.length() == 1) { builder.append("0"); } builder.append(stmp); } return builder.toString().toUpperCase(); } @Test public void testDigestInputStream() throws Exception { MessageDigest digest = MessageDigest.getInstance("MD5"); String value = "xtayfjpk"; byte[] bytes = value.getBytes(); //还可以使用DigestInputStream来自动计算消息摘要,只要是从DigestInputStream流中读取的数据, //都会更新到MessageDigest中,相当于间接调用了MessageDigest的update方法 DigestInputStream stream = new DigestInputStream(new ByteArrayInputStream(bytes), digest); //一定要开启,默认为开启 stream.on(true); stream.read(bytes); byte[] result = stream.getMessageDigest().digest(); System.out.println(toHexString(result)); stream.close(); } @Test public void testDigestOutStream() throws Exception { MessageDigest digest = MessageDigest.getInstance("MD5"); String value = "xtayfjpk"; byte[] bytes = value.getBytes(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); //与DigestInputStream相似,只不过使用DigestOutputStream时是从其流出的数据都会更新到MessageDigest中 DigestOutputStream stream = new DigestOutputStream(baos, digest); //一定要开启,默认为开启 stream.on(true); stream.write(bytes); byte[] result = stream.getMessageDigest().digest(); System.out.println(SecurityUtils.toHexString(result)); stream.close(); } }
@Test public void testMac() throws Exception { String myInfo = "我的测试信息"; Mac digest = Mac.getInstance("HmacSHA512"); //获取密钥生成器,AES为密钥算法 KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); //用生成的密钥进行初始化 digest.init(keyGenerator.generateKey()); //更新待计算摘要数据 digest.update(myInfo.getBytes()); //得到摘要结果 byte[] result = digest.doFinal(); System.out.println("本信息摘要为:" + toHexString(result)); }
原文地址:http://blog.csdn.net/xtayfjpk/article/details/45914437