Top / Java / 暗号化

Javaで共通鍵暗号方式で暗号化を行うやりかたです。

サンプルコード

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

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

public class EncryptSample {

  public static void main(String[] args) throws Exception {
    // 鍵の文字列の作成
    String key = "aaaaaaaaaabbbbbb"; //16バイトである必要がある
    byte[] keyBytes = key.getBytes();

    byte[] enBytes = EncryptSample.encrypt("きの".getBytes(), keyBytes);
    System.out.println(new String(enBytes));

    byte[] deBytes = EncryptSample.decrypt(enBytes, keyBytes);
    System.out.println(new String(deBytes));
  }

  /**
   * 
   * @param data
   *      暗号化したいデータ
   * @param secret_key
   *      秘密鍵
   * @return 暗号化されたデータ
   */
  public static byte[] encrypt(byte[] data, byte[] secret_key) {
    SecretKeySpec sKey = new SecretKeySpec(secret_key, "AES");
    try {
      // Cipher cipher = Cipher.getInstance("AES");
      // cipher.init(Cipher.ENCRYPT_MODE, sKey);
      // secret = cipher.doFinal(text.getBytes());

      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      cipher.init(Cipher.ENCRYPT_MODE, sKey);
      byte[] iv = cipher.getIV();
      byte[] enc = cipher.doFinal(data);
      byte[] ret = new byte[iv.length + enc.length];
      System.arraycopy(iv, 0, ret, 0, iv.length);
      System.arraycopy(enc, 0, ret, iv.length, enc.length);
      return ret;
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    }
    return new byte[0];
  }

  /**
   * @param encData
   *      暗号化されたデータ
   * @param secret_key
   *      秘密鍵
   * @return 復号化されたデータ
   */
  public static byte[] decrypt(byte[] encData, byte[] secret_key) {

    SecretKeySpec sKey = new SecretKeySpec(secret_key, "AES");
    byte[] secret = null;

    try {
      // Cipher cipher = Cipher.getInstance("AES");
      // cipher.init(Cipher.DECRYPT_MODE, sKey);
      // secret = cipher.doFinal(encData);

      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      AlgorithmParameters iv = AlgorithmParameters.getInstance("AES");
      final int BLOCK_SIZE = cipher.getBlockSize();
      byte[] ib = new byte[2 + BLOCK_SIZE];
      ib[0] = 4;
      ib[1] = (byte) BLOCK_SIZE;
      System.arraycopy(encData, 0, ib, 2, BLOCK_SIZE);
      iv.init(ib);
      cipher.init(Cipher.DECRYPT_MODE, sKey, iv);
      secret = cipher.doFinal(encData, BLOCK_SIZE, encData.length
          - BLOCK_SIZE);
      return secret;
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    }
    return new byte[0];
  }
}

共通鍵をランダムに生成する

上のように明示的に指定して共通鍵を作ることもできるし、ランダムに鍵を生成することもできます。

private static Key genKey() throws NoSuchAlgorithmException {
  KeyGenerator generator = KeyGenerator.getInstance("AES");
  SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
  generator.init(128, random);
  Key key = generator.generateKey();
  return key;
}

このキークラスから

byte[] keyBytes = key.getEncoded();

とやってキーのバイト列を取得することができます。このバイト列をファイルに保存しておけば鍵ファイルができます。

Utils.byte2File(keyBytes, "hoge.key");

この記事は

選択肢 投票
おもしろかった 0  
そうでもない 0  

Top / Java / 暗号化

現在のアクセス:59204


トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS