Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import java.nio.ByteBuffer;
import java.security.*;

import java.util.Arrays;

public class Main {
    static final int AES_BLOCK_SIZE = 16;

    public static byte[] aesIGEdecrypt(byte[] tmpAESiv, byte[] tmpAesKey, byte[] data) {
        try {

            ByteBuffer out = ByteBuffer.allocate(data.length);

            byte[] iv2p = Arrays.copyOfRange(tmpAESiv, 0, tmpAESiv.length / 2);
            byte[] ivp = Arrays.copyOfRange(tmpAESiv, tmpAESiv.length / 2, tmpAESiv.length);

            int len = data.length / AES_BLOCK_SIZE;

            byte[] xorInput = null;
            byte[] xorOutput = null;

            SecretKeySpec keySpec = null;
            keySpec = new SecretKeySpec(tmpAesKey, "AES");
            Cipher cipher = null;
            cipher = Cipher.getInstance("AES/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec);

            byte[] input = null;
            byte[] output = null;

            for (int i = 0; i < len; i++) {
                input = Arrays.copyOfRange(data, i * AES_BLOCK_SIZE, (i + 1) * AES_BLOCK_SIZE);
                xorInput = xor(input, ivp);
                output = cipher.doFinal(xorInput);
                xorOutput = xor(output, iv2p);
                out.put(xorOutput);

                ivp = xorOutput;
                iv2p = input;
            }
            return out.array();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static byte[] xor(byte[] a, byte[] b) {
        if (a.length == b.length) {
            byte[] res = new byte[a.length];
            for (int i = 0; i < a.length; i++) {
                res[i] = (byte) (a[i] ^ b[i]);
            }
            return res;
        } else
            return null;
    }
}