java aes256
时间: 2023-11-16 07:07:52 浏览: 133
以下是Java中使用AES-256加密解密的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;
import java.util.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 content 待加密内容
* @param password 密钥
* @param iv 向量
* @return 加密后的字符串
*/
public static String encrypt(String content, String password, String iv) {
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
byte[] raw = password.getBytes(CHARSET_NAME);
SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_ALGORITHM);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(CHARSET_NAME));
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);
byte[] encrypted = cipher.doFinal(content.getBytes(CHARSET_NAME));
return Base64.getEncoder().encodeToString(encrypted);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* AES解密
*
* @param content 待解密内容
* @param password 密钥
* @param iv 向量
* @return 解密后的字符串
*/
public static String decrypt(String content, String password, String iv) {
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
byte[] raw = password.getBytes(CHARSET_NAME);
SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_ALGORITHM);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(CHARSET_NAME));
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);
byte[] encrypted = Base64.getDecoder().decode(content);
byte[] original = cipher.doFinal(encrypted);
return new String(original, CHARSET_NAME);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
```
使用示例:
```java
public class Test {
public static void main(String[] args) {
String content = "Hello, world!";
String password = "12345678901234567890123456789012";
String iv = "1234567890123456";
String encrypted = AESUtil.encrypt(content, password, iv);
System.out.println("加密后的内容:" + encrypted);
String decrypted = AESUtil.decrypt(encrypted, password, iv);
System.out.println("解密后的内容:" + decrypted);
}
}
```
阅读全文