IOS advanced learning-Network-based data security, ios advanced

Source: Internet
Author: User
Tags key string asymmetric encryption

IOS advanced learning-Network-based data security, ios advanced

I. Data Security

  

1. terms:

  • Key: A key is a parameter entered in an algorithm that converts plaintext to ciphertext or converts ciphertext to plaintext. Keys are classified into symmetric keys and asymmetric keys (you can also divide them into encryption keys and decryption keys based on their purposes ).
  • Plaintext: Information that directly represents the meaning of the original text without encryption.
  • Ciphertext: After encryption, the original meaning information is hidden.
  • Encryption: implements the process of converting plaintext into ciphertext.
  • Decryption: the implementation process of converting ciphertext into plain text.

2. Data Security

  • Data security: it is an active inclusion measure. Data security must be based on reliable encryption algorithms and security systems, there are two types of asymmetric algorithms: symmetric algorithms and public key cryptography systems. They both contain data encryption and decryption processes.
  • Symmetric algorithms: symmetric cryptographic algorithms are sometimes called traditional cryptographic algorithms. They are called encryption keys that can be derived from decryption keys.
  • Asymmetric algorithms: Asymmetric keys are also called public key encryption, that is, they cannot be pushed from one of them to another.
  • There are many encryption algorithms. In iOS development, MD5 is a commonly used Digest algorithm.

Ii. MD5 Encryption

1. Hash Algorithm:

  • Hash Algorithm: the hash algorithm maps binary values of any length to short binary values of a fixed length. This small binary value is called a hash value.
  • A hash value is a unique and extremely compact numeric representation of a piece of data. The hash value of the data can verify the integrity of the data. It is generally used for quick search and encryption algorithms.
  • Typical hash algorithms include MD2, MD4, MD5, and SHA-1.

2. MD5:

  • MD5: Message Digest Algorithm MD5 (the fifth version of the Message Digest Algorithm in Chinese) is a hash function widely used in the computer security field to provide Message integrity protection.
  • The MD5 algorithm has the following features:
  • Compression: Data of any length. The calculated MD5 value length is fixed (hexadecimal, 32-bit ).
  • Easy to calculate: it is easy to calculate the MD5 value from the original data.
  • Anti-modification: Any modification to the original data, even if only one byte is modified, the MD5 value is very different.
  • Strong anti-collision: it is very difficult to find a data with the same MD5 value (that is, forged data) because the original data and its MD5 value are known.

3. Obtain the MD5 value of a string: Introduce <CommonCrypto/CommonCrypto. h> to obtain the MD5 value of a string.

Sample Code:

// 1. prepare a string for encryption (similar to the MD5 encrypted content of the same string) NSString * str = @ "I Love you"; // 2. because MD5 is based on the C language, you need to encode the string const char * data = [str UTF8String]; // 3. use a string array to access the encrypted content (MD5 hexadecimal, 32-bit) // CC_MD5_DIGEST_LENGTH indicates the length of unsigned char result [CC_MD5_DIGEST_LENGTH]; // 4. perform MD5 encryption // parameter 1: the content to be encrypted // parameter 2: the length of the data to be encrypted // parameter 3: The array storing the encrypted result (MD5) CC_MD5 (data, (CC_LONG) strlen (data), result); // 5. create a variable string and save the result NSMutableString * mStr = [NSMutableString string]; // 6. traverse the result array and add it to the variable string for (int I = 0; I <CC_MD5_DIGEST_LENGTH; I ++) {[mStr appendFormat: @ "% 02x ", result [I];}

4. Obtain the MD5 values of other objects: Introduce <CommonCrypto/CommonCrypto. h>, convert other objects to NSData objects (objects can be written to files in advance), and read the MD5 values of NSData objects.
Code example: (using arrays as an example)

