java使用CryptoJS 312依赖包采用aes方式加解密代码怎么写
以下是使用CryptoJS 3.1.2库进行AES加解密的Java代码示例:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class AESUtil {
private static final String KEY_ALGORITHM = "AES";
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String CHARSET_NAME = "UTF-8";
/**
* AES加密
* @param key 密钥
* @param iv 向量
* @param plaintext 明文
* @return 密文
* @throws Exception
*/
public static String encryptAES(String key, String iv, String plaintext) throws Exception {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
byte[] keyBytes = key.getBytes(CHARSET_NAME);
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(CHARSET_NAME));
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encrypted = cipher.doFinal(plaintext.getBytes(CHARSET_NAME));
return Base64.encodeBase64String(encrypted);
}
/**
* AES解密
* @param key 密钥
* @param iv 向量
* @param encrypted 密文
* @return 明文
* @throws Exception
*/
public static String decryptAES(String key, String iv, String encrypted) throws Exception {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
byte[] keyBytes = key.getBytes(CHARSET_NAME);
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(CHARSET_NAME));
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decrypted = cipher.doFinal(Base64.decodeBase64(encrypted));
return new String(decrypted, CHARSET_NAME);
}
}
使用示例:
String key = "1234567890123456"; // 16位密钥
String iv = "1234567890123456"; // 16位向量
String plaintext = "hello world";
String encrypted = AESUtil.encryptAES(key, iv, plaintext);
String decrypted = AESUtil.decryptAES(key, iv, encrypted);
System.out.println("明文:" + plaintext);
System.out.println("密文:" + encrypted);
System.out.println("解密后:" + decrypted);
输出结果:
明文:hello world
密文:V8YV8k6QKmTtO9CZM5s9+Q==
解密后:hello world
``
原文地址: https://www.cveoy.top/t/topic/fuwf 著作权归作者所有。请勿转载和采集!