Objective-C 中的 MD5 算法 [英] MD5 algorithm in Objective-C

查看:26
本文介绍了Objective-C 中的 MD5 算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中如何计算MD5?

How to calculate the MD5 in Objective-C?

推荐答案

md5 在 iPhone 上可用,可以添加为 ie NSStringNSData 之类的补充下面.

md5 is available on the iPhone and can be added as an addition for ie NSString and NSData like below.

MyAdditions.h

MyAdditions.h

@interface NSString (MyAdditions)
- (NSString *)md5;
@end

@interface NSData (MyAdditions)
- (NSString*)md5;
@end

MyAdditions.m

MyAdditions.m

#import "MyAdditions.h"
#import <CommonCrypto/CommonDigest.h> // Need to import for CC_MD5 access

@implementation NSString (MyAdditions)
- (NSString *)md5
{
    const char *cStr = [self UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, (int)strlen(cStr), result ); // This is the md5 call
    return [NSString stringWithFormat:
        @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
        result[0], result[1], result[2], result[3], 
        result[4], result[5], result[6], result[7],
        result[8], result[9], result[10], result[11],
        result[12], result[13], result[14], result[15]
        ];  
}
@end

@implementation NSData (MyAdditions)
- (NSString*)md5
{
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5( self.bytes, (int)self.length, result ); // This is the md5 call
    return [NSString stringWithFormat:
        @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
        result[0], result[1], result[2], result[3], 
        result[4], result[5], result[6], result[7],
        result[8], result[9], result[10], result[11],
        result[12], result[13], result[14], result[15]
        ];  
}
@end

编辑

添加了 NSData md5 因为我自己需要它并且认为这是保存这个小片段的好地方...

EDIT

Added NSData md5 because I needed it myself and thought this is a good place to save this little snippet...

使用 NIST MD5 测试向量验证这些方法http://www.nsrl.nist.gov/testdata/

These methods are verified using the NIST MD5 test vectors in http://www.nsrl.nist.gov/testdata/

这篇关于Objective-C 中的 MD5 算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