技术联盟

Android java.security.NoSuchProviderException: no such provider: Crypto

由于项目的优化改进,用到AES+RSA加密传输数据。于是,在网上摘录了网友们的AES算法,如下:
public static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(clear);
        return encrypted;
    }

    public static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }

    public static byte[] getRawKey(byte[] seed) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
        sr.setSeed(seed);
        kgen.init(128, sr);
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();
        return raw;
    }
一切正常的在Android 4.3-6.1的手机上加解密,但是我用 LGE Nexus 5X (7.1.1 API 25)上发现在Android N上 google去掉了Crypto provider,意味着我们将不能继续像上面那样对数据加密填充。当然,在studio里的Logcat里会提示前往关于Android N对Crypto的解决方案:

http://Android-developers.blogspot.com/2016/06/security-crypto-provider-deprecated-in.html

解决方案:

SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", new CryptoProvider());

代替

SecureRandom sr = SecureRandom.getInstance("SHA1PRNG","Crypto");

[java] view plain copy

  1. import 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. */
  7. public final class CryptoProvider extends Provider {
  8.     /**
  9.  * Creates a Provider and puts parameters
  10.  */
  11. public 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. }
  17. }

Share this:

码字很辛苦,转载请注明来自技术联盟《Android java.security.NoSuchProviderException: no such provider: Crypto》

评论