Java AES encryptDecrypt(int mode, String data, String key, String salt, String iv)

Here you can find the source of encryptDecrypt(int mode, String data, String key, String salt, String iv)

Description

Encrypts and decrypts a string.

License

Open Source License

Parameter

Parameter Description
mode integer that determines whether to encrypt or decrypt
data data to encrypt/decrypt
key encryption/decryption key
salt random salt
iv random initialization vector

Exception

Parameter Description

Return

encrypted/decrypted string

Declaration

public static String encryptDecrypt(int mode, String data, String key, String salt, String iv)
        throws Exception 

Method Source Code


//package com.java2s;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;

import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

public class Main {
    public final static int DECRYPT_MODE = 2;
    private final static int ITERATIONS = 10000;
    private final static int KEY_LENGTH = 128;
    private final static String SECRET_KEY_FACTORY_ALGORITHM = "PBKDF2WithHmacSHA1";
    private final static String SECRET_KEY_ALGORITHM = "AES";
    private final static String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";

    /**//from  ww  w. j av a2  s .  co  m
     * Encrypts and decrypts a string.
     *
     * @param mode integer that determines whether to encrypt or decrypt
     * @param data data to encrypt/decrypt
     * @param key  encryption/decryption key
     * @param salt random salt
     * @param iv   random initialization vector
     * @return encrypted/decrypted string
     * @throws java.security.spec.InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException
     */
    public static String encryptDecrypt(int mode, String data, String key, String salt, String iv)
            throws Exception {
        KeySpec pbeKeySpec = new PBEKeySpec(key.toCharArray(), DatatypeConverter.parseBase64Binary(salt),
                ITERATIONS, KEY_LENGTH);
        SecretKey secretKey = getSecretKey(pbeKeySpec);
        Cipher cipher = getCipher();
        cipher.init(mode, secretKey, new IvParameterSpec(DatatypeConverter.parseBase64Binary(iv)));
        if (mode == DECRYPT_MODE) {
            return new String(cipher.doFinal(DatatypeConverter.parseBase64Binary(data)), StandardCharsets.UTF_8);
        } else {
            return DatatypeConverter.printBase64Binary(cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)));
        }
    }

    /**
     * Generates SecretKey.
     *
     * @param pbeKeySpec password based encryption key spec
     * @return SecretKey
     * @throws java.security.NoSuchAlgorithmException, InvalidKeySpecException
     */
    private static SecretKey getSecretKey(KeySpec pbeKeySpec)
            throws NoSuchAlgorithmException, InvalidKeySpecException {
        SecretKey tmpKey = getSecretKeyFactory().generateSecret(pbeKeySpec);
        return new SecretKeySpec(tmpKey.getEncoded(), SECRET_KEY_ALGORITHM);
    }

    /**
     * Generates a cipher.
     *
     * @return Cipher
     * @throws javax.crypto.NoSuchPaddingException, NoSuchAlgorithmException
     */
    private static Cipher getCipher() throws NoSuchPaddingException, NoSuchAlgorithmException {
        return Cipher.getInstance(CIPHER_ALGORITHM);
    }

    /**
     * Generates SecretKeyFactory.
     *
     * @return SecretKeyFactory
     * @throws java.security.NoSuchAlgorithmException
     */
    private static SecretKeyFactory getSecretKeyFactory() throws NoSuchAlgorithmException {
        return SecretKeyFactory.getInstance(SECRET_KEY_FACTORY_ALGORITHM);
    }
}

Related

  1. aesStoreKeyToFile(Key secretKey, String path)
  2. createSessionKey()
  3. decrypt(String encryptedText, String key)
  4. decrypt_aes(String key, String initVector, String encrypted)
  5. encryptAes(String value)
  6. getAesKey(String key)