Introduction to iOS common cryptographic algorithms and code practices

Source: Internet
Author: User

The iOS system library defines the encryption and decryption algorithms commonly used in software development, and the interface is in C language form. The following categories are included:

1 #include <CommonCrypto/CommonCryptor.h>//Common encryption and decryption algorithm 2 #include <CommonCrypto/CommonDigest.h>//Digest Algorithm 3 # Include <commoncrypto/commonhmac.h>4 #include <commoncrypto/commonkeyderivation.h>5 #include < Commoncrypto/commonsymmetrickeywrap.h>

The first type of commonly used encryption and decryption algorithm includes aes,des, and obsolete RC4, the second kind of summary algorithm, including such as Md5,sha. This paper mainly introduces the implementation of Aes,md5,sha three most common algorithms.

1 Symmetric cipher Algorithm--aes

AES is mainly used in key data and file confidentiality while also need to decrypt the situation, its encryption key and decryption key is the same, according to the key length is divided into 128, 192 and 2,563 levels, the greater the key length security is greater, but the performance is lower, according to the actual business security requirements to determine the better. In general, the objects that encrypt some key data are strings, and the encrypted results are also saved as strings, so both the parameters and the return values are strings when designing the interface. (The meaning of key parameters is explained after the code.) )

1.1 Encryption process

 1-(NSString *) Aes256_encrypt: (NSString *) Key 2 {3 const char *CSTR = [Self Cstringusingencoding:nsutf8stringencodin G]; 4 NSData *data = [NSData datawithbytes:cstr length:self.length]; 5 6//Encrypt data 7 char keyptr[kcckeysizeaes256+1]; 8 bzero (keyptr, sizeof (KEYPTR)); 9 [Key Getcstring:keyptr maxlength:sizeof (keyptr) encoding:nsutf8stringencoding];10 Nsuinteger dataLength = [data length];11 size_t buffersize = datalength + kccblocksizeaes128;12 void *buffer = malloc (buffersize); size_t                                           numbytesencrypted = 0;14 Cccryptorstatus cryptstatus = Cccrypt (Kccencrypt, kccalgorithmaes,15 kccoptionpkcs7padding |                                           kccoptionecbmode,16 Keyptr, kcckeysizeaes256,17                                           null,18 [data bytes], datalength,19                         Buffer, buffersize,20                  &numbytesencrypted), if (cryptstatus = = kccsuccess), {nsdata *result = [NSData Datawithbytesnocopy:buffer length:numbytesencrypted];24//base6425 return [result Base64encodedstringwith options:nsdatabase64encoding64characterlinelength];26}else27 {nil;29}30 31}

1.2 Decryption process

 1-(NSString *) Aes256_decrypt: (NSString *) Key 2 {3 NSData *data = [[NSData alloc] Initwithbase64encodeddata:[self da Tausingencoding:nsasciistringencoding] options:nsdatabase64decodingignoreunknowncharacters]; 4 5//Decrypt Data 6 char keyptr[kcckeysizeaes256+1]; 7 bzero (keyptr, sizeof (KEYPTR)); 8 [Key Getcstring:keyptr maxlength:sizeof (KEYPTR) encoding:nsutf8stringencoding];  9 Nsuinteger datalength = [data length];10 size_t buffersize = datalength + kccblocksizeaes128;11 void *buffer = malloc (buffersize), size_t numbytesdecrypted = 0;13 cccryptorstatus cryptstatus = Cccrypt (Kccdecrypt, KCCAlgo rithmaes,14 kccoptionpkcs7padding |                                           kccoptionecbmode,15 Keyptr, kcckeysizeaes256,16                                           null,17 [data bytes], datalength,18     Buffer, buffersize,19                                      &numbytesdecrypted), if (cryptstatus = = kccsuccess), {NSDA ta* result = [NSData datawithbytesnocopy:buffer length:numbytesdecrypted];23 return [[NSString alloc] I  Nitwithdata:result encoding:nsutf8stringencoding];25}else27 {nil;29}30 31}

1.3 Interface Invocation Example

1 int main (int argc, const char * argv[]) {2     @autoreleasepool 3     {4          5         nsstring *plaintext = @ "O57w05xn-eq 2HCD3V-LPJJ4H0N-ZFO2WHRR-9HAVXR2J-YTYXDQPK-SJXZXALI-FAIHJV "; 6         NSString *key = @ "12345678901234561234567890123456"; 7          8         nsstring *crypttext = [PlainText Aes256_encrypt : Key]; 9         NSLog (@ "crypttext:\n%@", Crypttext), ten         nsstring *newplaintext = [Crypttext Aes256_decrypt:key];         NSLog (@ "newplaintext:%@", Newplaintext);         NSString *newcryptext3 = @ " U7cked8fscz6czs5eu7emxnm6/5awkzwbufk+d1jqdzim5junkgqnzi/vmiwfpvy5qd5vifh7qajzjdszxnkspg/b4if5bskdffp/3aysbw= ";         nsstring *newplaintext3 = [NewCrypText3 aes256_decrypt:key];16         NSLog (@ "newplaintext3:%@", NEWPLAINTEXT3);     }19     return 0;20}

1.4 Significance of key parameters

To master the use of AES algorithm, it is necessary to understand its several modes of operation, initialization vector, filling patterns and other concepts, often need to maintain a consistent multi-platform encryption and decryption results, use must be more confirmation. (You can use online website encryption to authenticate yourself.) )

kCCKeySizeAES256

There are 128,192 key lengths, enumerated types, and two.

kCCBlockSizeAES128

Block length, fixed value 16 (bytes, 128 bits), determined by the AES algorithm internal cryptographic details, but which method, mode, are for this.

Kccalgorithmaes

The algorithm name, which does not distinguish between 128, 192, or 258. KCCAlgorithmAES128 is only a historical reason, the same as the Kccalgorithmaes value.

Kccoptionpkcs7padding

Fill mode, the internal encryption details of the AES algorithm determine that the plaintext of AES must be an integer multiple of 64 bits, if the number of bits is insufficient, it needs to be padded. Kccoptionpkcs7padding said, the lack of a few to fill a few. For example, if 3 bits are missing, then fill 3 3 in clear text. iOS is only one way to do this, and other platforms are more like kccoptionpkcs5padding,kccoptionzeropadding. If consistency is to be achieved, other platforms here will also use kccoptionpkcs7padding.

Kccoptionecbmode

Mode of operation, electronic password mode. This mode does not require an initialization vector. There are only two modes of iOS, the default is CBC mode, which is block encryption mode. Standard AES is in addition to other methods such as CTR,CFB. Kccoptionecbmode mode multi-platform requirements are not high, recommended to use. CBC mode, requires the same initialization vector, multiple platforms to be consistent, workload increased, more secure, suitable for higher requirements of the scene use.

Base64

A Unicode to ASci code mapping, because the plaintext and ciphertext standards before and after the encryption may be Chinese characters or special characters, so for the intuitive display, the plaintext and ciphertext are usually base64 encoded.

2 Digest algorithm

Abstract algorithm, with one-way irreversible basic properties, fast.

2.1 Message digest Algorithm MD5

The MD5 algorithm maps any plaintext (not null) to a bit 32-bit string. Digital signatures and complex encryption systems are used in isolation due to the low security of the crash-vault.

1-(NSString *) Md5hexdigest 2 {3     const char *CSTR = [self cstringusingencoding:nsutf8stringencoding]; 4      5     UN Signed Char Result[cc_md5_digest_length]; 6      7     cc_md5 (CStr, (unsigned int) strlen (CSTR), result); 8      9     nsmutablestring *output = [nsmutablestring Stringwithcapacity:cc_md5_digest_length * 2];10 one for     (int i = 0; i < cc_md5_digest_length; i++)         [ Output appendformat:@ "%02x", result[i]];13     return output;15 16}

The results are stored in 16-string format, and can be base64 and other processing.

2.2 Secure Hashing Algorithm SHA

Sha According to the results of the number of bits divided into 256, 484, 5,123 basic methods, according to the results of the requirements and choose. Set by enumeration types such as Cc_sha256_digest_length.

1-(NSString *) Sha256hexdigest 2 {3     const char *CSTR = [self cstringusingencoding:nsutf8stringencoding]; 4     Nsdat A *data = [NSData datawithbytes:cstr length:self.length]; 5      6     uint8_t digest[cc_sha256_digest_length]; 7      8     cc_sha256 (data.bytes, (unsigned int) data.length, Digest); 9     nsmutablestring* output = [nsmutablestring stringwithcapacity:cc_sha256_digest_length * 2];11     12 for     (int i = 0; i < cc_sha256_digest_length; i++)         [Output appendformat:@ "%02x", digest[i]];14     return output;16}

Introduction to iOS common cryptographic algorithms and code practices

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.