为了账号安全,请及时绑定邮箱和手机立即绑定

Objective-C中的MD5算法

Objective-C中的MD5算法

拉丁的传说 2019-11-22 11:00:06
如何在Objective-C中计算MD5?
查看完整描述

3 回答

?
慕斯王

TA贡献1864条经验 获得超2个赞

您可以使用内置的Common Crypto库来执行此操作。记住要导入:


#import <CommonCrypto/CommonDigest.h>

然后:


- (NSString *) md5:(NSString *) input

{

    const char *cStr = [input UTF8String];

    unsigned char digest[CC_MD5_DIGEST_LENGTH];

    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call


    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];


    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)

    [output appendFormat:@"%02x", digest[i]];


    return  output;

}


查看完整回答
反对 回复 2019-11-22
?
函数式编程

TA贡献1807条经验 获得超9个赞

如果性能很重要,则可以使用此优化版本。它比使用stringWithFormat或的速度快约5倍NSMutableString。


这是NSString的类别。


- (NSString *)md5

{

    const char* cStr = [self UTF8String];

    unsigned char result[CC_MD5_DIGEST_LENGTH];

    CC_MD5(cStr, strlen(cStr), result);


    static const char HexEncodeChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    char *resultData = malloc(CC_MD5_DIGEST_LENGTH * 2 + 1);


    for (uint index = 0; index < CC_MD5_DIGEST_LENGTH; index++) {

        resultData[index * 2] = HexEncodeChars[(result[index] >> 4)];

        resultData[index * 2 + 1] = HexEncodeChars[(result[index] % 0x10)];

    }

    resultData[CC_MD5_DIGEST_LENGTH * 2] = 0;


    NSString *resultString = [NSString stringWithCString:resultData encoding:NSASCIIStringEncoding];

    free(resultData);


    return resultString;

}


查看完整回答
反对 回复 2019-11-22
  • 3 回答
  • 0 关注
  • 580 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信