我知道SHA-1是首选,但这个项目需要我使用MD5.

#include <openssl/md5.h>

- (NSString*) MD5Hasher: (NSString*) query {
    NSData* hashed = [query dataUsingEncoding:NSUTF8StringEncoding];
    unsigned char *digest = MD5([hashed bytes], [hashed length], NULL);
    NSString *final = [NSString stringWithUTF8String: (char *)digest];
    return final;
}

我从StackOverflow上的另一个类似问题的答案中得到了这段代码,但当程序在return final;时中断时,我从GDB得到了以下错误

(gdb) p digest
$1 = (unsigned char *) 0xa06310e4 "\0206b\260/\336\316^\021\b\a/9\310\225\204"
(gdb) po final
Cannot access memory at address 0x0
(gdb) po digest

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0xb0623630
0x98531ed7 in objc_msgSend ()
The program being debugged was signaled while in a function called from GDB.
GDB has restored the context to what it was before the call.
To change this behavior use "set unwindonsignal off"
Evaluation of the expression containing the function
(_NSPrintForDebugger) will be abandoned.

我搞不懂.

推荐答案

这是我使用的类别:

NSString+MD5.h

@interface NSString (MD5)

- (NSString *)MD5String;

@end

NSString+MD5.m

#import <CommonCrypto/CommonDigest.h>

@implementation NSString (MD5)

- (NSString *)MD5String {
    const char *cStr = [self UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, (CC_LONG)strlen(cStr), result );

    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

Usage

NSString *myString = @"test";
NSString *md5 = [myString MD5String]; // returns NSString of the MD5 of test

Objective-c相关问答推荐

Objective c 判断文本字段是否为空

UICollectionView:一行或一列

如何在 Objective-C 中编写计时器?

使用自动布局自定义纵横比

iphone - 防止uiscrollview通过滚动

多个 WKWebView 之间的 Cookie 共享

为什么我不用 * 声明 NSInteger

如何知道 NSAssert 在发布版本中是否被禁用?

我们可以在 UIPageViewController 中自定义页面指示器吗?

使用情节提要的条件转场

在 NSNumbers 的 NSArray 中查找最小值和最大值

在 ios8 中没有调用 didRegisterForRemoteNotificationsWithDeviceToken,但是 didRegister...Settings 是

如何编写 OS X Finder 插件

如何在 Objective-C 中创建一个空白的透明 png?

NSHTTPCookieStorage 状态未在应用退出时保存.那里有任何明确的知识/文档吗?

当 UIView 框架更改时,视图内的 AVPlayer 层不会调整大小

如何调整 UITableView 中原型单元格的左边距?

如何判断 NSString 的最后一个字符

AVAudioPlayer 不播放任何声音

CALayer:仅在一侧添加边框