由于项目的优化改进,用到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
解决方案:
`<span class="typ">SecureRandom</span><span class="pln"> sr </span><span class="pun">=</span> <span class="typ">SecureRandom</span><span class="pun">.</span><span class="pln">getInstance</span><span class="pun">(</span><span class="str">"SHA1PRNG"</span><span class="pun">,</span> <span class="kwd">new</span> <span class="typ">CryptoProvider</span><span class="pun">());</span>`
代替
`<span class="typ">SecureRandom</span><span class="pln"> sr </span><span class="pun">=</span> <span class="typ">SecureRandom</span><span class="pun">.</span><span class="pln">getInstance</span><span class="pun">(</span><span class="str">"SHA1PRNG"</span><span class="pun">,</span><span class="str">"Crypto"</span><span class="pun">);</span>`
💬 评论