AES128bit暗号化/復号化を文字列で行なってみる
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.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; /** * 文字列のAES暗号化/復号化ユーティリティ * * @author bose999 * */ public class AESUtil { /** * AES */ private static final String AES = "AES"; public static void main(String[] args) { try { String secretKey = "12345678901$3456"; // キーは16文字で String original = "この文字列を暗号化したいの!"; // 元の文字列 String encryptBytesBase64String = AESUtil.encrypt(original, secretKey); System.out.println("暗号化文字列:" + encryptBytesBase64String); String returnString = AESUtil.decrypt(encryptBytesBase64String, secretKey); System.out.println("復号化文字列:" + returnString); } catch (Exception e) { e.printStackTrace(); } } /** * 文字列を16文字の秘密鍵でAES暗号化してBase64した文字列で返す * * @param originalString String * @param secretKey String * @return String * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws InvalidKeyException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public static String encrypt(String originalString, String secretKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { byte[] originalBytes = originalString.getBytes(); byte[] secretKeyBytes = secretKey.getBytes(); SecretKeySpec secretKeySpec = new SecretKeySpec(secretKeyBytes, AES); Cipher cipher = Cipher.getInstance(AES); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); byte[] encryptBytes = cipher.doFinal(originalBytes); byte[] encryptBytesBase64 = Base64.encodeBase64(encryptBytes, false); return new String(encryptBytesBase64); } /** * Base64されたAES暗号化文字列を元の文字列に復元する * * @param encryptBytesBase64String String * @param secretKey String * @return String * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws InvalidKeyException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public static String decrypt(String encryptBytesBase64String, String secretKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { byte[] encryptBytes = Base64.decodeBase64(encryptBytesBase64String); byte[] secretKeyBytes = secretKey.getBytes(); SecretKeySpec secretKeySpec = new SecretKeySpec(secretKeyBytes, AES); Cipher cipher = Cipher.getInstance(AES); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); byte[] originalBytes = cipher.doFinal(encryptBytes); return new String(originalBytes); } }
コンソールへの出力結果
暗号化文字列:dtA6UNsMnahxCkfGdrc8AFhisnFZg8FnKTl7Sk4Wg9J8gYK8+Dv6Io7Ssef7ZPTo 復号化文字列:この文字列を暗号化したいの!