privateexample.java

来自「这是一个文本加密、解密系统」· Java 代码 · 共 57 行

JAVA
57
字号
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 + =
减小字号Ctrl + -
显示快捷键?