/**
* SHA-1和MD5示例程序 Java编写
*/
package com.koal.svs;
public class MYDigest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MYDigest mydigest=new MYDigest();
mydigest.testDigest();
}
public void testDigest()
{
try
{
String myinfo=”my test information!”;
java.security.MessageDigest alga=java.security.MessageDigest.getInstance(“SHA-1”);
alga.update(myinfo.getBytes());
byte[] digesta=alga.digest();
System.out.println(“本信息SHA-1摘要是:”+byte2hex(digesta));
java.security.MessageDigest algb=java.security.MessageDigest.getInstance(“MD5”);
algb.update(myinfo.getBytes());
byte[] digestb=algb.digest();
System.out.println(“本信息MD5摘要是: “+byte2hex(digestb));
if(algb.isEqual(digesta, algb.digest()))
{
System.out.println(“equal!”);
}
else
{
System.out.println(“failure”);
}
}
catch(java.security.NoSuchAlgorithmException ex)
{
System.out.println(ex.toString());
}
}
public String byte2hex(byte[] b)
{
String hs=””;
String stmp=””;
for(int n=0;n<b.length;n++)
{
stmp=(java.lang.Integer.toHexString(b[n] & 0XFF));
if(stmp.length()==1)
hs=hs+’0’+stmp;
else
hs=hs+stmp;
if(n<b.length-1)
hs=hs+’:’;
}
return hs.toUpperCase();
}
}
程序运行结果如下:
本信息SHA-1摘要是:DC:22:48:48:0E:6F:6B:90:A8:F0:D1:0E:66:D6:D4:63:EB:E2:FC:5A
本信息MD5摘要是: C9:AA:1A:FB:B9:DA:A6:CC:AD:7D:38:0A:48:F1:2E:B6
failure
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/6935.html