示例代码:使用Android Keystore系统加密、解密文件
// 生成密钥并保存到Keystore中 KeyGenerator keyGenerator = KeyGenerator.getInstance( KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT); builder.setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7); keyGenerator.init(builder.build()); keyGenerator.generateKey();
// 加密文件 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); cipher.init(Cipher.ENCRYPT_MODE, getKey(), new IvParameterSpec(getIV())); try (CipherOutputStream cipherOutputStream = new CipherOutputStream(new BufferedOutputStream( new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "encrypted_file"))), cipher)) { IOUtils.copy(new FileInputStream(new File(Environment.getExternalStorageDirectory(), "plain_file")), cipherOutputStream); }
// 解密文件 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); cipher.init(Cipher.DECRYPT_MODE, getKey(), new IvParameterSpec(getIV())); try (CipherInputStream cipherInputStream = new CipherInputStream(new BufferedInputStream( new FileInputStream(new File(Environment.getExternalStorageDirectory(), "encrypted_file"))), cipher)) { IOUtils.copy(cipherInputStream, new FileOutputStream(new File( Environment
上一篇:Android界面:在EditText获取焦点后屏幕旋转时,浮动操作按钮被软键盘遮挡。
下一篇:Android解密抛出java.security.InvalidAlgorithmParameterException:在CBC模式下必须指定IV。