Creating SHA1 Hash from NSString

前端 未结 7 1207
梦毁少年i
梦毁少年i 2020-12-23 19:57

How can I create a SHA1 from a NSString.

Let\'s say the NSString is set up as:

NSString *message = @\"Message\";

I can

7条回答
  •  天涯浪人
    2020-12-23 20:33

    I have this in a category on NSString (available at https://github.com/hypercrypt/NSString-Hashes):

    #import 
    
    ...
    
    - (NSString *)sha1
    {
        NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
        uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
        CC_SHA1(data.bytes, (CC_LONG)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;
    }
    

    Starting with Xcode 10.0, you should use import CommonCrypto instead since it is now natively available in Swift! If you have recently migrated to Xcode 10.0 and use the old approach, this can be your cue to make the change:

    Command CompileSwift failed with a nonzero exit code

提交回复
热议问题