I am using pairing-based cryptography lib to implement an application. And I want to store the element by calling
int element_length_in_bytes(element_t e)
and
int element_to_bytes(unsigned char *data, element_t e)
The problem is that the value store in the type of unsigned char *
. So I don't know how to store it in a file.
I tried to cast it to char *
and used a lib called jsoncpp
to store. However the value is not correct when I use Json::Value((char *)data)
to keep. What should I do to solve this problem.
You need to first allocate some memory, and then pass the address of this allocated memory to the element_to_bytes() function, which will store the element in the memory that you allocated.
How do you know how many bytes to allocate? Use the element_length_in_bytes() for that.
int num_bytes = element_length_in_bytes(e);
/* Handle errors, ensure num_bytes > 0 */
char *elem_bytes = malloc(num_bytes * sizeof(unsigned char));
/* Handle malloc failure */
int ret = element_to_bytes(elem_bytes, e);
/* Handle errors by looking at 'ret'; read the PBC documentation */
At this point you have your element rendered as bytes sitting in elem_bytes. The simplest way to just write it to a file would be to use open()/write()/close(). If there is some specific reason why you have to use jsoncpp, then you have to read the documentation for jsoncpp about how to writing a byte array. Note that any method you call must ask for the number of bytes that are being written.
Using open()/write()/close() here is how you would do it:
int fd = open("myfile", ...)
write(fd, elem_bytes, num_bytes);
close(fd);
After you are done, you have to free up the memory you allocated:
free(elem_bytes);