iOS Development algorithm Encryption md5,sha1,aes,base64

Source: Internet
Author: User
Tags base64 md5 md5 encryption sha1 sha1 encryption

1. MD5:

MD5 is the Message-digest algorithm 5 (Information-Digest algorithm 5), which is used to ensure complete consistency of information transmission. is one of the most widely used hashing algorithms (also translated digest algorithm, hashing algorithm), the mainstream programming language has been MD5 realized. The role of MD5 is to allow bulk information to be "compressed" into a confidential format (that is, to transform an arbitrary length of a byte string into a certain length of hexadecimal numbers ) before signing the private key with the digital signature software. (quoted from Baidu Encyclopedia)

MD5 Encryption is currently irreversible, can only be used as a test process, can not restore its original.

MD5 algorithm produces a fixed 128bit, that is, 128 0 and 1 of the bits, and in the actual application development, is usually 16 in the output, so exactly is 32 digits of 16, the White is 32 16 into the number.

Need to introduce header file:

#import <CommonCrypto/CommonDigest.h>

#define CC_MD5_DIGEST_LENGTH    /          * DIGEST LENGTH in bytes * *
-(NSString *) MD5: (Nsdictionary *) paramsdict {nsstring *instring = [paramsdict stringvalueforkey:@ "Data" defaultValue:@
    ""];
    if (instring.length <= 0) {return @ "";
        else {const char *cstrvalue = [instring utf8string];
        Open up a 16-byte (128-bit: MD5 is a 128-bit/bit) space (one byte = 8 character = 8 binary number) unsigned char outresult[cc_md5_digest_length];
        
        CC_MD5 (Cstrvalue, strlen (cstrvalue), outresult); x means hexadecimal, x meaning that less than two bits will be padded with 0 if the extra two bits do not affect nsstring *outstring = [NSString stringwithformat:@%02x%02x%02x%02x%0
               2x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x ", Outresult[0], outresult[1], outresult[2], outResult[3], OUTRESULT[4], outresult[5], outresult[6], outresult[7], outresult[8, outresult[9], outresult[
        ], outresult[11], outresult[12], outresult[13], outresult[14], outresult[15];
        *//Method Two: Nsmutablestring *outstring = [nsmutablestring string]; For (int i = 0; i < i++) {[outstring appendformat:@ ' X ', outresult[i]];
    } */return outstring; }
 }

Why [16], this is because the MD5 algorithm finally generates 128 bits, while the smallest storage unit in the computer is byte, 1 bytes are 8 bits, and corresponding to a char type, the calculation can take 16 char. So result is [16]. So why is the format of the output must be%02x, not the other. This is also a reason: because the Convention MD5 is generally output in the form of 16, so in fact the problem is converted to 128 0 and 1 in 16, each 4-bit binary corresponding to a 16-binary element, you need 32 16-in elements, if the element is all 0, put in the char array, Normal is not output, such as 00001111, to%x output, then F, then you will lose 0, but if the output is 0f in%02x, it is exactly the correct result of the conversion.

2. SHA1 Encryption

SHA1 algorithm is as irreversible.

-(NSString *) SHA1: (NSString *) input
{
    const char *CSTR = [input cstringusingencoding:nsutf8stringencoding];< C2/>nsdata *data = [NSData datawithbytes:cstr length:input.length];

    #define CC_SHA1_DIGEST_LENGTH       /* DIGEST LENGTH in bytes *
    uint8_t digest[cc_sha1_digest_length];
    CC_SHA1 (Data.bytes, Data.length, Digest);
    
    nsmutablestring *output = [nsmutablestring stringwithcapacity:cc_sha1_digest_length * 2];
    for (int i=0; i<cc_sha1_digest_length; i++) {
         [Output appendformat:@ '%02x ', Digest[i]];
    }
    return output;
}

3. AES Encryption

Advanced Encryption Standard (Advanced encryption Standard,aes), also known as the Rijndael encryption method.

It should be noted that AES can not be used as a hash algorithm, encryption and decryption results, and not necessarily the same as the original, please pay attention to the use of results checking. For example, to decrypt the length of the original text, format rules.

need to introduce header file

#import <CommonCrypto/CommonCryptor.h>

The encryption and decryption method uses a parameter key that can all be 32-bit-length strings and can be used to compute a 32-bit string as a key by MD5 any string, or to customize the following:

#define App_public_password @ "Boundary"

