SHA1 for Specific String in iOS

无人久伴 提交于 2019-12-04 16:52:05
Abhishek Singh

I have created this function , which works fine according to your requirement . You just have to input a string.

#import <CommonCrypto/CommonDigest.h>

- (NSString *)calculateSHA:(NSString *)yourString
{
    const char *ptr = [yourString UTF8String];

    int i =0;
    int len = strlen(ptr);
    Byte byteArray[len];
    while (i!=len)
    {
        unsigned eachChar = *(ptr + i);
        unsigned low8Bits = eachChar & 0xFF;

        byteArray[i] = low8Bits;
        i++;
    }


    unsigned char digest[CC_SHA1_DIGEST_LENGTH];

    CC_SHA1(byteArray, len, digest);

    NSMutableString *hex = [NSMutableString string];
    for (int i=0; i<20; i++)
        [hex appendFormat:@"%02x", digest[i]];

    NSString *immutableHex = [NSString stringWithString:hex];

    return immutableHex;
}

Then you just have to call the above method.

[self calculateSHA:yourString];
NSData *dataString = [yourString dataUsingEncoding: NSUTF8StringEncoding];

converts the string to UTF-8 bytes, e.g. "é" = Unicode 00E9 is converted to the two bytes C3 A9, and "€" = Unicode 20AC is converted to three bytes E2 82 AC.

If your requirement is to "truncate" the Unicode characters to the lower 8 bits, you have to do this "manually", I do not know a built-in encoding that could be used for that:

NSMutableData *dataString = [NSMutableData dataWithLength:[yourString length]];
uint8_t *dataBytes = [dataString mutableBytes];
for (NSUInteger i = 0; i < [yourString length]; i++) {
    // assigning the character to a uint_8 truncates to the lower 8 bit:
    dataBytes[i] = [yourString characterAtIndex:i];
}

Based on your code snippet, you want to do something like:

unsigned char digest[CC_SHA1_DIGEST_LENGTH];
NSData *dataString = [yourString dataUsingEncoding: NSUTF8StringEncoding];
NSMutableString *outString;

if (CC_SHA1([dataString bytes], [dataString length], digest)) {
    for (int i=0;i<CC_SHA1_DIGEST_LENGTH;i++) {
        [outString appendFormat:@"%02x", digest[i]];
    }
}

Where outString will be your 40-char string.

Peter

Here's an NSString category for creating a SHA1 hash of an NSString. Creating SHA1 Hash from NSString

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!