decode byte array with AES/CBC/NoPadding - Java Security

Java examples for Security:AES

Description

decode byte array with AES/CBC/NoPadding

Demo Code


import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

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

public class Main {

  private static final int AES_128_KEY_LEN = 32;

  public static final String KEY_ALGORITHM = "AES";

  private static String CIPHER_ALGORITHM = "AES/CBC/NoPadding";
  private static final byte[] BT_KEY = "share_key".getBytes();
  private static final byte[] BT_IV = SecureRandom.getSeed(16);

  public static byte[] decode(byte[] btCipher) throws BadPaddingException, IllegalBlockSizeException,
      InvalidAlgorithmParameterException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
    return encodeDecode(btCipher, BT_KEY, BT_IV, 1);
  }/*from   w  ww . j ava 2s.  c  o m*/

  public static byte[] decode(byte[] btCipher, byte[] btKey, byte[] btIV)
      throws BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException,
      NoSuchAlgorithmException, NoSuchPaddingException {
    return encodeDecode(btCipher, btKey, btIV, 1);
  }

  public static byte[] encodeDecode(byte[] btData, byte[] btKey, byte[] btIV, int iFlag)
      throws BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException,
      NoSuchAlgorithmException, NoSuchPaddingException {
    int ii;
    int l_iMode;
    byte[] l_btKey = null;
    Cipher l_oCipher = null;

    if ((btData == null) || (btKey == null)) {
      return new byte[] {};
    }

    int iLen = btData.length;
    int iKeyLen = btKey.length;
    int iIVLen = btIV == null ? 0 : btIV.length;

    if (iKeyLen > AES_128_KEY_LEN) // 16 Bytes
    {
      iKeyLen = AES_128_KEY_LEN; // 16 Bytes
    }

    l_btKey = new byte[AES_128_KEY_LEN]; // 16 Bytes

    for (ii = 0; ii < AES_128_KEY_LEN; ii++) {
      l_btKey[ii] = (byte) 0x00;
    }

    for (ii = 0; ii < iKeyLen; ii++) {
      l_btKey[ii] = btKey[ii];
    }

    l_oCipher = Cipher.getInstance(CIPHER_ALGORITHM);

    if (iFlag == 0) {
      l_iMode = Cipher.ENCRYPT_MODE;
    } else {
      l_iMode = Cipher.DECRYPT_MODE;
    }

    if (btIV == null) {
      l_oCipher.init(l_iMode, new SecretKeySpec(l_btKey, 0, AES_128_KEY_LEN, KEY_ALGORITHM));
    } else {
      l_oCipher.init(l_iMode, new SecretKeySpec(l_btKey, 0, AES_128_KEY_LEN, KEY_ALGORITHM),
          new IvParameterSpec(btIV, 0, iIVLen));
    }
    return l_oCipher.doFinal(btData, 0, iLen);
  }
}

Related Tutorials