// Requirement: Create an array to store elements in the array and write the array into the sandbox. // create an array NSArray * array = @ [@ "Jack ", @ "Rose"]; // find the sandbox path NSString * path = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0]; // splicing path NSString * arrayPath = [path stringByAppendingPathComponent: @ "array. plist "]; // write [sender writeToFile: arrayPath atomically: YES]; // retrieve NSData from the sandbox NSData * data = [NSData dataWithContentsOfFile: arrayPath]; // NSData-type data encryption process // 1. create an MD5 object CC_MD5_CTX md5; // 2. initialize the MD5 object CC_MD5_Init (& md5); // 3. prepare to start data encryption CC_MD5_Update (& md5, data. bytes, (CC_LONG) data. length); // 4. end MD5 encryption // prepare a string array to store the result unsigned char result [CC_MD5_DIGEST_LENGTH]; CC_MD5_Final (result, & md5); // 5. obtain the result NSMutableString * mStr = [[NSMutableString alloc] initWithCapacity: CC_MD5_DIGEST_LENGTH]; // assign a value to the variable string for (int I = 0; I <strong; I ++) {[mStr appendFormat: @ "% 02x", result [I];} NSLog (@ "% @", mStr );

Note:

  • A hash algorithm is a digest algorithm used to obtain data summaries. Strictly speaking, it is not an encryption algorithm (because there is no decryption process)
  • It is relatively simple to obtain the MD5 value of a string. Other objects can be converted to NSData objects before performing operations.
  • You can directly obtain the file data according to the path, or you can write the object to the file and obtain it as an NSData object.
  • IOS also supports SHA1, base64, AES, and key string encryption.

3. Key string Encryption

1. Key string Introduction: key string: (English: Keychain) is the password management system in Apple's Mac OS. It is imported after Mac OS 8.6 and iOS7 and included in all subsequent versions. A key string can contain various types of data: passwords (including websites, FTP servers, SSH accounts, network sharing, wireless networks, group software, encrypted Disk Images, etc.), private keys, e-certificates and encrypted notes.

2. Key string encryption:

  • Apple iOS and Mac OS X systems come with a set of sensitive information storage solutions: "Keychain ).
  • The content stored in the key string is equivalent to the system's protection and encrypted when the device is locked.
  • The entries in the key string are called SecItem, but they are stored in the CFDictionary. The SecItemRef type does not exist. SecItem has five types of passwords: Internet passwords, certificates, keys, and identities. In most cases, we use a universal password.
  • The usage of the key string is very similar to that of the dictionary.
  • With the native Security. framework, you can access and read/write Key Strings. But it can only be performed on a real machine. Generally, KeychainItemWrapper (github) is used to encrypt the key string.

3. Key string usage:

  • Copy the key string to the Project
  • Introduce standard header files
  • Generate a key string object
  • Store encrypted data
  • Get the key string object
  • Obtain encrypted data
  • Sample Code:
// First, import the third-party KeychainItemWrapper of the key string. h/m // create a key string object // parameter 1: ID, used to identify the encrypted content (return identifier) // parameter 2: group, generally nil KeychainItemWrapper * keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier: identifier accessGroup: nil]; // two keys in key-value pairs commonly used with the encrypted user name and password // provided by the system, non-system Keys cannot be added to the dictionary. id kUserName = (_ bridge id) kSecAttrAccount; id kPasswordName = (_ bridge id) kSecValueData; [keychainItem setObject: @ "user" forKey: kUserName]; [keychainItem setObject: @ "123456" forKey: kPasswordName]; // KeychainItemWrapper * keychainItem2 = [KeychainItemWrapper alloc] identifier: identifier accessGroup: nil]; NSString * name = [keychainItem objectForKey: kUserName]; NSString * pwd = [keychainItem2 objectForKey: kPasswordName]; NSLog (@ "% @, pwd = % @", name, pwd );

4. Note:

  • The introduced header file is in MRC mode and needs to be mixed
  • Identify must be consistent when obtaining objects.
  • The non-system key value cannot be added to the dictionary.

Iv. public key encryption

