Objective-C Encryption Algorithm

Source: Internet
Author: User
#import <CommonCrypto/CommonDigest.h>#import <CommonCrypto/CommonCryptor.h>//MD5- (NSString*)md5Hash {    unsigned char result[CC_MD5_DIGEST_LENGTH];    CC_MD5([self bytes], [self length], result);        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]            ];}//SHA1- (NSString*)sha1Hash {    unsigned char result[CC_SHA1_DIGEST_LENGTH];    CC_SHA1([self bytes], [self length], result);        return [NSString stringWithFormat:            @"%02x%02x%02x%02x%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],            result[16], result[17], result[18], result[19]            ];}
///////////////////////////////////////////////////////////////////////////////////////////////////// base64 code found on http://www.cocoadev.com/index.pl?BaseSixtyFour// where the poster released it to public domain// style not exactly congruous with normal three20 style, but kept mostly intact with the originalstatic const char encodingTable[] ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";///////////////////////////////////////////////////////////////////////////////////////////////////+ (NSData*)dataWithBase64EncodedString:(NSString *)string {    if ([string length] == 0)        return [NSData data];        static char *decodingTable = NULL;    if (decodingTable == NULL)    {        decodingTable = malloc(256);        if (decodingTable == NULL)            return nil;        memset(decodingTable, CHAR_MAX, 256);        NSUInteger i;        for (i = 0; i < 64; i++)            decodingTable[(short)encodingTable[i]] = i;    }        const char *characters = [string cStringUsingEncoding:NSASCIIStringEncoding];    if (characters == NULL)     //  Not an ASCII string!        return nil;    char *bytes = malloc((([string length] + 3) / 4) * 3);    if (bytes == NULL)        return nil;    NSUInteger length = 0;        NSUInteger i = 0;    while (YES)    {        char buffer[4];        short bufferLength;        for (bufferLength = 0; bufferLength < 4; i++)        {            if (characters[i] == '\0')                break;            if (isspace(characters[i]) || characters[i] == '=')                continue;            buffer[bufferLength] = decodingTable[(short)characters[i]];            if (buffer[bufferLength++] == CHAR_MAX)      //  Illegal character!            {                free(bytes);                return nil;            }        }                if (bufferLength == 0)            break;        if (bufferLength == 1)      //  At least two characters are needed to produce one byte!        {            free(bytes);            return nil;        }                //  Decode the characters in the buffer to bytes.        bytes[length++] = (buffer[0] << 2) | (buffer[1] >> 4);        if (bufferLength > 2)            bytes[length++] = (buffer[1] << 4) | (buffer[2] >> 2);        if (bufferLength > 3)            bytes[length++] = (buffer[2] << 6) | buffer[3];    }        realloc(bytes, length);    return [NSData dataWithBytesNoCopy:bytes length:length];}///////////////////////////////////////////////////////////////////////////////////////////////////- (NSString *)base64Encoding {    if ([self length] == 0)        return @"";        char *characters = malloc((([self length] + 2) / 3) * 4);    if (characters == NULL)        return nil;    NSUInteger length = 0;        NSUInteger i = 0;    while (i < [self length])    {        char buffer[3] = {0,0,0};        short bufferLength = 0;        while (bufferLength < 3 && i < [self length])            buffer[bufferLength++] = ((char *)[self bytes])[i++];                // Encode the bytes in the buffer to four characters,        // including padding "=" characters if necessary.        characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2];        characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];        if (bufferLength > 1)            characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];        else characters[length++] = '=';        if (bufferLength > 2)            characters[length++] = encodingTable[buffer[2] & 0x3F];        else characters[length++] = '=';    }        return [[[NSString alloc] initWithBytesNoCopy:characters length:length                                         encoding:NSASCIIStringEncoding freeWhenDone:YES]            autorelease];}// end recycled base64 code///////////////////////////////////////////////////////////////////////////////////////////////////
# Import <commoncrypto/commondigest. h> # import <commoncrypto/commoncryptor. h> // AES encryption-(nsdata *) aes256encryptwithkey :( nsstring *) Key {char keyptr [k1_eysizeaes256 + 1]; bzero (keyptr, sizeof (keyptr); [Key getcstring: keyptr maxlength: sizeof (keyptr) encoding: nsutf8stringencoding]; nsuinteger datalength = [self length]; size_t buffersize = datalength + buffers; void * buffer = malloc (buffersize ); size_t encrypt = 0; cccryptorstatus cryptstatus = cccrypt (kccencrypt, encrypt, decrypt | decrypt, keyptr, decrypt, null, [self bytes], datalength, buffer, buffersize, & numbytesencrypted ); if (cryptstatus = kccsuccess) {return [nsdata datawithbytesnocopy: Buffer length: numbytesencrypted];} Free (buffer); Return nil;} // AES decryption-(nsdata *) aes256decryptwithkey :( nsstring *) Key {char keyptr [kcckeysizeaes256 + 1]; bzero (keyptr, sizeof (keyptr); [Key getcstring: keyptr maxlength: sizeof (keyptr) Encoding: required]; nsuinteger datalength = [self length]; size_t buffersize = datalength + buffers; void * buffer = malloc (buffersize); size_t buffers = 0; cccryptorstatus cryptstatus = cccrypt (encrypted, encrypt, decrypt | kccoptionecbmode, keyptr, delimiter, null, [self bytes], datalength, buffer, buffersize, & bytes); If (cryptstatus = kccsuccess) {return [nsdata datawithbytesnocopy: buffer length: numbytesdecrypted];} Free (buffer); Return nil ;}

Author: Tracy E

Source: http://www.cnblogs.com/tracy-e

The copyright of this article is shared by the author and the blog Park. You are welcome to repost it, but please indicate the original article connection. Otherwise, you will be entitled to pursue legal liability.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.