MrJD
MrJD

Reputation: 1889

NSData encoding to Unicode returning nil

I am attempting to convert an HMAC (hashed data) to a string safe for urls for authentication purposes.

Im having problems converting data generated from sha256 hashing (using apples crypto library) to Unicode in both little and big Endian, one hashed string will work in big and not in little, and visa versa for a different hashed string. For some hashed strings it works perfectly. I think it may have something to do with an out of range character or something. When I say it doesn't work, I mean it returns nil.

The code looks like this:

NSString *mystring = [[NSString alloc] initWithData:myHash encoding:NSUnicodeEncoding

Is Unicode the best to use? I tried encoding to UTF8, it returns nil and ascii doesn't have all the characters, I get a few "?" where data is missing.

Really, my question is, how do I make A string from NSData from a sha256 hash?


Solution:

https://github.com/eczarny/xmlrpc

NSData+Base64.h and NSData+Base64.m

Upvotes: 0

Views: 1092

Answers (1)

Jonas Schnelli
Jonas Schnelli

Reputation: 10005

You first need to make a hex string out of your HMAC bytes. You can make it like this:

void bytes_to_hexstring(void *uuid, char *hex_string, size_t osize) {
    static const char hexdigits[] = "0123456789ABCDEF";
    const unsigned char* bytes = (unsigned char *)uuid;

    int i = 0;
    for (i = 0; i<osize; ++i) {
        const unsigned char c = *bytes++;
        *hex_string++ = hexdigits[(c >> 4) & 0xF];
        *hex_string++ = hexdigits[(c ) & 0xF];
    }
    *hex_string = 0;
}

char *mystring = malloc(41);
bytes_to_hexstring(myHash, mystring, 20);

something like this.

Upvotes: 1

Related Questions