本文实例讲述了Java实现SHA算法的方法。分享给大家供大家参考,具体如下:
一 简介
安全散列算法
固定长度摘要信息
二 SHA算法
SHA-1、SHA-2(SHA-224、SHA-256、SHA384、SHA-512)
三 SHA算法实现
package com.imooc.security.sha;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.digests.SHA224Digest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class ImoocSHA {
private static String src = "cakin24 security sha";
public static void main(String[] args) {
jdkSHA1();
bcSHA1();
bcSHA224();
ccSHA1();
}
public static void jdkSHA1() {
try {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(src.getBytes());
System.out.println("jdk sha-1 : " + Hex.encodeHexString(md.digest()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public static void bcSHA1() {
Digest digest = new SHA1Digest();
digest.update(src.getBytes(), 0, src.getBytes().length);
byte[] sha1Bytes = new byte[digest.getDigestSize()];
digest.doFinal(sha1Bytes, 0);
System.out.println("bc sha-1 : " + org.bouncycastle.util.encoders.Hex.toHexString(sha1Bytes));
}
public static void bcSHA224() {
Digest digest = new SHA224Digest();
digest.update(src.getBytes(), 0, src.getBytes().length);
byte[] sha224Bytes = new byte[digest.getDigestSize()];
digest.doFinal(sha224Bytes, 0);
System.out.println("bc sha-224 : " + org.bouncycastle.util.encoders.Hex.toHexString(sha224Bytes));
}
public static void ccSHA1() {
System.out.println("cc sha1 - 1 :" + DigestUtils.sha1Hex(src.getBytes()));
System.out.println("cc sha1 - 2 :" + DigestUtils.sha1Hex(src));
}
//384、256、512。。。。。。
}
四 运行结果
jdk sha-1 : ba28a0f5f08efc8afaee4706ffd496e1f88befdb
bc sha-1 : ba28a0f5f08efc8afaee4706ffd496e1f88befdb
bc sha-224 : ae3b58439cd53d28455781fe6dc20c83a45d63e1d9550330c7911f58
cc sha1 - 1 :ba28a0f5f08efc8afaee4706ffd496e1f88befdb
cc sha1 - 2 :ba28a0f5f08efc8afaee4706ffd496e1f88befdb
五 SHA算法应用
PS:关于加密解密感兴趣的朋友还可以参考本站在线工具:
在线MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具:http://tools.jb51.net/password/hash_md5_sha
希望本文所述对大家java程序设计有所帮助。