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.SecretKeySpec;

public class Main {
    public static final String KEY_ALGORITHM = "AES";
    public static final String CIPHER_ALGORITHM = "AES/ECB/PKCS7Padding";

    /** 
     * decrypt 
     * @param data prepare to be decrypted 
     * @param key byteArray[] key
     * @return byte[] original data 
     * */
    public static byte[] decrypt(byte[] data, byte[] key) throws Exception {

        Key k = byteArrayKeyToSecurityKey(key);

        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        //init, decrypt mode
        cipher.init(Cipher.DECRYPT_MODE, k);
        //exec 
        return cipher.doFinal(data);
    }

    /** 
     * byte[] key to java.security.Key
     * @param key byte[] key 
     * @return Key java.security.Key 
     * */
    public static Key byteArrayKeyToSecurityKey(byte[] key) throws Exception {

        return new SecretKeySpec(key, KEY_ALGORITHM);

    }
}