object-c MD5,BASE64加密不能返回固定值

时间:2017-08-09 03:39:09

标签: ios objective-c cryptography base64 md5

我使用这些代码来获取MD5 + Base64加密字符串,但是当我运行代码时,它有时无法返回真正的加密字符串,而不是经常。我的加密代码如下:

    + (NSString *) md5: (NSData *) data
{
    const char* original_str = (const char *)[data bytes];
    unsigned char digist[CC_MD5_DIGEST_LENGTH]; //CC_MD5_DIGEST_LENGTH = 16
    CC_MD5(original_str, (uint)strlen(original_str), digist);
    NSData * md5data = [[NSData alloc] initWithBytes:digist length:sizeof(digist)];
    NSString * result = [md5data base64EncodedStringWithOptions:0];
    return result;
}

2 个答案:

答案 0 :(得分:0)

尝试

const char *cStr = [@"fd" UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(cStr, (int)strlen(cStr), result);
NSMutableString *md5String = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; ++i) {
    [md5String appendFormat:@"%02x", result[i]];
}
NSString *encodedString = [NSString stringWithString:md5String];
NSData *nsdata = [encodedString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64Encoded = [nsdata base64EncodedStringWithOptions:0];

答案 1 :(得分:0)

我有解决方案。只需更改此代码

即可
CC_MD5(original_str, (uint)strlen(original_str), digist);

CC_MD5(original_str, (CC_LONG)data.length, digist);