ios des 加/解密(with base64)

#include <CommonCrypto/CommonCryptor.h>

+ (NSString*)Encrypte:(NSString*)src key:(NSString*)key{

    NSString* retStr = nil;

    NSData* srcData = [src dataUsingEncoding:NSUTF8StringEncoding];

    size_t dataOutAvilable = ([srcData length] + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);

    unsigned char* dataOut = (unsigned char* )malloc(dataOutAvilable * sizeof(unsigned char));

    memset((void*)dataOut, 0x0, dataOutAvilable);

    size_t dataOutMoved = 0;

    Byte iv[] = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};

    CCCryptorStatus ccStatus = CCCrypt(kCCEncrypt, kCCAlgorithm3DES, kCCOptionPKCS7Padding | kCCOptionECBMode, (void const*)[key UTF8String], kCCKeySize3DES, iv, [srcData bytes], [srcData length], (void*)dataOut, dataOutAvilable, &dataOutMoved);

    if (ccStatus == 0) {//成功 base64

        int base64Len = base64_encode_length(dataOutMoved) + 2;

        char* tmp = new char[base64Len];

        memset(tmp, 0, base64Len);

        int base64Ret = base64_encode((const char*)dataOut,dataOutMoved,tmp,base64Len);

        if (base64Ret > 0) {

            retStr = [[[NSString alloc] initWithUTF8String:tmp] autorelease];

        }

        delete []tmp;

    }

    //NSLog(@"ccStatus: %d EncrypteStr:%@",ccStatus,retStr);

    delete dataOut;

    return retStr;

}


+ (NSString*)Decypte:(NSString*)src key:(NSString*)key{

    NSString* retStr = nil;

    int base64Len = base64_decode_length([src length]) + 2;

    char* tmp = new char[base64Len];

    memset(tmp, 0, base64Len);

    CCCryptorStatus ccStatus = kCCParamError;

    int base64Ret = base64_decode([src UTF8String], [src length],tmp, base64Len);

    if (base64Ret > 0) {

        size_t dataOutAvilable = (base64Len + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);

        unsigned char* dataOut = (unsigned char* )malloc(dataOutAvilable * sizeof(unsigned char));

        memset((void*)dataOut, 0x0, dataOutAvilable);

        size_t dataOutMoved = 0;

        Byte iv[] = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};

        ccStatus = CCCrypt(kCCDecrypt, kCCAlgorithm3DES, kCCOptionPKCS7Padding | kCCOptionECBMode, (void const*)[key UTF8String], kCCKeySize3DES, iv, (const void*)tmp, base64Ret, (void*)dataOut, dataOutAvilable, &dataOutMoved);

        if (ccStatus == 0) {

            retStr = [[[NSString alloc] initWithBytes:dataOut length:dataOutMoved encoding:NSUTF8StringEncoding] autorelease];

        }

        delete dataOut;

    }

    //NSLog(@"ccStatus: %d Decypte:%@",ccStatus,retStr);

    delete []tmp;

    return retStr;

}

希望天一直是蓝的,真的很美......
posted @ 2011-12-27 15:55  vieri122  阅读(2459)  评论(1编辑  收藏  举报