[objc/swift] md5 encode 하기

천현철·2021년 1월 21일
0

iOS

목록 보기
5/51
post-custom-banner

objc:

#import <CommonCrypto/CommonDigest.h>

+ (NSString *) md5:(NSString *) input
{
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, (CC_LONG)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;
}

swift:

import CommonCrypto

func MD5(_ input: String) -> String? {
    let length = Int(CC_MD5_DIGEST_LENGTH)
    var digest = [UInt8](repeating: 0, count: length)
    if let d = input.data(using: .utf8) {
        _ = d.withUnsafeBytes { body -> String in
            CC_MD5(body.baseAddress, CC_LONG(d.count), &digest)
            return ""
        }
    }
    return (0..<length).reduce("") {
        $0 + String(format: "%02x", digest[$1])
    }
}

출처
https://stackoverflow.com/questions/1524604/md5-algorithm-in-objective-c
https://stackoverflow.com/questions/32163848/how-can-i-convert-a-string-to-an-md5-hash-in-ios-using-swift

[Android Java] 안드로이드 암호화(md5, sha256)

profile
기도하지말고 행동하라
post-custom-banner

0개의 댓글