Android N手机AES加密提示no such provider: Crypto

android studio 相关说明 | 2018-10-26 20:24

原先的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    }1617    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 parameters10 */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}

喜欢 就关注吧,欢迎投稿!