Skip to content

Instantly share code, notes, and snippets.

@Kozlov-V
Last active August 29, 2015 14:15
Show Gist options
  • Save Kozlov-V/07568b410bc876107caa to your computer and use it in GitHub Desktop.
Save Kozlov-V/07568b410bc876107caa to your computer and use it in GitHub Desktop.
// NSString+Extension.h
@interface NSString (Extension)
+ (NSString *) getUUID;
+ (NSString *) sha1:(NSString *)input;
@end
// NSString+Extension.m
#import "NSString+Extension.h"
#import <CommonCrypto/CommonDigest.h>
@implementation NSString (Extension)
+ (NSString *)getUUID {
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return [(NSString *)string autorelease];
}
+ (NSString *) sha1:(NSString *)input
{
const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:input.length];
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(data.bytes, data.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];
return output;
}
@end
#import "NSString+Extension.h"
//Get a random hash (Generated from CFUUID+sha1)
NSString *hash = [NSString sha1:[NSString getUUID]];
//Shorten the sha1
NSString *short_random_id = [hash substringFromIndex:[hash length]-10];
//Random uppercase / lowercase the id
NSMutableString *random_id_final = [NSMutableString string];
for (NSUInteger i = 0; i < [short_random_id length]; i++)
{
NSString *substring = [short_random_id substringWithRange:NSMakeRange(i, 1)];
[random_id_final appendString:(rand() % 2) ? [substring lowercaseString] : [substring uppercaseString]];
}
//Use random_id_final
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment