Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.util.Arrays;
import javax.crypto.Cipher;

import javax.crypto.spec.SecretKeySpec;

public class Main {
    public static byte[] calMacCode(byte[] mak, byte[] src) {
        int srcLen = src.length;
        int m_len = srcLen % 8;
        int count = srcLen + (m_len == 0 ? m_len : (8 - m_len));

        byte[] calData = new byte[count];
        byte[] _data8 = new byte[8];
        Arrays.fill(calData, (byte) 0);
        Arrays.fill(_data8, (byte) 0);
        System.arraycopy(src, 0, calData, 0, srcLen);
        System.arraycopy(calData, 0, _data8, 0, 8);

        for (int i = 1; i < count / 8; i++) {
            for (int j = 0; j < 8; j++) {
                _data8[j] = (byte) (_data8[j] ^ calData[i * 8 + j]);
            }
        }

        return TriDesEncryption(mak, _data8);
    }

    public static byte[] TriDesEncryption(byte[] byteKey, byte[] dec) {
        try {
            byte[] en_key = new byte[24];
            if (byteKey.length == 16) {
                System.arraycopy(byteKey, 0, en_key, 0, 16);
                System.arraycopy(byteKey, 0, en_key, 16, 8);
            }
            SecretKeySpec key = new SecretKeySpec(en_key, "DESede");
            Cipher ecipher = Cipher.getInstance("DESede/ECB/NoPadding");
            ecipher.init(Cipher.ENCRYPT_MODE, key);

            byte[] en_b = ecipher.doFinal(dec);
            return en_b;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}