Here you can find the source of encrypt(byte[] data, byte[] key, String cipherAlgorithm)
Parameter | Description |
---|---|
data | data |
key | binary secret key |
cipherAlgorithm | encrypt algorithm/work pattern/padding mode |
Parameter | Description |
---|---|
Exception | an exception |
public static byte[] encrypt(byte[] data, byte[] key, String cipherAlgorithm) throws Exception
//package com.java2s; import java.security.Key; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class Main { /**/*from w ww . j av a 2s . c o m*/ * Secret Key algorithms */ private static final String KEY_ALGORITHM = "AES"; private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding"; /** * encrypt * * @param data data * @param key secret key * @return byte[] encrypt data * @throws Exception */ public static byte[] encrypt(byte[] data, Key key) throws Exception { return encrypt(data, key, DEFAULT_CIPHER_ALGORITHM); } /** * encrypt * * @param data data * @param key binary secret key * @return byte[] encrypt data * @throws Exception */ public static byte[] encrypt(byte[] data, byte[] key) throws Exception { return encrypt(data, key, DEFAULT_CIPHER_ALGORITHM); } /** * encrypt * * @param data data * @param key binary secret key * @param cipherAlgorithm encrypt algorithm/work pattern/padding mode * @return byte[] encrypt data * @throws Exception */ public static byte[] encrypt(byte[] data, byte[] key, String cipherAlgorithm) throws Exception { //restore secret key Key k = toKey(key); return encrypt(data, k, cipherAlgorithm); } /** * encrypt * * @param data data * @param key secret key * @param cipherAlgorithm encrypt algorithm/work pattern/padding mode * @return byte[] encrypt data * @throws Exception */ public static byte[] encrypt(byte[] data, Key key, String cipherAlgorithm) throws Exception { //init Cipher cipher = Cipher.getInstance(cipherAlgorithm); //set encrypt mode cipher.init(Cipher.ENCRYPT_MODE, key); //perform action return cipher.doFinal(data); } /** * transfer secret key * * @param key binary secret key * @return secret key */ private static Key toKey(byte[] key) { //create secret key return new SecretKeySpec(key, KEY_ALGORITHM); } }