Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a good way to generate a random string on iPhone?

Here's the code I came up with:

NSString *randomString = @"";
for (int x=0;x<NUMBER_OF_CHARS;x++) {
  randomString = [randomString stringByAppendingFormat:@"%c", (char)(65 + (arc4random() % 25))];
}
return randomString;

EDIT:

To answer the comments:

1) I'm mostly concerned with brevity of code.

2) I also wonder if this is secure against guessing the string, and/or proof against collisions, if NUMBER_OF_CHARS is a high number (say 40) - not for this application, but in other cases.

3) Also, is there is a faster way if I want to make a ton of strings some day? This seems like it will be slow, since it makes an object each time through the loop.

like image 666
Andrew Johnson Avatar asked Apr 20 '12 19:04

Andrew Johnson


2 Answers

If NUMBER_OF_CHARS is compile-time constant, you can speed up your code by avoiding repeated object creation. You can make your program shorter by one line, too:

char data[NUMBER_OF_CHARS];
for (int x=0;x<NUMBER_OF_CHARS;data[x++] = (char)('A' + (arc4random_uniform(26))));
return [[NSString alloc] initWithBytes:data length:NUMBER_OF_CHARS encoding:NSUTF8StringEncoding];

As far as I know, arc4random_uniform should be good enough for cryptographic applications, but you may need to consult a cryptography expert if the data that you are planning to protect is of high value to you or especially to your clients.

EDIT : Edited in response to nielsbot's comment.

like image 177
Sergey Kalinichenko Avatar answered Oct 03 '22 16:10

Sergey Kalinichenko


FWIW, I'd favor Vincent Gable's suggestion of using a UUID. If you are set on the suggested algorithms, you can get a little bit more variance by using something like this variant of nielsbot's code (just replace the string of characters with whatever you want to include as part of your random strings)...

const NSUInteger NUMBER_OF_CHARS = 40 ;
NSString * CreateRandomString()
{
    static char const possibleChars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    unichar characters[NUMBER_OF_CHARS];
    for( int index=0; index < NUMBER_OF_CHARS; ++index )
    {
        characters[ index ] = possibleChars[arc4random_uniform(sizeof(possibleChars)-1)];
    }

    return [ NSString stringWithCharacters:characters length:NUMBER_OF_CHARS ] ;
}
like image 40
Jody Hagins Avatar answered Oct 03 '22 16:10

Jody Hagins