I am working on data encryption sample code provided by Apple in the "Certificate, Key and Trust Programming guide". The sample code for encrypting/decrypting data considers an uint8_t
. However the real world application would be doing this on an NSString
object. I have been trying to convert NSString
object to uint8_t
but every-time I try I get a compiler warning. Solutions given for 'almost' same problems given in various forums, don't seem to work for me.
Here is an example of turning any string value into a uint8_t*
. The easiest way is to just cast the bytes of NSData as and uint8_t*. Other option is to allocate memory and copy the bytes but you will still need to track the length somehow.
NSData *someData = [@"SOME STRING VALUE" dataUsingEncoding:NSUTF8StringEncoding];
const void *bytes = [someData bytes];
int length = [someData length];
//Easy way
uint8_t *crypto_data = (uint8_t*)bytes;
//If you plan on using crypto_data as a class variable
// you will need to do a memcpy since the NSData someData
// will get autoreleased
crypto_data = malloc(length);
memcpy(crypto_data, bytes, length);
//work with crypto_data
//free crypto_data most likely in dealloc
free(crypto_data);
NSString *stringToEncrypt = @"SOME STRING VALUE";
uint8_t *cString = (uint8_t *)stringToEncrypt.UTF8String;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With