使用java.security.MessageDigest类来实现MD5、SHA加密

使用java.security.MessageDigest类来实现MD5、SHA加密,输出16进制格式加密结果,代码如下:

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class TestCheckSum{
	public static void main(String[] args){
		String myString=""+1+2;
		//Adler32 adler32 = new Adler32();
		try{
			byte[] bytesOfMessage = myString.getBytes("UTF-8");
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] thedigest = md.digest(bytesOfMessage);
			for(int i = 0;i < thedigest.length;i++){
				System.out.print(thedigest[i]+" ");//thedigest只是数组对象引用
			}
			System.out.println();
			
			StringBuffer sb=new StringBuffer();
			for(byte b:thedigest){
				sb.append(String.format("%02x", b & 0xff));
//Java的Byte都是有符号的(singed)整数,这里将byte数组元素和0xff相与主要是将其转为对应的无符号数,如-62补码11000010存储,扩展之后就是11111111 11000010和0xff扩展后的00000000 11111111相与得到相就的无符号数C2
			}
                            System.out.println("original:" +myString );
			System.out.println("digested(hex):" + sb.toString());//输出与python hashval=md5('12').hexdigest()中一样证明正确
			byte[] array = (sb.toString()).getBytes("UTF-8");//由String对象的getBytes()方法获得的byte数组,其元素为字符串中每个字符的ascii码
						
			for(int i=0;i

程序结果为

-62 10 -44 -41 111 -23 119 89 -86 39 -96 -55 -101 -1 103 16
original:12
digested(hex):c20ad4d76fe97759aa27a0c99bff6710  (16进制的加密结果)
99 50 48 97 100 52 100 55 54 102 101 57 55 55 53 57 97 97 50 55 97 48 99 57 57 98 102 102 54 55 49 48

你可能感兴趣的:(C/C++)