Skip to content

Instantly share code, notes, and snippets.

@honwhy
Created October 18, 2019 17:08
Show Gist options
  • Save honwhy/54292eb66d5a205bec11097f6646abae to your computer and use it in GitHub Desktop.
Save honwhy/54292eb66d5a205bec11097f6646abae to your computer and use it in GitHub Desktop.
aes cbc demo
package com.honey;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Random;
public class AesDemo {
private static final Random RANDOM = new Random(System.currentTimeMillis());
public static void main(String[] args) throws Exception {
String key = randomKey();
String iv = randomKey();
System.out.println("AES/CBC/PKCS5Padding");
System.out.println("key=" + key + ",iv=" + iv);
String content = "you can't see me!";
String encrypted = encrypt(content, key, iv);
String decrypted = decrypt(encrypted, key, iv);
System.out.println("encrypted=" + encrypted + ",decrypted=" + decrypted);
}
private static String randomKey() {
String origin = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "1234567890";
StringBuilder sb = new StringBuilder(16);
for (int i = 0; i < 16; i++) {
int idx = RANDOM.nextInt(26 + 26 + 10);
sb.append(origin.charAt(idx));
}
return sb.toString();
}
//加密
public static String encrypt(String content, String key, String iv) throws Exception {
byte[] raw = key.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"
//使用CBC模式,需要一个向量iv,可增加加密算法的强度
IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ips);
byte[] encrypted = cipher.doFinal(content.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
//解密
public static String decrypt(String content, String key, String iv) throws Exception {
try {
byte[] raw = key.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ips);
byte[] encrypted = Base64.getDecoder().decode(content);
try {
byte[] original = cipher.doFinal(encrypted);
String originalString = new String(original, StandardCharsets.UTF_8);
return originalString;
} catch (Exception e) {
System.err.println(e.toString());
return null;
}
} catch (Exception ex) {
System.err.println(ex.toString());
return null;
}
}
}
///
/// one result example
///
AES/CBC/PKCS5Padding
key=0oaJ3WwHV1me3NwL,iv=DhlQ9sIG3i5Q7R0d
encrypted=tEglOFwLnnaZUlJdh6mQPtJh6xSbmlQ5iutCg6x6QB4=,decrypted=you can't see me!
///
/// for checking online
/// see http://ctf.ssleye.com/caes.html
/// img: https://wx1.sinaimg.cn/mw1024/667f4ad7ly1g82unnwe6xj21iz0u0adz.jpg
///
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment