Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.security.Key;

import javax.crypto.Cipher;

import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    private static final String KEY_ALGORITHM = "AES";
    private static final String CIPHER_ALGORITHM_DEFAULT = "AES";

    public static byte[] encrypt(byte[] data, byte[] key) {
        return encrypt(data, key, CIPHER_ALGORITHM_DEFAULT);
    }

    public static byte[] encrypt(byte[] data, byte[] key, String cipherAlgotirhm) {
        return encrypt(data, key, null, cipherAlgotirhm);
    }

    public static byte[] encrypt(byte[] data, byte[] key, byte[] iv, String cipherAlgotirhm) {
        try {
            Cipher cipher = initCipher(Cipher.ENCRYPT_MODE, key, iv, cipherAlgotirhm);
            return cipher.doFinal(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Cipher initCipher(int mode, byte[] key, byte[] iv, String cipherAlgotirhm) {
        try {
            Key k = toKey(key);
            Cipher cipher = Cipher.getInstance(cipherAlgotirhm);
            String CipherAlgotirhm = cipherAlgotirhm.toUpperCase();
            if (CipherAlgotirhm.contains("CFB") || CipherAlgotirhm.contains("CBC"))
                cipher.init(mode, k, new IvParameterSpec(iv));
            else
                cipher.init(mode, k);
            return cipher;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    private static Key toKey(byte[] key) {
        return new SecretKeySpec(key, KEY_ALGORITHM);
    }
}