📄 privateexample.java
字号:
package example;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
/**
*私?加密,保证消息机密性
*/
public class PrivateExample
{
public static void main(String[] args) throws Exception
{
byte[] plainText=args[0].getBytes("UTF8");
//通过KeyGenerator形成一个key
System.out.println("\nStart generate AES key");
KeyGenerator keyGen=KeyGenerator.getInstance("AES");
keyGen.init(128);
Key key=keyGen.generateKey();
System.out.println("Finish generating AES key");
System.out.println("key is " + new String(key.getEncoded()));
//获得一个私?加密类Cipher,ECB是加密方式,PKCS5Padding是填充方法
Cipher cipher=Cipher.getInstance("AES/ECB/PKCS5Padding");
System.out.println("\n"+cipher.getProvider().getInfo());
System.out.println(Cipher.getMaxAllowedKeyLength(new String(plainText)));
//使用私?加密
System.out.println("\nStart encryption:");
cipher.init(Cipher.ENCRYPT_MODE,key);
byte[] cipherText=cipher.doFinal(plainText);
System.out.println("Finish encryption:");
System.out.println(new String(cipherText,"UTF8"));
/*
cipherText[0] = 'c';
cipherText[1] = 'g';
cipherText[2] = 'a';
cipherText[3] = 'd';
cipherText[4] = 'r';
cipherText[5] = 'e';
cipherText[6] = 'q';
cipherText[7] = 'k';
//*/
System.out.println("\nStart decryption:");
cipher.init(Cipher.DECRYPT_MODE,key);
byte[] newPlainText=cipher.doFinal(cipherText);
System.out.println("Finish decryption:");
System.out.println(new String(newPlainText,"UTF8"));
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -