mac下用c语言md5加密

今天在Mac下弄md5加密,需要使用库CommonCrypto进行。

第一种方式:

//
//  main.c
//  CAESTest
//
//  Created by comeontom on 14/7/31.
//  Copyright (c) 2014年 comeontom. All rights reserved.
//

#include 
#include 
#include 
#include 
#include 

#import 
//#import 

char cryptKey[kCCKeySizeAES128] = "O3fX{j{{*1:r[S2w";

char hexChar(unsigned char c) {
    return c < 10 ? '0' + c : 'a' + c - 10;
}

void hexString32(unsigned char *from, char *to, int length) {
    for (int i = 0; i < length; ++i) {
        unsigned char c = from[i];
        unsigned char cHigh = c >> 4;
        unsigned char cLow = c & 0xf;
        to[2 * i] = hexChar(cHigh);
        to[2 * i + 1] = hexChar(cLow);
    }
    to[2 * length] = '\0';
}



int main(int argc, const char * argv[])
{
    const char* original_str = "comeontom";
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(original_str, (CC_LONG)strlen(original_str), result);
    
    char hexResult32[2 * CC_MD5_DIGEST_LENGTH + 1];
    hexString32(result, hexResult32, CC_MD5_DIGEST_LENGTH);
    printf("%s\n",hexResult32);
    return 0;//返回0;正常退出
}


这种方式我只能得到32位md5


第二种方式:

int main(int argc, const char * argv[])
{
    const char* original_str = "comeontom";
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(original_str, (CC_LONG)strlen(original_str), result);
    
    //16位md5的获取
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++){
        if (i >= 4 && i <= 11) {
            printf("%02X", result[i]);
        }
    }
    printf("\n");
    
    //32位md5的获取
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++){
        if (i >= 4 && i <= 11) {
            printf("%02X", result[i]);
        }
    }
    printf("\n");

    return 0;//返回0;正常退出
}

说实在的,这些位的操作,真不是我能懂的,我先记录起来,后面用的时候在看

你可能感兴趣的:(C语言学习,objective-c基础)