Android AES加解密(兼容Android7.0)

Android 7.0及以上 AES加密报错:

1
New versions of the Android SDK no longer support the Crypto provider.

原因在于生成 AES加密密钥时,在 Axndroid N 上已经将相关的 Crypto providerSHA1PRNG 算法同时废弃掉了,并计划在后续的 SDK 中完全移除相关的库。

增加 CryptoProvider 类

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
/**
* Aes密钥处理
* @param seed
* @return
* @throws Exception
*/
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance(AES);
//for android
SecureRandom sr = null;
// 在4.2以上版本中,SecureRandom获取方式发生了改变
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sr = SecureRandom.getInstance(SHA1PRNG, "Crypto");
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
sr = SecureRandom.getInstance(SHA1PRNG, new CryptoProvider());
} else {
sr = SecureRandom.getInstance(SHA1PRNG);
}
// for Java
// secureRandom = SecureRandom.getInstance(SHA1PRNG);
sr.setSeed(seed);
kgen.init(128, sr); //256 bits or 128 bits,192bits
//AES中128位密钥版本有10个加密循环,192比特密钥版本有12个加密循环,256比特密钥版本则有14个加密循环。
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}

// 增加 CryptoProvider 类
public static class CryptoProvider extends Provider {
/**
* Creates a Provider and puts parameters
*/
public CryptoProvider() {
super("Crypto", 1.0, "HARMONY (SHA1 digest; SecureRandom; SHA1withDSA signature)");
put("SecureRandom.SHA1PRNG", "org.apache.harmony.security.provider.crypto.SHA1PRNG_SecureRandomImpl");
put("SecureRandom.SHA1PRNG ImplementedIn", "Software");
}
}

Google 终极推荐

参考:[Android 7.0后加密库Crypto被废弃后填坑](http://www.appblog.cn/2018/08/09/Android 7.0后加密库Crypto被废弃后填坑/ “Android 7.0后加密库Crypto被废弃后填坑”)

开源 AES加解密库

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :