问题描述:

I am working on a Cryptographic project, where several 1024 bit numbers (using GMP in C) are generated. These numbers are communicated via a Java program (the C file is called through JNI). I need those large numbers to be returned to the Java program. Now, data types are different mpz_t and BigInteger, so which native data type should be used?

网友答案:

C part.

#include <jni.h>

jbyteArray array(mpz_t *m) {
  const size_t size = sizeof (mpz_t);
  jbyteArray jbytes = (*env)->NewByteArray(env, (jsize) size);
  if (result != NULL) {
    jbyte *cbytes = (*env)->GetByteArrayElements(env, result, NULL);
    if (cbytes != NULL) {
      int i;
      for (i = (int) (size - 1); i >= 0; i--) {
        cbytes[i] = (jbyte) (*m & 0xFF);
        *m >>= 8;
      }
      (*env)->ReleaseByteArrayElements(env, result, cbytes, 0);
    }
  }
  return result;
}

JNIEXPORT jbyteArray JNICALL Java_Test_bytes(JNIEnv *env, jclass cls) {
  mpz_t *m = getSome();
  return array(m);
}

Java part.

static native byte[] bytes();

static BigInteger bigInteger() {
    final byte[] bytes = bytes();
    return bytes == null ? null : new BigInteger(1, bytes);
}

Note that the first argument 1 means a positive signum.

网友答案:

jbyteArray because BigInteger can be serialized and deserialized to/from Java byte[] and mpz_t can be serialized and deserialized to/from a structure that—without the header—seems like it would be same sequences of bytes.

相关阅读:
Top