由于项目的优化改进,用到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");
import java.security.Provider;
/**
* Implementation of Provider for SecureRandom. The implementation supports the
* "SHA1PRNG" algorithm described in JavaTM Cryptography Architecture, API
* Specification & Reference
*/
public final 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");
}
}