AndroidでAESの暗号化する
import javax.crypto.*; import java.security.KeyFactory; import java.security.Key; import java.security.spec.X509EncodedKeySpec; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.spec.InvalidKeySpecException; import java.security.NoSuchAlgorithmException; import java.security.InvalidAlgorithmParameterException; import java.security.spec.AlgorithmParameterSpec; import android.util.Base64; import java.io.InputStream; import java.util.Random; public class HogeCipher{ private static final String keyString = "aaaabbbbccccddddaaaabbbbccccdddd"; //固定でもつ public String encryptString(String ivString, String input) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{ byte[] ivBytes = ivString.getBytes("UTF-8"); byte[] keyBytes = this.keyString.getBytes("UTF-8"); return Base64.encodeToString(this.encryptAES(ivBytes, keyBytes, input.getBytes("UTF-8")), Base64.DEFAULT); } public byte[] encryptAES(byte[] iv, byte[] key, byte[] enc) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{ AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv); SecretKeySpec newKey = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec); return cipher.doFinal(enc); } public byte[] decryptAES(byte[] iv, byte[] key, byte[] dec) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{ AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv); SecretKeySpec newKey = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, newKey); return cipher.doFinal(dec); } }
動作確認はしていない