-2

如何在 JNI 中实现这个功能?

public byte[] decrypt(byte[] enc) throws Exception{
    Cipher c3des = Cipher.getInstance("DESede/CBC/PKCS5Padding");
    SecretKeySpec    myKey = new SecretKeySpec(key, "DESede");
    IvParameterSpec ivspec = new IvParameterSpec(initializationVector);
    c3des.init(Cipher.DECRYPT_MODE, myKey, ivspec);
    byte[] cipherText = c3des.doFinal(enc);
    return cipherText;
}

我写了几乎所有的方法,但最后两行有问题:

jbyteArray Java_MainActivity_decrypt(JNIEnv* env, jobject context,jbyteArray key, jbyteArray iv, jbyteArray enc) {


   //Cipher c3des = Cipher.getInstance("DESede/CBC/PKCS5Padding");
   jclass cl = (*env)->FindClass(env,"javax/crypto/Cipher");
   jmethodID MID = (*env)->GetStaticMethodID(env,cl, "getInstance", "(Ljava/lang/String;)Ljavax/crypto/Cipher;");
   jstring s = (*env)->NewStringUTF(env,"DESede/CBC/PKCS5Padding");
   jobject c3des = (*env)->CallStaticObjectMethod(env,cl, MID, s);

   //SecretKeySpec    myKey = new SecretKeySpec(key, "DESede");
   jclass cl1 = (*env)->FindClass(env, "javax/crypto/spec/SecretKeySpec");
   jclass constructor1 = (*env)->GetMethodID(env, cl1, "<init>", "([BLjava/lang/String;)V");
   jstring s1 = (*env)->NewStringUTF(env,"DESede");
   jobject myKey = (*env)->NewObject(env, cl1, constructor1, key, s1);

   //IvParameterSpec ivspec = new IvParameterSpec(initializationVector);
   jclass cl2 = (*env)->FindClass(env, "javax/crypto/spec/IvParameterSpec");
   jclass constructor2 = (*env)->GetMethodID(env, cl2, "<init>", "([B)V");
   jobject ivspec = (*env)->NewObject(env, cl2, constructor2, iv);

   //c3des.init(Cipher.DECRYPT_MODE, myKey, ivspec);
   jmethodID mid_int = (*env)->GetMethodID(env, cl, "init","(ILjava/security/Key;Ljava/security/AlgorithmParameters;)V");
   jfieldID field_dec_id = (*env)->GetStaticFieldID(env, cl, "DECRYPT_MODE","I");
   jint field_dec = (*env)->GetStaticIntField(env, cl, field_dec_id);
   (*env)->CallVoidMethod(env,c3des,mid_int,field_dec,myKey,ivspec); //<--app crash at this line

   return;
}

应用程序崩溃

(*env)->CallVoidMethod(env,c3des,mid_int,field_dec,myKey,ivspec);

myKey 和 ivspec 没问题,我可以返回它们并在 java 中解密:

Cipher c3des = Cipher.getInstance("DESede/CBC/NoPadding");
c3des.init(Cipher.DECRYPT_MODE, myKey, ivspec);
byte[] cipherText = c3des.doFinal(enc);

提前致谢

4

1 回答 1

1

您应该按照Android JNI 提示页面(即)中的说明启用扩展 JNI 检查adb shell setprop debug.checkjni 1。或者,您可以在已经启用 CheckJNI 工具的模拟器上运行您的代码。通常,启用该功能后,查看 logcat 输出将为您提供 JNI 调用崩溃的确切原因。

此外,在调用 Java 方法之间,您应该执行以下操作:

if (env->ExceptionCheck()) {
    // 可选择在此处记录一些内容。
    返回空值;
}

在这种特定情况下,您似乎使用了错误的函数原型Cipher#initIvParameterSpecAlgorithmParameterSpecand not的一个实例AlgorithmParameters,因此您需要改用原型(ILjava/security/Key;Ljava/security/spec/AlgorithmParameterSpec;)V

于 2013-05-26T18:45:59.290 回答