Introduction to IOS common cryptographic algorithms and code practice _ios

Source: Internet
Author: User
Tags base64 decrypt md5

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 specifically included:

 #include <CommonCrypto/CommonCryptor.h>//commonly used encryption and decryption algorithm
 #include <CommonCrypto/CommonDigest.h>//Digest algorithm
 #include <CommonCrypto/CommonHMAC.h>
 #include <CommonCrypto/CommonKeyDerivation.h>
 # Include <CommonCrypto/CommonSymmetricKeywrap.h> 

The first kind of commonly used encryption and decryption algorithm contains Aes,des, and abandoned RC4, the second kind of digest algorithm, including such as Md5,sha. This paper mainly introduces the implementation of Aes,md5,sha three kinds of most commonly used algorithms.
1 symmetric cipher algorithm--aes
AES is mainly used in the confidentiality of key data and files, but also need to decrypt the situation, with the same encryption key and encryption key, according to the key length of 128, 192 and 2,563 levels, the greater the key length security is greater, but the lower performance, according to the actual business security requirements to determine the good. Typically, the objects that encrypt some key data are strings, and the results of the encryption are saved as strings, so both the parameter and the return value are strings when designing the interface. (The meaning of key parameters is explained after the code.) )

1.1 Encryption process

-(NSString *) Aes256_encrypt: (NSString *) key {const char *CSTR = [self cstringusingencoding:nsutf8stringencoding];
  
  NSData *data = [NSData datawithbytes:cstr length:self.length];
  Encrypt the data char keyptr[kcckeysizeaes256+1];
  Bzero (keyptr, sizeof (KEYPTR));
  [Key Getcstring:keyptr maxlength:sizeof (KEYPTR) encoding:nsutf8stringencoding];
  Nsuinteger datalength = [data length];
  size_t buffersize = datalength + kCCBlockSizeAES128;
  void *buffer = malloc (buffersize);
  size_t numbytesencrypted = 0; Cccryptorstatus cryptstatus = Cccrypt (Kccencrypt, Kccalgorithmaes, kccoptionpkcs7padding | kCCOptionE Cbmode, Keyptr, kCCKeySizeAES256, NULL, [data bytes], datal
  Ength, buffer, buffersize, &numbytesencrypted);
    if (Cryptstatus = = kccsuccess) {NSData *result = [NSData datawithbytesnocopy:buffer length:numbytesencrypted]; Base64 return [RESult Base64encodedstringwithoptions:nsdatabase64encoding64characterlinelength];
  }else {return nil; }
  
}

1.2 Decryption Process

-(NSString *) Aes256_decrypt: (NSString *) Key {NSData *data = [[NSData alloc] initwithbase64encodeddata:[self DataUsingE
  
  Ncoding:nsasciistringencoding] options:nsdatabase64decodingignoreunknowncharacters];
  Decrypt the data by Char Keyptr[kcckeysizeaes256+1];
  Bzero (keyptr, sizeof (KEYPTR));
  [Key Getcstring:keyptr maxlength:sizeof (KEYPTR) encoding:nsutf8stringencoding];
  Nsuinteger datalength = [data length];
  size_t buffersize = datalength + kCCBlockSizeAES128;
  void *buffer = malloc (buffersize);
  size_t numbytesdecrypted = 0; Cccryptorstatus cryptstatus = Cccrypt (Kccdecrypt, Kccalgorithmaes, kccoptionpkcs7padding | kCCOptionE Cbmode, Keyptr, kCCKeySizeAES256, NULL, [data bytes], datal
  Ength, buffer, buffersize, &numbytesdecrypted);
   if (Cryptstatus = = kccsuccess) {nsdata* result = [NSData datawithbytesnocopy:buffer length:numbytesdecrypted]; 
    return [[NSString alloc] Initwithdata:result encoding:nsutf8stringencoding];
  }else {return nil; }
  
}

1.3 Interface Invocation Example

