Java examples for Security:AES
Encrypts the given message using the given key with AES-CBC.
//package com.java2s; import javax.crypto.*; import javax.crypto.spec.*; public class Main { /**//www .ja v a2s . c o m * Encrypts the given message using the given key with AES-CBC. * * @param message the message (in bytes) * @param keySpec the secret key * @return encrypted message (with algorithm parameters appended */ public static byte[] encrypt(byte[] message, SecretKeySpec keySpec) { byte[] ret = null; try { // Initialize the cipher with the given key Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, keySpec); // encrypt the message byte[] cipherText = cipher.doFinal(message); byte[] params = cipher.getParameters().getEncoded(); // Combine the ciphertext and cipher parameters into one byte array ret = new byte[cipherText.length + params.length]; System.arraycopy(cipherText, 0, ret, 0, cipherText.length); System.arraycopy(params, 0, ret, cipherText.length, params.length); } catch (Exception e) { e.printStackTrace(); } return ret; } }