AESで文字列を暗号化してみます。
暗号化した後、BASE64で文字列を出力。復号します。
AESですので、暗号強度は十分だと思います。
サンプルコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class CryptTest { public static String encode(String str,String encKey,String iVec,String charset) { try { SecretKeySpec key = new SecretKeySpec(encKey.getBytes(charset), "AES"); IvParameterSpec iv = new IvParameterSpec(iVec.getBytes(charset)); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, iv); byte[] byteResult = cipher.doFinal(str.getBytes(charset)); return Base64.getEncoder().encodeToString(byteResult); } catch (Exception e) { } return null; } public static String decode(String str,String encKey,String iVec,String charset) { try { SecretKeySpec key = new SecretKeySpec(encKey.getBytes(charset), "AES"); IvParameterSpec iv = new IvParameterSpec(iVec.getBytes(charset)); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key, iv); byte[] byteResult = cipher.doFinal(Base64.getDecoder().decode(str)); return new String(byteResult, charset); } catch (Exception e) { } return null; } public static void main(String[] args) { String str = "aaaaaa"; String encKey = "0123012301230123"; String iVec = "1234567890123456"; String charset = "UTF-8"; //encode System.out.println(encode(str,encKey,iVec,charset)); //decode System.out.println(decode(encode(str,encKey,iVec,charset),encKey,iVec,charset)); } } |