java加密体系-消息验证码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010739551/article/details/82983461

1、消息验证码算法实现支持

算法 摘要长度 备注
HmacMD5 128 BouncyCastle实现
HmacSHA1 160 BouncyCastle实现
HmacSHA256 256 BouncyCastle实现
HmacSHA384 384 BouncyCastle实现
HmacSHA512 512 JAVA6实现
HmacMD2 128 BouncyCastle实现
HmacMD4 128 BouncyCastle实现
HmacSHA224 224 BouncyCastle实现

 

2、使用HmacSHA256算法实现消息验证码

import java.security.Security;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;


/**
 * 消息验证码
 * @author luke
 */
public class HAMC {

	public static byte[] initHmacSHA256Key() throws Exception{
		Security.addProvider(new BouncyCastleProvider());
		KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacSHA256");
		SecretKey secretKey = keyGenerator.generateKey();
		return secretKey.getEncoded();
	}
	
	public static byte[] encodeHmacSHA256(byte[] data,byte[] key) throws Exception{
		Security.addProvider(new BouncyCastleProvider());
		SecretKey secretKey = new SecretKeySpec(key, "HmacSHA256");
		Mac mac = Mac.getInstance(secretKey.getAlgorithm());
		mac.init(secretKey);
		return mac.doFinal(data);
	}
	
	public static void main(String[] args) {
		try {
			//初始化密钥
			byte[] key=HAMC.initHmacSHA256Key();
			//通过密钥和消息获取消息验证码
			String str="999999999999999999999999999999999999999";//模拟发送的消息
			byte[] data=HAMC.encodeHmacSHA256(str.getBytes(), key);
			//消息验证码转16进制字符串
			String dataHex=new String(Hex.encode(data));
			System.out.println("发送的消息:"+str);//将消息和消息验证码发送出去
			System.out.println("发送验证码HEX:"+dataHex);		
			System.out.println("---------------------------------");
			String str2="999999999999999999999999999999999999999";//模拟接收到的消息
			byte[] data2=HAMC.encodeHmacSHA256(str2.getBytes(), key);
			String data2Hex=new String(Hex.encode(data2));
			System.out.println("接收到的消息:"+str2);//当消息被篡改,计算出的消息验证码将不一致
			System.out.println("计算出验证码HEX:"+data2Hex);		
			System.out.println("---------------------------------");
			System.out.println(dataHex.equals(data2Hex));//对比计算出的和接收到的是否一致,验证消息的完整性和认证性
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
}

3、测试结果

        发送的消息:999999999999999999999999999999999999999
        发送验证码HEX:f6628635b8fe53277ff5b9f003b88bbe35af38f5ee91d34440e9b655efa14f59
        ---------------------------------
       接收到的消息:999999999999999999999999999999999999999
       计算出验证码HEX:f6628635b8fe53277ff5b9f003b88bbe35af38f5ee91d34440e9b655efa14f59
       ---------------------------------
      true

阅读更多
换一批

没有更多推荐了,返回首页