原先的AES加密代码:
1public static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
2 SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
3 Cipher cipher = Cipher.getInstance("AES");
4 cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
5 byte[] encrypted = cipher.doFinal(clear);
6 return encrypted;
7 }
8
9 public static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
10 SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
11 Cipher cipher = Cipher.getInstance("AES");
12 cipher.init(Cipher.DECRYPT_MODE, skeySpec);
13 byte[] decrypted = cipher.doFinal(encrypted);
14 return decrypted;
15 }
16
17 public static byte[] getRawKey(byte[] seed) throws Exception {
18 KeyGenerator kgen = KeyGenerator.getInstance("AES");
19 SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
20 sr.setSeed(seed);
21 kgen.init(128, sr);
22 SecretKey skey = kgen.generateKey();
23 byte[] raw = skey.getEncoded();
24 return raw;
25 }
一切正常的在Android 4.3-6.1的手机上加解密,但是我用 LGE Nexus 5X (7.1.1 API 25)上发现在Android N上 google去掉了Crypto provider,意味着我们将不能继续像上面那样对数据加密填充。当然,在studio里的Logcat里会提示前往关于Android N对Crypto的解决方案:
解决方案:
将这句代码SecureRandom sr = SecureRandom.getInstance(“SHA1PRNG”, “Crypto”);
换成
SecureRandom sr = SecureRandom.getInstance(“SHA1PRNG”,new CryptoProvider());
CryptoProvider 是继承Provider的自定义的一个类。
1import java.security.Provider;
2/**
3 * Implementation of Provider for SecureRandom. The implementation supports the
4 * "SHA1PRNG" algorithm described in JavaTM Cryptography Architecture, API
5 * Specification & Reference
6*/
7public final class CryptoProvider extends Provider {
8 /**
9 * Creates a Provider and puts parameters
10 */
11public CryptoProvider() {
12 super("Crypto", 1.0, "HARMONY (SHA1 digest; SecureRandom; SHA1withDSA signature)");
13 put("SecureRandom.SHA1PRNG",
14 "org.apache.harmony.security.provider.crypto.SHA1PRNG_SecureRandomImpl");
15 put("SecureRandom.SHA1PRNG ImplementedIn", "Software");
16}
喜欢 就关注吧,欢迎投稿!
如有任何疑问可在文章底部留言。为了防止恶意评论,本博客现已开启留言审核功能。但是博主会在后台第一时间看到您的留言,并会在第一时间对您的留言进行回复!欢迎交流!
本文链接: https://leetcode.jp/android-n手机aes加密提示no-such-provider-crypto/