简体   繁体   中英

Generate a unique numeric String based off another String iOS

I'm looking to generate a unique string of numbers - preferabley 6-8 digits long, based off another string.

eg I have a string containing an email address. Then when clicking a button i get another string containing a unique 6-8 digit number based off of that email address.

The others suggested using a cryptographically secure MD5 hash.

If you don't care about cryptographic security, you could also simply use the built-in hash function:

NSUInteger *emailHash = [emailAddressString hash];

Since what you're converting to a number is an email address, it seems like encryption is overkill.

You could create an MD5 hash.

H2CO3 published a category for this: NSString-MD5

You will have to #import "NSString-MD5" .

Then you can create a hash:

NSString *emailHash = [email MD5Hash];

License is, well, public domain.

As rmaddy pointed out: there are no guarantees that you will get absolutely unique value which goes for any hashing method with fixed result size (ie: limited number of results for unlimited number of input variants).

Create an md5 hash on the string. CC_MD5 return 16 bytes. If you want to take 8 bytes, you can discard other bytes, but you need to check for uniqueness, (compare with your earlier received or stored values).

#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>
#import <CommonCrypto/CommonCryptor.h>


+ (NSString *)md5String:(NSString *)plainText
{
    if(plainText == nil || [plainText length] == 0)
        return nil;

    const char *value = [plainText UTF8String];
    unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5(value, strlen(value), outputBuffer);

    NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(NSInteger count = 0; count < CC_MD5_DIGEST_LENGTH; count++){
        [outputString appendFormat:@"%02x",outputBuffer[count]];
    }
    NSString * retString = [NSString stringWithString:outputString];
    [outputString release];
    return retString;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM