0 Replies Latest reply: Mar 13, 2013 9:45 AM by 996648 RSS

    passing byte array from c+= to java

      when i pass byte array from c++ to java i see in the java function that the byte array is longer with 1 byte

      I am trying to encrypt in java, a buffer sent from c++

      does anybody know why?

      here is the c++ func:

      JNIEXPORT void JNICALL Java_com_example_javabridge_Callbacks_nativeMethod(JNIEnv *env, jobject obj)
      __android_log_write(ANDROID_LOG_INFO, "Zx", "start");

      char pText[] = "you woke up in the middle of the night the fear was calling your name this huge red dragon";

      __android_log_print(ANDROID_LOG_INFO, "Zx", "original buf = %s", pText);

      char pKey[] = "0123456789123456";
      char pIv[] = "this-is-iv-this-";

      jsize nTextLen = sizeof(pText);
      jsize nKeyLen = sizeof(pKey);
      jsize nIvLen = sizeof(pIv);

      jclass cls = (*env)->GetObjectClass(env, obj);

      jmethodID midEncrypt = (*env)->GetStaticMethodID(env, cls, "Encrypt", "([BI[B[B[B)I");

      if (midEncrypt == 0)
        __android_log_write(ANDROID_LOG_ERROR, "Zx", "didnt find encrypt method");

      jbyteArray jBufIn = (*env)->NewByteArray(env, nTextLen);
      jbyteArray jKey = (*env)->NewByteArray(env, nKeyLen);
      jbyteArray jIv = (*env)->NewByteArray(env, nIvLen);
      jbyteArray jBufOut = 0;

      (*env)->SetByteArrayRegion(env, jBufIn, 0, nTextLen, (jbyte*)pText);
      (*env)->SetByteArrayRegion(env, jKey, 0, nKeyLen, (jbyte*)pKey);
      (*env)->SetByteArrayRegion(env, jIv, 0, nIvLen, (jbyte*)pIv);

      jint nBufOutLen = (*env)->CallStaticIntMethod (env, cls, midEncrypt, jBufIn, nTextLen, jKey, jIv, jBufOut);

      __android_log_write(ANDROID_LOG_INFO, "AE2", "end of function");

      Here is the java func:

      public static int Encrypt(byte[] pBufIn, int nBufInLen, byte[] pKey, byte[] pIv, byte[] pBufOut)

      SecretKeySpec key = new SecretKeySpec(pKey, "AES");
      IvParameterSpec ivSpec = new IvParameterSpec(pIv);
      int nBufOutLen = 0;

      Cipher cipher = Cipher.getInstance("AES");
      cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
      nBufOutLen = cipher.doFinal(pBufIn, 0, nBufInLen, pBufOut, 0);
      catch (Exception ex)


      return nBufOutLen;