本文实例讲述了java实现sha算法的方法。分享给大家供大家参考,具体如下:
一 简介
安全散列算法
固定长度摘要信息
二 sha算法
sha-1、sha-2(sha-224、sha-256、sha384、sha-512)
三 sha算法实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
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算法应用
希望本文所述对大家java程序设计有所帮助。
原文链接:https://blog.csdn.net/chengqiuming/article/details/78760791