LoginSignup
24
21

More than 3 years have passed since last update.

【Java】標準ライブラリでAES暗号で暗号化する方法

Last updated at Posted at 2019-06-13

やりたいこと

  • Javaの標準ライブラリを使ってtokenを暗号化して保存したい
  • token情報を取得する際は復号化した状態で使いたい
  • 暗号化と復号化するときの鍵が同じAES暗号を使いたい

暗号化/復号化処理のサンプル

  • 暗号化&復号化で使用する鍵は128bit(=16byte/英数字16文字)
  • 暗号利用モードがCBCの場合は鍵と同じ長さの初期ベクトルが必要

実装例

CryptSample.java
package com.tamorieeeen.sample

import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 暗号化/復号化処理サンプル
 * @author tamorieeeen
 */
public class CryptSample {

  // アルゴリズム/ブロックモード/パディング方式
  private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
  // 暗号化&復号化で使用する鍵
  private static final String ENCRYPT_KEY = "yourEncryptKey01";
  // 初期ベクトル
  private static final String INIT_VECTOR = "yourInitVector01";

  private final IvParameterSpec iv = new IvParameterSpec(INIT_VECTOR.getBytes());
  private final SecretKeySpec key = new SecretKeySpec(ENCRYPT_KEY.getBytes(), "AES");

  /**
   * tokenを保存
   */
  public void saveToken(String token) {

    String encryptedToken = this.encryptToken(token);
    // encryptedTokenをDBに保存
    this.saveTokenToDb(encryptedToken);
  }

  /**
   * 暗号化処理
   */
  private String encryptToken(String token) throws Exception {

    Cipher encrypter = Cipher.getInstance(ALGORITHM);
    encrypter.init(Cipher.ENCRYPT_MODE, this.key, this.iv);
    byte[] byteToken = encrypter.doFinal(token.getBytes());

    return new String(Base64.getEncoder().encode(byteToken));
  }

  /**
   * tokenを取得
   */
  public String getToken() {

    // DBからtokenを取得
    String encryptedToken = this.getEncryptedTokenFromDb();

    return this.decryptToken(encryptedToken);
  }

  /**
   * 復号化処理
   */
  private String decryptToken(String encryptedToken) throws Exception {

    Cipher decrypter = Cipher.getInstance(ALGORITHM);
    decrypter.init(Cipher.DECRYPT_MODE, this.key, this.iv);
    byte[] byteToken = Base64.getDecoder().decode(encryptedToken);

    return new String(decrypter.doFinal(byteToken));
  }

  /** ここから下は各自必要なメソッドを作成してください **/

  /**
   * tokenをDBに保存
   */
  private void saveTokenToDb(String encryptedToken) throws Exception {

    // encryptedTokenをDBに保存する処理
  }

  /**
   * DBからtokenを取得
   */
  private String getEncryptedTokenFromDb() throws Exception {

    // DBからtokenを取得する処理
  }
}

参考

【Java】標準ライブラリで暗号技術を使う
暗号処理をやってみよう!

24
21
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
21