如何在JNI中实现

时间:2013-05-25 18:19:24

标签: java android cryptography java-native-interface 3des

如何在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;
}

app崩溃

(*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);

提前致谢

1 个答案:

答案 0 :(得分:1)

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

此外,在Java方法的调用之间你应该这样做:

if (env->ExceptionCheck()) {
    // Optionally log something here.
    return NULL;
}

在这种特定情况下,您似乎正在使用Cipher#init的错误函数原型。 IvParameterSpecAlgorithmParameterSpec而非AlgorithmParameters的实例,因此您需要使用原型(ILjava/security/Key;Ljava/security/spec/AlgorithmParameterSpec;)V