I have created one project in spring boot in which i have integrated one library which is used to generate keys, encrypt and decrypt so i have deleveloped rest apis which will do these 3 functionalities but i am not getting correct encrypt and decrypt msg if i pass the samecipher text to decrypt i am not getting original plain text please review the code and tell me what is wrong
// Rename function pointers to avoid conflict with kyber_API.h
typedef void (keygen_fn_ptr)(uint8_t, uint8_t*);
typedef void (encrypt_fn_ptr)(uint8_t, uint8_t*, uint16_t*);
typedef void (decrypt_fn_ptr)(uint8_t, uint8_t*, uint16_t*);
// Global function pointers with new names
keygen_fn_ptr keygeneration_ptr = nullptr;
encrypt_fn_ptr encryption_ptr = nullptr;
decrypt_fn_ptr decryption_ptr = nullptr;
// Handle for the dynamically loaded library
HMODULE handle = nullptr;
// JNI_OnLoad: Called when the native library is loaded
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
printf("JNI_OnLoad called: Loading the library...\n");
// Load the lib_kyber library
// char* projectRoot = getenv("PROJECT_ROOT"); // Set PROJECT_ROOT as your project root
// if (projectRoot == nullptr) {
// fprintf(stderr, "Error: PROJECT_ROOT environment variable is not set.\n");
// return JNI_ERR; // Return error code
// }
// Construct the path to the Kyber .so file
char soPath[1024] = "";
// Start with the project root
strcat(soPath, "C:/Quantam/spring/Quantum/src/main/resources/libs/lib_kyber.dll"); // Change .so to .dll
// Load the Kyber .dll file
handle = LoadLibraryA(soPath);
if (!handle) {
// Print the error and the shared library path
fprintf(stderr, "Error loading Kyber library. Path: %s. Error: %lu\n", soPath, GetLastError());
return JNI_ERR; // Return error code
} else {
printf("kyber_lib loaded\n");
}
// Resolve the symbols for the Kyber functions
keygeneration_ptr = (keygen_fn_ptr)GetProcAddress(handle, "keygeneration");
encryption_ptr = (encrypt_fn_ptr)GetProcAddress(handle, "encryption");
decryption_ptr = (decrypt_fn_ptr)GetProcAddress(handle, "decryption");
if (!keygeneration_ptr || !encryption_ptr || !decryption_ptr) {
std::cerr << "Failed to load Kyber function symbols." << std::endl;
FreeLibrary(handle); // Clean up in case of failure
return JNI_ERR; // Return error code
}
printf("Library and function pointers loaded successfully.\n");
return JNI_VERSION_1_6; // Return the JNI version
}
// JNI_OnUnload: Called when the native library is unloaded
JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved) {
printf("JNI_OnUnload called: Unloading the library...\n");
// JNI wrapper for the keygeneration function
JNIEXPORT void JNICALL Java_com_kyber_quantum_QuantumWrapper_keygeneration(JNIEnv *env, jclass clazz, jobject pubKeyBuffer, jobject privKeyBuffer) {
printf("Key Generation called\n");
// Create buffers for public and private keys
uint8_t pubKey[1568];
uint8_t privKey[1536];
// Call the Kyber API keygeneration function
keygeneration_ptr(pubKey, privKey);
// Copy public key into ByteBuffer
uint8_t* pubKeyPtr = (uint8_t*)env->GetDirectBufferAddress(pubKeyBuffer);
if (pubKeyPtr == nullptr) {
std::cerr << "Error accessing public key ByteBuffer memory." << std::endl;
return;
}
std::memcpy(pubKeyPtr, pubKey, sizeof(pubKey));
// Copy private key into ByteBuffer
uint8_t* privKeyPtr = (uint8_t*)env->GetDirectBufferAddress(privKeyBuffer);
if (privKeyPtr == nullptr) {
std::cerr << "Error accessing private key ByteBuffer memory." << std::endl;
return;
}
std::memcpy(privKeyPtr, privKey, sizeof(privKey));
}
// JNI wrapper for the encryption function
JNIEXPORT void JNICALL Java_com_kyber_quantum_QuantumWrapper_encryption(JNIEnv *env, jclass clazz, jbyteArray pubKey, jobject cipherBuffer, jbyteArray message) {
printf("Encryption called\n");
// Get the public key array from Java
jbyte* pubKeyPtr = env->GetByteArrayElements(pubKey, NULL);
if (pubKeyPtr == nullptr) {
std::cerr << "Error accessing public key array." << std::endl;
return;
}
// Get the cipher buffer from Java
uint8_t* cipherPtr = (uint8_t*)env->GetDirectBufferAddress(cipherBuffer);
if (cipherPtr == nullptr) {
std::cerr << "Error accessing cipher ByteBuffer memory." << std::endl;
return;
}
// Get the message array from Java (should be passed as a byte array)
jbyte* messagePtr = env->GetByteArrayElements(message, NULL);
if (messagePtr == nullptr) {
std::cerr << "Error accessing message array." << std::endl;
return;
}
// Call the Kyber API encryption function
encryption_ptr((uint8_t*)pubKeyPtr, cipherPtr, (uint16_t*)messagePtr);
// Release JNI arrays
env->ReleaseByteArrayElements(pubKey, pubKeyPtr, 0);
env->ReleaseByteArrayElements(message, messagePtr, 0);
}
// JNI wrapper for the decryption function
JNIEXPORT void JNICALL Java_com_kyber_quantum_QuantumWrapper_decryption(JNIEnv *env, jclass clazz, jbyteArray privKey, jbyteArray cipher, jobject messageBuffer) {
printf("Decryption called\n");
// Get the private key array from Java
jbyte* privKeyPtr = env->GetByteArrayElements(privKey, NULL);
if (privKeyPtr == nullptr) {
std::cerr << "Error accessing private key array." << std::endl;
return;
}
// Get the cipher array from Java
jbyte* cipherPtr = env->GetByteArrayElements(cipher, NULL);
if (cipherPtr == nullptr) {
std::cerr << "Error accessing cipher array." << std::endl;
return;
}
// Get the message buffer from Java (should be passed as a direct ByteBuffer)
uint16_t* messagePtr = (uint16_t*)env->GetDirectBufferAddress(messageBuffer);
if (messagePtr == nullptr) {
std::cerr << "Error accessing message ByteBuffer memory." << std::endl;
return;
}
// Call the Kyber API decryption function
decryption_ptr((uint8_t*)privKeyPtr, (uint8_t*)cipherPtr, messagePtr);
// Release JNI arrays
env->ReleaseByteArrayElements(privKey, privKeyPtr, 0);
env->ReleaseByteArrayElements(cipher, cipherPtr, 0);
}
--- Entry 2 ---
Filename: com_kyber_quantum_QuantumWrapper.h
Path: cpp\com_kyber_quantum_QuantumWrapper.h
Content:
/* DO NOT EDIT THIS FILE - it is machine generated /
#include <jni.h>
/ Header for class com_kyber_quantum_QuantumWrapper */
Based on the provided code snippets and the issue you're encountering—decryption not recovering the original plaintext correctly—there are several potential areas that might be causing the problem. Below is a detailed analysis of your code along with recommendations to fix the issues.
1. Incorrect Parameter Naming and Usage in QuantumWrapper.java
Issue: Mismatch in Native Method Signatures
Encryption Method:
Current Declaration in QuantumWrapper.java:
public static native void encryption(byte[] privKey, ByteBuffer ciphertext, byte[] message);
Expected (Based on C++ JNI Signature):
// C++ expects: (jbyteArray pubKey, jobject cipherBuffer, jbyteArray message)
Problem: You are passing the private key (privKey) to the encryption function, whereas encryption should use the public key (pubKey).
Decryption Method:
Ensure that the decryption method correctly accepts the private key, ciphertext, and a buffer for the message.
Recommendation: Correct the Native Method Signatures
Update QuantumWrapper.java as follows:
public class QuantumWrapper {
// ...
// Corrected native method signatures
public static native void keygeneration(ByteBuffer pubKeyBuffer, ByteBuffer privKeyBuffer);
// Encryption should use pubKey, not privKey
public static native void encryption(byte[] pubKey, ByteBuffer ciphertext, byte[] message);
// Decryption should include privKey, cipher, and message buffer
public static native void decryption(byte[] privKey, byte[] cipher, ByteBuffer message);
// ...
}
Ensure Consistency Across All Calls:
When calling encryption, make sure you pass the public key.
When calling decryption, pass the private key along with the ciphertext and message buffer.
2. Handling of Message Data Types Between Java and C++
The encryption and decryption functions expect the message (messg) to be an array of uint16_t.
Java Side (QuantumWrapper.java and QuantumService.java):
Messages are handled as byte[], which are 8-bit, but C++ expects 16-bit (uint16_t) integers.
Problems This Causes:
Directly casting byte* to uint16_t* can lead to incorrect data interpretation, especially regarding byte ordering (endianness).
Potential data truncation or misalignment, especially if the message length doesn't align with 16-bit boundaries.
Recommendations:
Ensure Proper Data Conversion:
Java Side:
Convert byte[] to short[] (16-bit) before passing to the native method.
C++ Side:
If possible, modify the native methods to accept uint8_t arrays or handle the conversion appropriately.
Modify JNI Wrappers to Handle Data Correctly:
Example Conversion in Java:
public short[] convertBytesToShorts(byte[] bytes) {
if (bytes.length % 2 != 0) {
throw new IllegalArgumentException("Byte array length must be even");
}
short[] shorts = new short[bytes.length / 2];
ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts);
return shorts;
}
public byte[] convertShortsToBytes(short[] shorts) {
ByteBuffer byteBuffer = ByteBuffer.allocate(shorts.length * 2).order(ByteOrder.LITTLE_ENDIAN);
byteBuffer.asShortBuffer().put(shorts);
return byteBuffer.array();
}
Use These Methods When Interfacing with Native Code:
Before encryption/decryption, convert the message appropriately.
Alternatively, Modify C++ to Accept uint8_t*:
If possible, adjust the native C++ functions to handle uint8_t* directly, aligning with how data is managed in Java.
3. ByteBuffer Position Management
Issue: Improper Handling of ByteBuffer Positions
Problem: After native methods write to the ByteBuffer, the buffer’s position is at the end. When you call get(), it might not read the data correctly because the position is not reset.
Recommendation: Reset ByteBuffer Position Before Reading
After Native Method Calls:
ciphertext.rewind(); // Reset position to 0 before reading
byte[] cipher = new byte[ciphertext.capacity()];
ciphertext.get(cipher);
Similarly, for Decryption:
message.rewind(); // Reset position to 0 before reading
byte[] decryptedText = new byte[message.capacity()];
message.get(decryptedText);
Problem: If the decrypted message is expected to be larger (e.g., 64 bytes for 32 uint16_t elements), allocating only 32 bytes will lead to incomplete decryption.
Recommendation:
Allocate Sufficient Buffer Size:
Determine the exact size expected by the Kyber API for decrypted messages.
Adjust the buffer size accordingly. For example, if 32 uint16_t elements are expected:
By addressing the issues related to method signatures, data type mismatches, buffer management, and ensuring consistent handling of data between Java and C++, you should be able to resolve the encryption-decryption inconsistencies. Additionally, thorough logging and validation can help identify any remaining hidden issues.
If after these changes you still encounter problems, consider the following steps:
Unit Testing: Write unit tests for each component (key generation, encryption, decryption) to isolate and identify where the issue persists.
Library Documentation: Refer to the Kyber API documentation to ensure that all functions are used correctly.
Community Support: Reach out to the library maintainers or communities for specific insights related to the Kyber implementation.
Feel free to provide more details or logs if the issue persists after these changes, and I can assist you further.