Java AES Descrypt aesDecrypt(byte[] content, Key key)

Here you can find the source of aesDecrypt(byte[] content, Key key)

Description

aes Decrypt

License

Open Source License

Declaration

public static byte[] aesDecrypt(byte[] content, Key key) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import javax.crypto.Cipher;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.file.Files;

import java.nio.file.Paths;
import java.security.Key;

public class Main {
    private static final String AES_KEY_ALGORITHM = "AES";
    private static final String AES_CIPER_ALGRITHM = "AES/ECB/PKCS5Padding";

    public static byte[] aesDecrypt(byte[] content, Key key) {
        return aesCrypt(content, key, Cipher.DECRYPT_MODE);
    }/*  www .ja va2 s. co m*/

    public static byte[] aesDecrypt(byte[] content, String path) {
        SecretKey secretKey = aesReadKeyFromFile(path);
        if (null != secretKey) {
            return aesDecrypt(content, secretKey);
        }
        return content;
    }

    private static byte[] aesCrypt(byte[] content, Key key, int crypt) {
        try {
            Cipher cipher = Cipher.getInstance(AES_CIPER_ALGRITHM);
            cipher.init(crypt, key);
            return cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    private static SecretKey aesReadKeyFromFile(String path) {
        SecretKeySpec secretKeySpec = null;
        if (null != path && path.trim().length() > 0) {
            try {
                byte[] bytes = Files.readAllBytes(Paths.get(path));
                secretKeySpec = new SecretKeySpec(bytes, AES_KEY_ALGORITHM);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return secretKeySpec;
    }
}

Related

  1. AESDecrypt(byte[] encrypted, byte[] key, byte[] iv)
  2. aesDecrypt(byte[] input, Key key)
  3. aesDecrypt(String encryptStr, String decryptKey)
  4. aesDecryptByBytes(byte[] encryptBytes, String decryptKey)