[英]How to encrypt java Strings in C considering their size difference?
晚上好,我正在構建一個 java 項目,它通過 JNI 與英特爾 SGX 飛地通信,並看到它發送的信息被飛地密封。
但是,解密信息會返回我無法理解的信息,在這一點上,我認為這是由於大小差異造成的,但我並不完全理解。
所以,我知道Sizeof(char*)
相當於 1 個字節,就像sizeof(jbyte)
一樣。 但是, sizeof(jchar)
相當於 2 個字節。
了解這些知識后,我決定通過使用 JByteArray 來實現密封(或加密)function 以規避此問題。 這個 byte[] 應該是 UTF-8 還是 UTF-16? 對function整體有影響嗎?
這是我所做的一個例子:
JNIEXPORT jbyteArray JNICALL Java_sgxUtils_SgxFunctions_jni_1sgx_1seal_1info
(JNIEnv * env, jobject, jbyteArray jArray){
//Create a char* from the given byte array.
jbyte *b = env->GetByteArrayElements(jArray,NULL);
int StringSize = env->GetArrayLength(jArray);
char* c = (char*)malloc(sizeof(char) * StringSize);
memcpy(c,b,StringSize);
//Calculate the size of the encryption.
size_t sealed_size = sizeof(sgx_sealed_data_t) + StringSize;
//Create a uint8_t pointer to store the sealed information
uint8_t* sealed_data = (uint8_t*)malloc(sealed_size);
sgx_status_t ecall_status; //Store the status of the ecall.
seal(global_eid, &ecall_status,(uint8_t*)&c,StringSize, sgx_sealed_data_t*)sealed_data,sealed_size);
//Produce the jbyteArray to return:
jbyte* jresult = (jbyte*)calloc(sizeof(jbyte),sealed_size);
for(int i = 0 ; i < sealed_size ;i++){
jresult[i] = (jbyte)sealed_data[i];
}
jbyteArray jArray2 = env->NewByteArray(sealed_size+1);
env->SetByteArrayRegion(jArray2,0,sealed_size,jresult);
return jArray2;
使用 uint8_t 會影響密封嗎? 我不知道它可能是什么。 我在java中收到這個byte[]的方式如下:
byte[] c = sgx.jni_sgx_seal_info("toEncrypt".getBytes(Charset.forName("UTF-8")));
String sealed = new String(c,StandardCharsets.UTF_8);
有誰知道什么會影響這個? 解封(解密)后的output目前為 �|(�
您不能將隨機字節(例如加密產生的字節)轉換為UTF-8
(或許多多字節編碼,8 位單字節編碼就可以)。 字符串很可能會損壞,因為存在描述非法字符的字節序列,它們將被替換為0xFFFE
或 �
即 unicode 替換字符。
因此,您需要保留byte[]
並且在解密字節數組之前不要將其轉換為字符串,而不是字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.