unsigned char to string
Dec 30, 2015 at 8:09pm UTC
I'm looking at using openSSL. They use unsigned char in the functions. I'm trying out some conversions with the following:
<
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>
#define KEY_LEN 16
#define ITERATION 1000
using namespace std;
int main()
{
int itt;
size_t szsaltlen, szcpwdlen;
string str;
char cpwd[] = "magicdemon" ;
szcpwdlen = strlen(cpwd);
unsigned char salt_value[] = {'s' ,'a' ,'l' ,'t' };
szsaltlen = sizeof (salt_value);
unsigned char * ucOut;
ucOut = (unsigned char *) malloc(sizeof (unsigned char ) * KEY_LEN +1);
unsigned char uchr[KEY_LEN+1];
if ( PKCS5_PBKDF2_HMAC_SHA1(cpwd, szcpwdlen, salt_value, szsaltlen, ITERATION, KEY_LEN, ucOut) != 0 )
{
printf("initvector direct out:\n" );
for (itt=0;itt<KEY_LEN;itt++) {
printf("%02x" , ucOut[itt]);
uchr[itt] = ucOut[itt];
str += ucOut[itt];
}
printf("\n" );
uchr[itt] = '\0' ;
}else {
printf("error\n" );
return 1;
}
for (itt=0; itt<16; itt++){
str += uchr[itt];
}
cout << "uchr cout: " << uchr << endl;
printf("uchr hex: " );
for (itt=0; itt<16; itt++){ printf("%02x" , uchr[itt]); }
printf("\n" );
cout << "str cout: " << str << endl;
printf("str hex: " );
for (itt=0; itt<16; itt++){ printf("%02x" , str[itt]); }
printf("\n" );
return 0;
}
>
the output is:
$ ./uc2string
initvecor direct out:
20bb6ec86902d8d1ce259d4cf234d8be
uchr cout: �n�i���%�L�4ؾ
uchr hex: 20bb6ec86902d8d1ce259d4cf234d8be
str cout: �n�i���%�L�4ؾ �n�i���%�L�4ؾ
str hex: 20ffffffbb6effffffc86902ffffffd8ffffffd1ffffffce25ffffff9d4cfffffff234ffffffd8ffffffbe
I understand all except the str hex: output has me headscratching. Does anyone know what's going on? and, what may be the best string container to use with the 'unsigned char' of openSSL? (I'm thinking char cast to unsigned char may be the easiest)
I will be using Linux and Windows with CodeBlocks, and/or CodeLite with wxWidgets.
Thank you all.
Last edited on Dec 30, 2015 at 8:16pm UTC
Dec 31, 2015 at 1:55pm UTC
You are experiencing sign extension on the str hex: output. Because the uchr is unsigned, you won't see the ffffff string; but with str, the sign is shown by the ffffffs.
Topic archived. No new replies allowed.