Android AES 加密、解密

private byte[] decrypt(byte[] content, SecretKey secretKey) throws Exception {

// 秘钥

byte[] enCodeFormat = secretKey.getEncoded();

// 创建AES秘钥

SecretKeySpec key = new SecretKeySpec(enCodeFormat, “AES”);

// 创建密码器

Cipher cipher = Cipher.getInstance(“AES”);

// 初始化解密器

cipher.init(Cipher.DECRYPT_MODE, key);

// 解密

return cipher.doFinal(content);

}

通常,如果加密和解密都是在同一个平台,比较简单,我们生成一个秘钥以后,将秘钥保存到本地,解密的时候直接获取本地的秘钥来解密就可以了,通常的使用场景为本地将xxx文件加密后上传保存或备份,需要的时候,下载再解密。这样上传的文件比较安全。

看上去很完美,下面问题来了,上述生产秘钥的方法,每次执行生成的秘钥都是不一样的。也就是说,加密时的秘钥如果没有保存到本地,解密的时候再次调用上述方法生成一个秘钥,那么将无法解密。

解决办法也有,使用如下方式生成秘钥,只要种子一样,生成的秘钥就是一样的。

private SecretKey generateKey(String seed) throws Exception {

// 获取秘钥生成器

KeyGenerator keyGenerator = KeyGenerator.getInstance(“AES”);

// 通过种子初始化

SecureRandom secureRandom = SecureRandom.getInstance(“SHA1PRNG”, “Crypto”);

secureRandom.setSeed(seed.getBytes(“UTF-8”));

keyGenerator.init(128, secureRandom);

// 生成秘钥并返回

return keyGenerator.generateKey();

}

但是Android N(7.0)以后将不再支持,移除了Crypto

E/System: ********** PLEASE READ ************

E/System: *

E/System: * New versions of the Android SDK no longer support the Crypto provider.

E/System: * If your app was relying on setSeed() to derive keys from strings, you

E/System: * should switch to using SecretKeySpec to load raw key bytes directly OR

E/System: * use a real key derivation function (KDF). See advice here :

E/System: * http://android-developers.blogspot.com/2016/06/security-crypto-provider-deprecated-in.html

E/System: ***********************************

W/System.err: java.security.NoSuchProviderException: no such provider: Crypto

Google也对应给出了解决方案,详见 Security “Crypto” provider deprecated in Android N

下面介绍另一种解决方案,我们不用种子生成秘钥,直接将password作为秘钥。

关于Android和IOS的同步问题,小伙伴也可以借鉴 AES加密 - iOS与Java的同步实现

如下方法 Android测试可行,IOS如果有小伙测试有问题也可以反馈给我。

加密

private byte[] encrypt(String content, String password) throws Exception {

// 创建AES秘钥

SecretKeySpec key = new SecretKeySpec(password.getBytes(), “AES/CBC/PKCS5PADDING”);

// 创建密码器

Cipher cipher = Cipher.getInstance(“AES”);

// 初始化加密器

cipher.init(Cipher.ENCRYPT_MODE, key);

// 加密

return cipher.doFinal(content.getBytes(“UTF-8”));

}

解密

private byte[] decrypt(byte[] content, String password) throws Exception {

// 创建AES秘钥

SecretKeySpec key = new SecretKeySpec(password.getBytes(), “AES/CBC/PKCS5PADDING”);

// 创建密码器

Cipher cipher = Cipher.getInstance(“AES”);

// 初始化解密器

cipher.init(Cipher.DECRYPT_MODE, key);

// 解密

return cipher.doFinal(content);

}

**注意:**必须必须要注意的是,这里的password的长度,必须为128192256bits.也就是162432byte。否则会报出如下错误:

com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher$1: Key length not 128/192/256 bits.

至于数字、字母、中文都各自占几个字节,相信小伙伴的都是了解的,就不废话了。
也可以byte[] password = new byte[16/24/32];
最后:至于最开始提到生成秘钥的方法,为什么种子相同,所生成的秘钥不同,还没看具体实现。有知道的小伙伴还请先指点一二。

最后

给大家分享一份移动架构大纲,包含了移动架构师需要掌握的所有的技术体系,大家可以对比一下自己不足或者欠缺的地方有方向的去学习提升;

参考docs.qq.com/doc/DSkNLaERkbnFoS0ZF
同,还没看具体实现。有知道的小伙伴还请先指点一二。

最后

给大家分享一份移动架构大纲,包含了移动架构师需要掌握的所有的技术体系,大家可以对比一下自己不足或者欠缺的地方有方向的去学习提升;

[外链图片转存中…(img-1lwPmuf9-1724066138540)]

参考docs.qq.com/doc/DSkNLaERkbnFoS0ZF

好的,这里是一个简单的示例,展示了如何在 Android 中使用 AES 加密解密文件: ```java import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.FileInputStream; import java.io.FileOutputStream; import java.security.MessageDigest; import java.util.Arrays; public class AesUtil { private static final String ALGORITHM = "AES/CBC/PKCS5Padding"; private static final String SECRET_KEY = "my_secret_key"; private static final String IV = "my_initialization_vector"; public static void encrypt(String inputFile, String outputFile) throws Exception { SecretKeySpec secretKeySpec = generateKey(SECRET_KEY); IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes("UTF-8")); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); FileInputStream inputStream = new FileInputStream(inputFile); FileOutputStream outputStream = new FileOutputStream(outputFile); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { byte[] output = cipher.update(buffer, 0, bytesRead); if (output != null) { outputStream.write(output); } } byte[] output = cipher.doFinal(); if (output != null) { outputStream.write(output); } inputStream.close(); outputStream.close(); } public static void decrypt(String inputFile, String outputFile) throws Exception { SecretKeySpec secretKeySpec = generateKey(SECRET_KEY); IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes("UTF-8")); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); FileInputStream inputStream = new FileInputStream(inputFile); FileOutputStream outputStream = new FileOutputStream(outputFile); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { byte[] output = cipher.update(buffer, 0, bytesRead); if (output != null) { outputStream.write(output); } } byte[] output = cipher.doFinal(); if (output != null) { outputStream.write(output); } inputStream.close(); outputStream.close(); } private static SecretKeySpec generateKey(String key) throws Exception { byte[] keyBytes = key.getBytes("UTF-8"); MessageDigest sha = MessageDigest.getInstance("SHA-256"); keyBytes = sha.digest(keyBytes); keyBytes = Arrays.copyOf(keyBytes, 16); return new SecretKeySpec(keyBytes, "AES"); } } ``` 在此示例中,我们使用 AES/CBC/PKCS5Padding 加密模式和 SHA-256 哈希算法生成密钥。我们将密钥和初始向量 IV 保存为常量,但您可以根据需要进行更改。 要使用此示例,请在您的代码中调用 `AesUtil.encrypt(inputFile, outputFile)` 或 `AesUtil.decrypt(inputFile, outputFile)` 方法,其中 `inputFile` 是要加密解密的文件路径,而 `outputFile` 是加密解密后的文件路径。 请注意,此示例中的加密解密操作是阻塞的,并且使用了相对较小的缓冲区。对于大文件和需要异步处理的情况,您需要进行适当的优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值