-(NSData *) Aes256encryptwithkey: (NSString *) key withstring: (NSString *) inputstring {//encryption NSData *indata = [InS
        Tring Datausingencoding:nsutf8stringencoding]; /***//If you want to return a string, start converting to nsdata at the beginning, corresponding to the following method three, methods one and two use the above statement can be a const char *CSTR = [instring cstringusingencod
        Ing:nsutf8stringencoding];
       NSData *indata = [NSData datawithbytes:cstr length:inString.length];
        /char keyptr[kcckeysizeaes256+1];
        Bzero (keyptr, sizeof (KEYPTR));
        [App_public_password getcstring:keyptr maxlength:sizeof (keyptr) encoding:nsutf8stringencoding];
        Nsuinteger datalength = [Indata length];
        size_t buffersize = datalength + kCCBlockSizeAES128;
        void *buffer = malloc (buffersize);
        size_t numbytesencrypted = 0;
                                              Cccryptorstatus cryptstatus = Cccrypt (Kccencrypt, kCCAlgorithmAES128, kccoptionpkcs7padding | KccoptionecbmodE, keyptr, kCCBlockSizeAES128, NULL, [indata bytes], Datale Ngth, buffer, buffersize,


        ; numbytesencrypted); if (Cryptstatus = = kccsuccess) {NSData *outdata = [NSData datawithbytesnocopy:buffer length:numbytesencrypted
            ];

           return outdata;  /***//If you need to return the NSString type result, here you need to convert://Method One: NSString *outstring = [[NSString   
                 Alloc]initwithdata:outdata encoding:nsutf8stringencoding]; Failure, note: Here outstring for nil, the specific reason seems to be because NSData content contains encoding encoded characters//Methods two: NSString *outstring

             = [Outdata base64encoding]; Method Three: (Convert to 2 binary string) if (Outdata && outdata.lengtH > 0) {Byte *datas = (byte*) [outdata bytes];
                       nsmutablestring *outstring = [nsmutablestring stringWithCapacity:outData.length * 2];
                       for (int i = 0; i < outdata.length i++) {[outstring appendformat:@ '%02x ', datas[i]];
        } ***/} free (buffer);
return nil; }
Decryption can be nsdata directly with the result of the encryption, which would be easy without the need for character conversion-(NSData *) Aes256decryptwithkey: (NSString *) key withnsdata: (NSString *) Indata {//decryption/***-(NSData *) Aes256decryptwithkey: (NSString *) key withstring: (NSString *) inputstring {//decryption//counterpart Plus
        The method of the secret algorithm two: (Before decrypting GTMBase64 code) NSData *indata = [GTMBase64 decodestring:instring];
           The method of corresponding encryption algorithm three: Nsmutabledata *indata = [Nsmutabledata DATAWITHCAPACITY:INSTRING.LENGTH/2];
           unsigned char whole_byte;
           Char byte_chars[3] = {' n ', ', ', ', ']
           int i;
               for (i=0 i < [instring length]/2; i++) {byte_chars[0] = [instring characteratindex:i*2];
               BYTE_CHARS[1] = [instring characteratindex:i*2+1];
               Whole_byte = Strtol (Byte_chars, NULL, 16);
           [Indata Appendbytes:&whole_byte length:1];
        } ***/Char keyptr[kcckeysizeaes256+1];
        Bzero (keyptr, sizeof (KEYPTR)); Use "key": #define App_public_pAssword @ "Boundary" [App_public_password getcstring:keyptr maxlength:sizeof (keyptr) encoding:nsutf8stringencod
        ING];
        Nsuinteger datalength = [Indata length];
        size_t buffersize = datalength + kCCBlockSizeAES128;
        void *buffer = malloc (buffersize);
        size_t numbytesdecrypted = 0;
                                 Cccryptorstatus cryptstatus = Cccrypt (Kccdecrypt, kCCAlgorithmAES128, kccoptionpkcs7padding |
                                 Kccoptionecbmode, Keyptr, kCCBlockSizeAES128, NULL,
                                 [Indata bytes], datalength, buffer, buffersize,

        &numbytesdecrypted); if (Cryptstatus = = kccsuccess) {NSData *outdata = [NSData datawithbytesnocopy:buffer length:numbytesdecrypted
            ];
            return outdata; /***///If you need to return to NSString, encrypt aboveThe algorithm and the decryption algorithm of each method correspond well, use the following statement to not return nil; Remember Datalength must match well nsstring *outstring = [[NSString alloc]initwithdata:outdata encoding:nsutf8stringencoding]
            ;
        /} free (buffer); return nil;}

4. Base 64 Encryption algorithm

Download Library GTMBase64

Instance Demo:http://up.2cto.com/2012/1215/20121215123257741.zip

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.