objective-c - Objective-C 中的 MD5 算法

Objective-C如何计算MD5?

最佳答案

md5 在 iPhone 上可用,可以添加为 NSStringNSData,如下所示。

MyAdditions.h

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

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

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,因为我自己需要它,并认为这是保存这个小片段的好地方...

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

https://stackoverflow.com/questions/1524604/

相关文章:

ios - 如何截取 UIView 的屏幕截图?

objective-c - 使用 NSLocalizedString 的最佳实践

iphone - 通过保持纵横比和宽度调整 UIImage 的大小

iphone - 在 iPhone TableView 单元格的单元格右侧添加小箭头

ios - 快速执行选择器 :withObject:afterDelay: is unavailab

objective-c - iOS 7 sizeWithAttributes : replaceme

objective-c - 如何将 NSNumber 转换为 NSString

ios - 如何根据文本长度计算 UILabel 宽度?

objective-c - 如何在 UIScrollView 内的 UIWebView 上启用放大功

iphone - -ObjC 链接器标志有什么作用?