package com.sf.test.encryption;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Scanner;
public class AESUtil {
public static String AESEncode(String encodeRules, String content) {
try {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128, new SecureRandom(encodeRules.getBytes()));
SecretKey original_key = keyGen.generateKey();
byte[] raw = original_key.getEncoded();
SecretKey key = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] byte_encode = content.getBytes(StandardCharsets.UTF_8);
byte[] byte_AES = cipher.doFinal(byte_encode);
String AES_encode = new String(Base64.getEncoder().encode(byte_AES));
return AES_encode;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
public static String AESDecode(String encodeRules, String content) {
try {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128, new SecureRandom(encodeRules.getBytes()));
SecretKey original_key = keyGen.generateKey();
byte[] raw = original_key.getEncoded();
SecretKey key = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] byte_content = Base64.getDecoder().decode(content);
byte[] byte_decode = cipher.doFinal(byte_content);
String AES_decode = new String(byte_decode, StandardCharsets.UTF_8);
return AES_decode;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
public static void test1() {
Scanner scanner = new Scanner(System.in);
System.out.println("encodeRules: ");
String encodeRules = scanner.next();
System.out.println("content to be encoded: ");
String content = scanner.next();
String encodedString = AESEncode(encodeRules, content);
System.out.println("encodedString: " + encodedString);
System.out.println("decodedString: " + AESDecode(encodeRules, encodedString));
}
public static void main(String[] args) {
test1();
}
}
encodeRules:
AllowMeToTakeCareOfYou
content to be encoded:
IWantToTakeCareOfYou
encodedString: ySFEfux/g+po5L//U4lOrLccosTHFNa8tNYVOKGNEjE=
decodedString: IWantToTakeCareOfYou