import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Scanner;public class TestAES {
public static void main(String[] args) throws Exception {
System.out.println("输入需要加密的消息:");
Scanner input = new Scanner(System.in);
String message= input.nextLine();
KeyGenerator kgen = KeyGenerator.getInstance("AES");//初始化密匙生成器
kgen.init(128);
SecretKey skey = kgen.generateKey();//生成密钥
Cipher cipher = Cipher.getInstance("AES");//初始化加密器
cipher.init(Cipher.ENCRYPT_MODE, skey);
byte[] encrypted = cipher.doFinal((message).getBytes());//加密
System.out.println("加密后的消息: " + new String(encrypted));
cipher.init(Cipher.DECRYPT_MODE, skey);
byte[] original = cipher.doFinal(encrypted);//解密
String originalString = new String(original);
System.out.println("解密后的消息: " +originalString);
input.close();
}
}测试结果:
java AES加密示例
最新推荐文章于 2024-07-23 16:20:49 发布