How to generate random key in iOS

No comments on How to generate random key in iOS

Written by

in

It is a common task to generate a random n char string (alphanumeric string). It can be solved the following way. First, we generate an alphabet, that has m chars. Then in a cycle we generate random indexes from 0 to (m-1) and take a char from alphabet with random index.

    NSString *alphabet  = @"abcdefghijklmnopqrstuvwxyz \
ABCDEFGHIJKLMNOPQRSTUVWXZY0123456789";
    NSMutableString *s = [NSMutableString stringWithCapacity:20];
    for (NSUInteger i = 0U; i < 20; i++) {
        u_int32_t r = arc4random() % [alphabet length];
        unichar c = [alphabet characterAtIndex:r];
        [s appendFormat:@"%C", c];
    }
    NSLog(@"%@", s);
    NSString *key = s;

Inspired by this post

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *