How to implement random_bytes(16) from PHP in iOS Objective C?

192 views Asked by At

I want to Implement random_bytes(16) in Objective C, In PHP output string is something like this:

d�g���&���$�

I tried this code for Objective C:

uint8_t randomBytes[16];
int result = SecRandomCopyBytes(kSecRandomDefault, 16, randomBytes);
NSString *iv = [NSString stringWithFormat:@"%s",randomBytes];

But this is not like PHP output.
Please help me.

1

There are 1 answers

0
NSDestr0yer On

In the PHP output, the � character is used to replace an unknown or unrepresented character. In order to print the output of raw bytes you will need to convert them to a readable format such as HEX or Base64, for example. If you just print the raw bytes directly, the output may differ depending on the environment. So the best way to compare between different environments is to convert them first and then do the comparison. So for HEX, in PHP, this can be done fairly easily using bin2hex

$bytes = random_bytes(16);
var_dump(bin2hex($bytes));

In your iOS environment you already have from your code above:

uint8_t randomBytes[16];
int result = SecRandomCopyBytes(kSecRandomDefault, 16, randomBytes);

To convert that array of bytes into a string showing the hex representation:

CFMutableStringRef mutableString = CFStringCreateMutable(kCFAllocatorDefault, 16);
for (CFIndex i = 0; i < 16; i++)
 {
     // Add a dash every four bytes, for readability. My newer PHP environment didn't have the dashes in the output so you may skip this part if yours is the same
     if (i != 0 && i%4 == 0)
     {
         CFStringAppend(mutableString, CFSTR("-"));
     }

     CFStringAppendFormat(mutableString, 0, CFSTR("%02x"), randomBytes[i]);
 }

//Now you can print mutableString.
//Usually when I work in the C Security Framework/Core Foundation level I stay at that level, hence the Core Foundation code (CFMutableStringRef).
//However, the question asks about Objective-C. So to get your Objective-C/Foundation NSString * object you can simply toll-free bridge
NSString *objectiveCString = [NSString stringWithString:(__bridge NSString *)mutableString];
CFRelease(mutableString);

//...