0

I need to encode an input string of type String16.For this I convert this string first into an ASCII byte array of type uint8_t and pass this input buffer to the encryption function which encrypts the input buffer and generates an encrypted output buffer also of type uint8_t. Now I need to convert this output buffer back to String16 and transmit the same on some binder interface .

As expected , the encrypted output buffer might contain valid NUL terminated characters (\0) .I first convert the encrypted byte array into a std:: string type and then eventually convert this string into String16 type using String16 finalString =String16(outputString.c_str()); But when I try to calculate the size of the final string using finalString.size() , I get a size of 1 as compared to the size of the output buffer .

This might be happening because in the encrypted buffer , the second element itself would be a \0 and hence the string terminates .

Do I need to use functions which convert ASCII/UTF-8 to UTF16 ? Here is the code snippet

#include <iostream>
#include <cstring>
#include <utils/String16.h>

using std::string;
using android::String16;
using android::String8;

Status MyFunc(const ::android::String16& msg, ::android::String16* _aidl_return) override
{
    uint8_t input_buffer[msg.size()];
    for (int i = 0; i != msg.size(); i++)
    {
        input_buffer[i] = msg[i];
        printf("%x \n", input_buffer[i]);
    }
    uint32_t ver_length = 8;
    uint32_t input_content_length = sizeof(input_buffer);
    uint32_t output_buf_length = input_content_length + ver_length;
    uint8_t *output_buf = (uint8_t *)calloc(output_buf_length, sizeof(uint8_t));
    encrypt_funct(&input_buffer[0], input_content_length, output_buf, &output_buf_length);
    std::string temp;
    for (int i = 0; i < output_buf_length; i++)
        temp.push_back((char)output_buf[i]);
    printf("Length of string temp is %d\n", temp.length());//I get correct length
    String16 finalString = String16(temp.c_str());
    printf("Length of finalString is %d\n", finalString.size());//I get length as 1
    return Status::ok();
}
Onik
  • 19,396
  • 14
  • 68
  • 91
  • 2
    I would encode the resulting encrypted data as base-64. This represents the binary values (including 0's) as textual data. – Paul Bentley May 03 '17 at 16:28
  • `uint8_t input_buffer[msg.size()];` that can't be right – Raxvan May 03 '17 at 16:56
  • @PaulBentley thanks for the suggestion . It worked for me when I converted encrypted array to base64 encoded string. – Sau_marvel May 04 '17 at 04:42
  • 1
    Happy to help! Could you please post the code you used as an edit to your question - to help others who have a similar issue in future? – Paul Bentley May 04 '17 at 06:42

0 Answers0