문제

Objective-C에서 MD5를 계산하는 방법은 무엇입니까?

도움이 되었습니까?

해결책

MD5는 iPhone에서 사용할 수 있으며 IE 추가로 추가 할 수 있습니다. NSString 그리고 NSData 아래처럼.

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/

다른 팁

내장 된 공통 암호화 라이브러리를 사용하여 그렇게 할 수 있습니다. 수입을 기억하십시오 :

#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;
}

성능이 중요하다면이 최적화 된 버전을 사용할 수 있습니다. 그것은있는 것보다 약 5 배 더 빠릅니다. stringWithFormat 또는 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;
}

사람들이 파일 스트리밍 버전을 요구 한 이후로. 나는 MD5, SHA1 및 SHA512와 함께 작동하는 Joel Lopes da Silva가 만든 멋진 작은 스 니펫을 수정했으며 스트림을 사용하고 있습니다. iOS 용으로 만들어졌지만 OSX Aswell에서 최소한의 변화만으로 작동합니다 (alassetRepresentation 방법을 제거). FilePath 또는 Alassets (alassetRepresentation 사용)가 제공된 파일에 대한 체크섬을 만들 수 있습니다. 파일 크기/자산 크기에 관계없이 메모리에 미치는 메모리에 미치는 작은 패키지로 데이터를 청킹합니다.

현재 Github에 있습니다. https://github.com/leetal/filehash

Apple 구현을 사용하지 않는 모든 이유 : https://developer.apple.com/library/mac/documentation/security/conceptual/cryptoservices/generalpurpursecrypto/generalpurposecrypto.html#//apple_ref/doc/uid/tp40011172-ch9-sw1

Apple 개발자 사이트에서 암호화 서비스 안내서를 검색하십시오.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top