AES加/解密用法 - Java示例

JDK自带AES算法示例,指定密钥、长度及随机密钥。

指定密钥

 // private static final byte[] sessionKey = new byte[] {0x61, 0x46, 0x06D, 0x30, 0x2E, 0x70, 0x6D,
  // 0x77, 0x6F,0x72, 0x25, 0x2F, 0x7A, 0x56, 0x45, 0x65};


  // public static final byte[] sessionKey = new byte[] {0x72, 0x25, 0x2F, 0x5B, 0x7A, 0x30, 0x3A,
  // 0x3C, 0x26,
  // 0x79, 0x32, 0x30, 0x2E, 0x70, 0x6D, 0x3A};

 static byte[] sessionKey = "1234567891234567".getBytes();
 static byte[] iv = "ABCDEFGHjkouwoak".getBytes();

示例1/example 1: 

  Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  SecretKeySpec secretKeySpec = new SecretKeySpec(sessionKey, "AES");
  IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

  byte[] plaintext = "123456".getBytes();

  byte[] encrypt = encrypt(plaintext, cipher, secretKeySpec, ivParameterSpec);
  System.out.println(new String(Base64.encodeBase64(encrypt)));
  byte[] decrypt = decrypt(encrypt, cipher, secretKeySpec, ivParameterSpec);
  System.out.println(new String(decrypt));

加/解密

 public static byte[] encrypt(byte[] plaintext, Cipher cipher, SecretKeySpec secretKeySpec,
   IvParameterSpec ivParameterSpec) throws Exception {
  cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
  byte[] ciphertext = cipher.doFinal(plaintext);
  return ciphertext;
 }

 public static byte[] decrypt(byte[] ciphertext, Cipher cipher, SecretKeySpec secretKeySpec,
   IvParameterSpec ivParameterSpec) throws Exception {

  cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
  byte[] plaintext = cipher.doFinal(ciphertext);
  return plaintext;
 }

示例2/example 2: 

 String plainText = "Hello World";
  SecretKey secKey = getSecretEncryptionKey();
  byte[] cipherText = encryptText(plainText, secKey);
  System.out.println(new String(Base64.encodeBase64(cipherText)));
  byte[] decryptedText = decryptText(cipherText, secKey);
  System.out.println(new String(decryptedText));

获取随机密钥

public static SecretKey getSecretEncryptionKey() throws Exception {
  KeyGenerator generator = KeyGenerator.getInstance("AES");
  generator.init(128);
  SecretKey secKey = generator.generateKey();
  return secKey;
 }

加密

 public static byte[] encryptText(String plainText, SecretKey secKey) throws Exception {
  Cipher aesCipher = Cipher.getInstance("AES");
  aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
  byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
  return byteCipherText;
 }

解密

 public static byte[] decryptText(byte[] byteCipherText, SecretKey secKey) throws Exception {
  Cipher aesCipher = Cipher.getInstance("AES");
  aesCipher.init(Cipher.DECRYPT_MODE, secKey);
  byte[] bytePlainText = aesCipher.doFinal(byteCipherText);
  return bytePlainText;
 }