int main (int argc, const char * argv[]) {
  @autoreleasepool
  {
    
    NSString *plaintext = @ " O57W05XN-EQ2HCD3V-LPJJ4H0N-ZFO2WHRR-9HAVXR2J-YTYXDQPK-SJXZXALI-FAIHJV ";
    NSString *key = @ "12345678901234561234567890123456";
    
    NSString *crypttext = [plaintext Aes256_encrypt:key];
    NSLog (@ "crypttext:\n%@", crypttext);
    
    NSString *newplaintext = [Crypttext Aes256_decrypt:key];
    NSLog (@ "newplaintext:%@", newplaintext);
    
    NSString *newcryptext3 = @ "u7cked8fscz6czs5eu7emxnm6/5awkzwbufk+d1jqdzim5junkgqnzi/ Vmiwfpvy5qd5vifh7qajzjdszxnkspg/b4if5bskdffp/3aysbw= ";
    NSString *NEWPLAINTEXT3 = [NewCrypText3 Aes256_decrypt:key];
    NSLog (@ "newplaintext3:%@", NEWPLAINTEXT3);

  }
  return 0;
}

1.4 Significance of key parameters
to master the use of AES algorithm, must understand its several operating modes, initialization vector, fill mode concepts, and often need to maintain a consistent platform for the encryption and decryption results, the use of more must be confirmed. (You can use the online site to decrypt and authenticate yourself.)
kCCKeySizeAES256
Key length, enumeration type, and 128,192. The
kCCBlockSizeAES128
block length, fixed value 16 (byte, 128-bit), is determined by the internal encryption details of the AES algorithm, but which method, pattern, and so on. The
kccalgorithmaes
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, AES algorithm internal encryption details determine AES must be a 64-bit integer multiple, if the number is insufficient, you need to be padded. Kccoptionpkcs7padding said, missing a few to make up a few. For example, missing 3 digits, then fill 3 3 after plaintext. This is the only way to complement the iOS, other platforms, such as Kccoptionpkcs5padding,kccoptionzeropadding. If you want to achieve consistency, you will also use kccoptionpkcs7padding for other platforms here.
kccoptionecbmode
Working mode, electronic cipher mode. This mode does not require initialization vectors. There are only two types of iOS, the CBC mode, or block encryption mode, by default. Standard AES is in addition to other methods such as CTR,CFB. Kccoptionecbmode mode, the requirements of multiple platforms is not high, recommended use. CBC mode, which requires the same initialization vector, multiple platforms to be consistent, increased workload, higher security, suitable for the higher requirements of the scene to use.
base64
A Unicode to ASci code mapping, because plaintext and ciphertext standard encryption before and after all may be Chinese characters or special characters, so for intuitive display, the text and ciphertext are usually base64 encoded.

2 Digest algorithm
the algorithm has the basic properties of unidirectional irreversibility, and is fast.
2.1 Message digest Algorithm MD5
The MD5 algorithm maps a bit 32-bit string to arbitrary plaintext (not null). Both digital signatures and complex cryptographic systems are used, and are used alone because of the low security of the crash-pool reason.

-(NSString *) md5hexdigest
{
  const char *cstr = [self cstringusingencoding:nsutf8stringencoding];
  
  unsigned char result[cc_md5_digest_length];
  
  CC_MD5 (CStr, (unsigned int) strlen (CSTR), result);
  
  nsmutablestring *output = [nsmutablestring stringwithcapacity:cc_md5_digest_length * 2];
  
  for (int i = 0; i < cc_md5_digest_length i++)
    [Output appendformat:@ "%02x", Result[i]];
  
  return output;

}

Here the result is saved as a 16 string, and can be base64 and other processing.

2.2 Secure Hashing Algorithm SHA
Sha According to the results of the number of digits into 256, 484, 5,123 basic methods, according to the requirements of the results to choose. Set by an enumeration type such as Cc_sha256_digest_length.

-(NSString *) sha256hexdigest
{
  const char *cstr = [self cstringusingencoding:nsutf8stringencoding];
  NSData *data = [NSData datawithbytes:cstr length:self.length];
  
  uint8_t Digest[cc_sha256_digest_length];
  
  Cc_sha256 (data.bytes, (unsigned int) data.length, digest);
  
  nsmutablestring* output = [nsmutablestring stringwithcapacity:cc_sha256_digest_length * 2];
  
  for (int i = 0; i < cc_sha256_digest_length i++)
    [Output appendformat:@ "%02x", Digest[i]];
  
  return output;
}

3 to be continued, the later introduction of RSA asymmetric password use.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.