1. Introduction to public key encryption:

  • Public key encryption is also called asymmetric encryption.
  • Common algorithms include RSA, ElGamal, backpack algorithm, and Rabin. The most common algorithms used in IOS are RSA (github ).
  • IOS uses RSA encryption and only requires the public key.
  • First, we need to introduce a third-party RSA. h.

2. public key encryption: (how to generate a public key and a private key)

// Both the public key and private key are generated using the certificate, which is not a custom string. We use the generated public key and private KEY // here ----- begin public key ----- and ----- end public key ----- do not belong to the KEY part // public key: used by the iOS client, after getting the public key, you only need to process data based on the public key to obtain the public key Data NSString * publicKey = @ "----- begin public key ----- BEGIN/decrypt/GbwSiOryUnVxJKFkV + lkb9tlj1_4egchiein/BEGIN ----- end public key -----"; // create a string NSString * testStr = @ "encryption example"; // create a string for storing the public key, and encrypt NSString * encPublicKey = [RSA encryptString: testStr publicKey: publicKey]; NSLog (@ "encpublic = % @", encPublicKey );

3. Private Key decryption: (the string decrypted by the private key must be provided by the JAVA background ,)

// Private Key: Used to decrypt data. Note: data cannot be leaked; otherwise, data is not secure! NSString * privateKey = @ "----- begin private key ----- examples/NUvZlpm + ZIYCX examples + examples/uKo6ffnYxWxx0/examples + 4fwewL7/examples + examples /N + keys/f4wUwK4BsxInLAdMusT + 5TF0UJj6BdNaTEQKECQ + hybrid keys + KVHZjV76rO6BGeldy + keys + 0AI/----- end private key -----"; // create a string NSString * result = @ "" for storing the private key; // After encryption, the encrypted content must be transmitted to the background, at this time, the background will return you a string // parameter 1: Provided by the java background // parameter 2: Private Key NSString * encPrivateKey = [RSA decryptString: result privateKey: privateKey]; NSLog (@ "(PHP enc) encPrivate = % @", encPrivateKey );

V. KVO

1. Introduction to KVO:

  • KVO :( Key-Value-Observer) is a concrete implementation of the Observer design pattern.
  • KVO trigger mechanism: one object (observer) is used to monitor whether a property of another object (observer) changes. If the property to be monitored changes, it will trigger a method of the observer (the method name is fixed, similar to the proxy method ).

2. KVO usage steps:

  • Register The Observer (specify the observer and the observed attribute for the observer );
  • Implement callback;
  • Trigger the callback method (the observed attribute is changed );
  • Remove the observer.
  • Sample Code:
-(Void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // Step 1: register the observer \ // parameter 1: added observer object \ // parameter 2: key of the string identifier \ // parameter 3: when to add the observer object \ // NSKeyValueObservingOptionNew key and value? If there is an update, the \ // NSKeyValueObservingOptionOld \ // expires \/expires \ // parameter 4 is triggered.: the text content is generally nil [self addObserver: self forKeyPath: @ "array" options: NSKeyValueObservingOptionNew context: nil];} // when the view is about to disappear-(void) viewWillDisappear :( BOOL) animated {// [self removeObserver: self forKeyPath: @ "array"] ;}// Step 2: implement the callback method-(void) When no observer is required) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object change :( NSDictionary <NSString *, id> *) change context :( void *) context {NSLog (@ "keyPath = % @", keyPath); NSLog (@ "object = % @", object); NSLog (@ "change = % @", change ); // You can refresh the UI} // Step 3: trigger variable array changes-(void) touchesBegan :( NSSet <UITouch *> *) touches withEvent :( UIEvent *) event {NSArray * subArr = @ [@ "1", @ "2", @ "3"]; // obtain a variable data object based on keyPath, setArray sets data for a variable array object [[self mutableArrayValueForKeyPath: @ "array"] setArray: subArr]; NSLog (@ "subArr = % @", [self mutableArrayValueForKeyPath: @ "array"]);}

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.