62,614
社区成员
发帖
与我相关
我的任务
分享
public class AnsiiX99MAC {
static{
Security.addProvider(new BouncyCastleProvider());
}
public static void main(String[] args) {
//zak(mackey)
byte[] MACKEY = ConvertUtil.strToBcd("8F37EADF07CB5232");
//待计算数据
byte[] data = ConvertUtil.stringToBytes("0200702004C000C010532000008600898000005018600000000000000100000047021F9106323330303030303133303130303230303030303036313000000000000000000047525108980001FFFFFFFF00008600898000005018741ECF4A010000010001863C00000064020000000000017132B6B800114000000800000003303030","iso8859-1");
//进行分组
int group = (data.length + (8 - 1)) / 8;
//偏移量
int offset = 0 ;
//输入计算数据
byte[] edata = null;
for(int i = 0 ; i < group; i++){
byte[] temp = new byte[8];
if(i != group - 1){
System.arraycopy(data, offset, temp, 0, 8);
offset += 8;
}else{//只有最后一组数据才进行填充0x00
System.arraycopy(data, offset, temp, 0, data.length - offset);
}
if(i != 0){//只有第一次不做异或
temp = XOR(edata,temp);
}
edata = desedeEn(MACKEY,temp);
}
System.err.println(ConvertUtil.bcdToStr(edata));
}
public static byte[] XOR(byte[] edata, byte[] temp) {
byte [] result = new byte[8];
for (int i = 0 , j = result.length ; i < j; i++) {
result [i] = (byte) (edata[i] ^ temp[i]);
}
return result;
}
public static byte[] desedeEn(byte[] key,byte[] data){
byte[] result = null;
try {
SecretKey secretKey = getSecretKeySpec(key);
Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding","BC");
cipher.init(Cipher.ENCRYPT_MODE, secretKey,new IvParameterSpec(new byte[8]));//初始化项目为0
result = cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private static SecretKey getSecretKeySpec(byte[] keyB) throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("Des");
SecretKeySpec secretKeySpec = new SecretKeySpec(keyB,"Des");
return secretKeyFactory.generateSecret(secretKeySpec);
}
}