【Java】Java で暗号化/複合化する ~Java1.8 標準を使用した場合 / IV使用編~

■ サンプル

Main.java

public class Main {
  public static void main(String[] args) {
    try {
      String algorithm = "AES"; // 暗号化方式「AES(Advanced Encryption Standard)」
      String key = "1234567890123456"; // 暗号化方式「AES」の場合、キーは16文字で
      String iv = "abcdefghijklmnop"; // 暗号化方式「AES」の場合、初期化ベクトルは16文字で

      String original = "This is a source of string!!"; // 元の文字列
      System.out.println("入力値データ:" + original);
      
      String encrypedResult = CipherHelper.encrypt(original, algorithm, key, iv);
      System.out.println("暗号化文字列:" + encrypedResult);

      String decryptedResult = CipherHelper.decrypt(encrypedResult, algorithm, key, iv);
      System.out.println("復号化文字列:" + decryptedResult);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

CipherHelper.java

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class CipherHelper {
  private static final String FORMAT_OF_TRANSFORMATION = "%s/CBC/PKCS5Padding";

  public static String encrypt(String originalSource, String algorithm, String secretKey, String initializationVector)
      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
      BadPaddingException, InvalidAlgorithmParameterException {

    byte[] originalBytes = originalSource.getBytes();
    byte[] encryptBytes = CipherHelper.cipher(originalBytes, true, algorithm, secretKey, initializationVector);
    return Base64.getEncoder().encodeToString(encryptBytes);
  }

  public static String decrypt(String encryptBytesBase64String, String algorithm, String secretKey,
      String initializationVector) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
      IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {

    byte[] encryptBytes = Base64.getDecoder().decode(encryptBytesBase64String);
    byte[] originalBytes = CipherHelper.cipher(encryptBytes, false, algorithm, secretKey, initializationVector);
    return new String(originalBytes);
  }

  /**
   * 暗号化/複合化の共通部分
   * 
   * @throws InvalidAlgorithmParameterException
   */
  private static byte[] cipher(byte[] source, boolean isEncrypt, String algorithm, String secretKey,
      String initializationVector) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
      IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
    
    SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), algorithm);
    IvParameterSpec iv = new IvParameterSpec(initializationVector.getBytes());
    Cipher cipher = Cipher.getInstance(String.format(FORMAT_OF_TRANSFORMATION, secretKeySpec.getAlgorithm()));
    if (isEncrypt) {
      cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv);
    } else {
      cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv);
    }

    return cipher.doFinal(source);
  }
}

出力結果

入力値データ:This is a source of string!!
暗号化文字列:2Bx/tukQtqTtUZcOfpPav0QPJJGYz8hnHrj4GLC/s0w=
復号化文字列:This is a source of string!!

■ 補足

パディング方式

[1] NoPadding       : パディングなし
[2] ZeroBytePadding : null値でパディング
[3] PKCS5Padding    : パディング文字数を表す数字でパディング

初期化ベクトル(Initialization Vector; IV)

 * 以下の関連記事を参照のこと。
https://blogs.yahoo.co.jp/dk521123/36417953.html


関連記事

Java

暗号化/複合化する ~Apache Commonsを使用した場合~
https://blogs.yahoo.co.jp/dk521123/32780473.html
Java で暗号化/複合化する ~Java1.8 標準を使用した場合~
https://blogs.yahoo.co.jp/dk521123/34330480.html
Java で暗号化/複合化する ~Java1.8 標準を使用した場合 / IV使用編~
https://blogs.yahoo.co.jp/dk521123/36419973.html
【トラブル】Java で初回の暗号化/複合化処理に時間が掛かる
https://blogs.yahoo.co.jp/dk521123/36783396.html
BouncyCastleライブラリ ~Java暗号ライブラリ~
https://blogs.yahoo.co.jp/dk521123/33256866.html
Java】 セキュアなランダム文字列生成を考える
https://blogs.yahoo.co.jp/dk521123/36415526.html

C#

共有キー暗号方式 ~暗号化編~
https://blogs.yahoo.co.jp/dk521123/30818470.html

その他

暗号化アルゴリズム
https://blogs.yahoo.co.jp/dk521123/36417953.html
暗号に関わる用語
https://blogs.yahoo.co.jp/dk521123/37269757.html