import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;
class Main {
public static void main(String[] args) {
System.out.println("Hello world! - java.jsrun.net ");
byte[] key = getRule(16);
String plaintext = "Hello, World!";
String encrypt = encrypt(plaintext, key);
String decryptedPlaintext = decrypt(encrypt, key);
System.out.println("明文数据: " + plaintext);
System.out.println("加密后的数据: " + encrypt);
System.out.println("解密后的数据: " + decryptedPlaintext);
System.out.println("Hello, World");
}
public static final String AES_CBC = "AES/CBC/PKCS5Padding";
public static final String AES_KEY = "AES";
public byte[] getRule(int i) throws Exception {
if (i != 16 && i != 24 && i != 32) {
throw new Exception("规则位数必须是16或24或32位数!");
}
StringBuffer sb = new StringBuffer();
byte[] key = new byte[i];
SecureRandom secureRandom = new SecureRandom();
secureRandom.nextBytes(key);
for (int in : key) {
sb.append(in).append(",");
}
String substring = sb.substring(0, sb.length() - 1);
System.out.println("秘钥:" + substring);
return key;
}
public static SecretKeySpec secretKeySpec(byte[] key) {
return new SecretKeySpec(key, AES_KEY);
}
public static Cipher cipher(byte[] key, int i) throws Exception {
SecretKeySpec secretKeySpec = secretKeySpec(key);
IvParameterSpec ivParameterSpec = new IvParameterSpec(key);
Cipher cipher = Cipher.getInstance(AES_CBC);
cipher.init(i, secretKeySpec, ivParameterSpec);
return cipher;
}
public static String encrypt(String plaintext, byte[] key) throws Exception {
Cipher cipher = cipher(key, Cipher.ENCRYPT_MODE);
byte[] bytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
String encode = Base64.getEncoder().encodeToString(bytes);
return encode;
}
public static String decrypt(String encrypt, byte[] key) throws Exception {
byte[] decode = Base64.getDecoder().decode(encrypt);
Cipher cipher = cipher(key, Cipher.DECRYPT_MODE);
byte[] plaintextBytes = cipher.doFinal(decode);
String plaintext = new String(plaintextBytes, StandardCharsets.UTF_8);
return plaintext;
}
}