過去に何度も書いた Java AES 暗合・複合
秘密鍵、初期ベクトルをどう作成するか、いろんな方法あるが、
改めて、256bit で、SHA-256 ハッシュ値を使う方法。
暗合
public static String encrypt(String passwd, String message){
try{
byte[] key = passwd.getBytes();
MessageDigest sha = MessageDigest.getInstance("SHA-256");
key = sha.digest(key);
key = Arrays.copyOf(key, 32);
SecretKeySpec keyObj = new SecretKeySpec(key, "AES");
IvParameterSpec ivObj = new IvParameterSpec(Arrays.copyOf(key, 16));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, keyObj, ivObj);
byte[] byteCipherText = cipher.doFinal(message.getBytes());
return Base64.getEncoder().encodeToString(byteCipherText);
}catch(Exception e){
throw new RuntimeException(e);
}
}
複合
public static String decrypt(String passwd, String cryptText){
try{
byte[] key = passwd.getBytes();
MessageDigest sha = MessageDigest.getInstance("SHA-256");
key = sha.digest(key);
key = Arrays.copyOf(key, 32);
SecretKeySpec keyObj = new SecretKeySpec(key, "AES");
IvParameterSpec ivObj = new IvParameterSpec(Arrays.copyOf(key, 16));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, keyObj, ivObj);
byte[] cipherBytes = Base64.getDecoder().decode(cryptText);
byte[] byteDecryptedText = cipher.doFinal(cipherBytes);
return new String(byteDecryptedText);
}catch(Exception e){
throw new RuntimeException(e);
}
}
Java8では、このままでは、java.security.InvalidKeyException: Illegal key size
となってしまうので、
JCEポリシーの制限を無くすために下記から policy の JAR をダウンロード
Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files for JDK/JRE 8 Download
jre/lib/security の下の
local_policy.jar
US_export_policy.jar
を置き換える。
Java9 では、
Security.getProperty("crypto.policy");
の結果が、 unlimited であるので、Java8のように置き換えは不要。
Security.setProperty("crypto.policy", "limited")
を実行すれば、制限かかって、InvalidKeyException になる。