以下の encrypt メソッドの引数に String でテキスト文字列を渡すと、暗号化されたものがバイト列で返ってくる。復号は decrypt の引数にそのバイト列を渡す。両メソッド共、crypt_spec 引数に AES を指定すれば AES で暗号するし、DES を指定すれば DES で暗号化する。
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
// CHANGE THIS VALUE DEPENDING ON WHAT YOU WANT
public static final int MESSAGE_LENGTH = 1024;
/**
 * @param text
 *            Message to encrypt
 * @param secret_key
 *            Secret Key
 * @param crypt_spec
 *            Crypt algorithm like "AES" or "DES"
 * @return Encrypted Byte Strings
 */
public byte[] encrypt(String text, byte[] secret_key, String crypt_spec)
        throws InvalidKeyException, IllegalBlockSizeException, IOException,
        BadPaddingException {
    SecretKeySpec sKey = new SecretKeySpec(secret_key, crypt_spec);
    byte[] secret = new byte[MESSAGE_LENGTH];
    try {
        Cipher cipher = Cipher.getInstance(crypt_spec);
        cipher.init(Cipher.ENCRYPT_MODE, sKey);
        secret = cipher.doFinal(text.getBytes());
    } catch (Exception e) {
        System.out.println(this.getClass().getName()
                + ".encrypt: Exception:");
        e.printStackTrace();
    }
    return secret;
}
/**
 * @param b
 *            Encypted Byte Message
 * @param crypt_spec
 *            Crypt Algorithm like "AES" or "DES"
 * @return Decrypted String
 */
public String decrypt(byte[] b, byte[] secret_key, String crypt_spec)
        throws InvalidKeyException, IllegalBlockSizeException, IOException,
        BadPaddingException {
    SecretKeySpec sKey = new SecretKeySpec(secret_key, crypt_spec);
    byte[] secret = new byte[MESSAGE_LENGTH];
    try {
        Cipher cipher = Cipher.getInstance(crypt_spec);
        cipher.init(Cipher.DECRYPT_MODE, sKey);
        secret = cipher.doFinal(b);
    } catch (Exception e) {
        System.out.println(this.getClass().getName()
                + ".decrypt: Exception:");
        e.printStackTrace();
    }
    return new String(secret);
}
    トラックバック URL:
    https://perltips.twinkle.cc/trackback/93