2014年2月15日土曜日

【Object-C】ハッシュSHA-256のサンプルコード







◆宣言

#include <CommonCrypto/CommonDigest.h>


◇メソッド
- (NSString *)hashed_string:(NSString *)input
{
    const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:input.length];
    uint8_t digest[64];
    
    // This is an iOS5-specific method.
    // It takes in the data, how much data, and then output format, which in this case is an int array.
    CC_SHA256(data.bytes, data.length, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:64];
    
    // Parse through the CC_SHA256 results (stored inside of digest[]).
    for(int i = 0; i < 32; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    
    return output;
}

@end

1 件のコメント: