目的:JNI反调Anroid下类实现RSA2048加解密
环境:
系统: Win10
环境: AndroidStudio 3.6.1
问题分析:
Android JNI开发过程中会遇到需要RSA2048加解密的情况。
解决方案:
1、c++使用openssl中的rsa加解密。
2、jni反射调用java上层的类来使用java.security.*加解密。 ---- 本例选用该方案。
1、完成java中的加解密类,代码如下:
package com.example.test;
import android.util.Base64;
import android.util.Log;
import javax.crypto.*;
import java.io.*;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* RSA2048, encrypt and decrypt.
*
* Fun1: RSA, encrypt by public key.
* Fun2: RSA, decrypt with private key.
*/
public class RSAEncryptDecrypt {
// rsa 1024
//private static int RSA_PRIVATE_ENCRYPT_MAX_SIZE = 117;
//private static int RSA_PRIVATE_DECRYPT_MAX_SIZE = 128;
// rsa 2048
private static int RSA_PRIVATE_ENCRYPT_MAX_SIZE = 256;
private static int RSA_PRIVATE_DECRYPT_MAX_SIZE = 256;
/**
* Fun1: RSA, encrypt by public key.
*
* @param data plainText
* @return cipherText
*/
public static byte[] publicRSAEncrypt(byte[] pubKey, byte[] data) {
if(pubKey == null || data == null || pubKey.length == 0 || data.length == 0){
Log.e("publicRSAEncrypt", "args are invalid.");
return null;
}
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(
new X509EncodedKeySpec(Base64.decode(pubKey, 0)));
// init public key
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// encrypt, 如果解密长度超过117/256, 需要分段加密 */
return Base64.encode