报文MAC算法java实现

/**
 * 
 */
package net.etongbao.common.utils;

import java.util.Arrays;

/**
 * Mac工具类,采用ECB算法
 * 
 * @author Fu Wei
 * 
 */
public class MacEcbUtils {
	public static byte[] IV = new byte[8];

	public static byte byteXOR(byte src, byte src1) {
		return (byte) ((src & 0xFF) ^ (src1 & 0xFF));
	}

	public static byte[] bytesXOR(byte[] src, byte[] src1) {
		int length = src.length;
		if (length != src1.length) {
			return null;
		}
		byte[] result = new byte[length];
		for (int i = 0; i < length; i++) {
			result[i] = byteXOR(src[i], src1[i]);
		}
		return result;
	}

	/**
	 * mac计算,数据不为8的倍数,需要补0,将数据8个字节进行异或,再将异或的结果与下一个8个字节异或,一直到最后,将异或后的数据进行DES计算
	 * 
	 * @param key
	 * @param Input
	 * @return
	 */
	public static byte[] clacMac(byte[] key, byte[] Input) {
		int length = Input.length;
		int x = length % 8;
		int addLen = 0;
		if (x != 0) {
			addLen = 8 - length % 8;
		}
		int pos = 0;
		byte[] data = new byte[length + addLen];
		System.arraycopy(Input, 0, data, 0, length);
		byte[] oper1 = new byte[8];
		System.arraycopy(data, pos, oper1, 0, 8);
		pos += 8;
		for (int i = 1; i < data.length / 8; i++) {
			byte[] oper2 = new byte[8];
			System.arraycopy(data, pos, oper2, 0, 8);
			byte[] t = bytesXOR(oper1, oper2);
			oper1 = t;
			pos += 8;
		}
		byte[] buff = DesUtils.encrypt(oper1, key);
		// 取8个长度字节
		byte[] retBuf = new byte[8];
		System.arraycopy(buff, 0, retBuf, 0, 8);
		return retBuf;
	}

	public static void main(String[] args) {
		byte[] buff = { 2, 1, 32, 32, 0, 0, 0, -64, -128, 25, 0, 0, 0, 0, 0, 86, 48, 49, 48, 52, 55, 51, 50, 53, 49,
		        48, 52, 49, 49, 48, 49, 53, 52, 49, 49, 52, 54, 54, 48, 67, 78, 89, 0, 6, 48, 49, 49, 48, 48, 48, 0,
		        68, 48, 48, 48, 48, 48, 49, 48, 56, 48, 48, 48, 49, 103, 80, 102, 53, 90, 72, 119, 67, 101, 105, 52,
		        61, 67, 90, 83, 83, 48, 48, 49, 53, 17, 49, 51, 49, 51, 49, 51, 49, 51, 49, 51, 49 };
		System.out.println(Arrays.toString(clacMac("b69e6b76".getBytes(), buff)));
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值