Advanced iOS Learning-network data security

Source: Internet
Author: User

First, data security

  

1. Terminology:

    • Key: A key is a parameter that is entered in an algorithm that converts plaintext into ciphertext or converts cipher text to plaintext. The key is divided into a symmetric key and an asymmetric key (which can also be divided into encryption key and decryption key depending on the purpose).
    • PlainText: Information that is not encrypted to directly represent the meaning of the original text.
    • Ciphertext: After the processing of encryption, hide the original meaning of the information.
    • Encryption: Converts the plaintext to the redact implementation process.
    • Decryption: The implementation process of converting ciphertext into plaintext.

2. Data security

    • Data security: Is an active containment measures, the security of the data itself must be based on a reliable encryption algorithm and security system, mainly symmetric algorithm and public key cryptosystem two (asymmetric algorithm), all contain the data encryption and decryption process
    • Symmetric algorithm: Symmetric cipher algorithm is sometimes called traditional cipher algorithm, which means that the encryption key can be deduced from the decryption key, which in turn is established.
    • Asymmetric algorithm: Asymmetric key is also called public key encryption, that is, one of the keys cannot be deduced from another key.
    • There are many encryption algorithms, and in iOS development, MD5 is our common digest algorithm.

Second, MD5 encryption

1. Hashing algorithm:

    • Hashing algorithm: The hashing algorithm maps a binary value of any length to a shorter fixed-length binary value, a small binary value 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. Typically used for quick find and encryption algorithms.
    • Typical hashing algorithms are: MD2, MD4, MD5, and SHA-1.

2, MD5:

    • Md5:message Digest Algorithm MD5 (Chinese named message Digest Algorithm version fifth) is a hash function widely used in the field of computer security to provide integrity protection of messages.
    • The MD5 algorithm has the following characteristics:
    • Compressibility: Any length of data, the calculated length of the MD5 value is fixed (16, 32 bits).
    • Easy to calculate: It is easy to calculate the MD5 value from the original data.
    • Anti-modification: Make any changes to the original data, even if only 1 bytes are modified, the resulting MD5 value is very different.
    • Strong anti-collision: known raw data and its MD5 value, it is very difficult to find a data with the same MD5 value (that is, falsification of data).

3. Get string MD5 value: Introduce <CommonCrypto/CommonCrypto.h>, get MD5 value of string.

code example:

    1. Prepare a string for encryption (similar to the same string for MD5 encrypted content)    nsstring *str = @ "I love You";    2. Because MD5 is based on the C language, it is necessary to encode the string    const char *data = [str utf8string];    3. Use a string array to access the encrypted content (MD5 16 binary, 32-bit)    //cc_md5_digest_length for length    unsigned char result [cc_md5_digest_length ];    4. MD5 encryption    //Parameter 1: Content to be encrypted/    /Parameter 2: A length of data to encrypt//    parameter 3: An array of stored cryptographic results (MD5)    cc_md5 (data, (Cc_long) strlen (data), result);    5. Create a mutable string, save the result    nsmutablestring *mstr = [nsmutablestring string];    6. Iterate through the result array and add to the variable string for    (int i = 0; i < cc_md5_digest_length; i++) {        [mstr appendformat:@ "%02x", result[i ]];    }

4, get other object MD5 value: Introduce <CommonCrypto/CommonCrypto.h>, convert other objects into NSData object (can write the object beforehand to file), read MD5 value of NSData object.
code example: (Take an array as an example)

  Requirements: Create an array, store the elements in the array, write the array into the sandbox//create an array nsarray *array = @[@ "Jack" @ "Rose"; Find sandbox path NSString *path = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) objectAtInd    EX:0];    Stitching path NSString *arraypath = [path stringbyappendingpathcomponent:@ "Array.plist"];        Write [sender Writetofile:arraypath Atomically:yes];           Remove the NSData data from the sandbox nsdata *data = [NSData Datawithcontentsoffile:arraypath];        NSData type Data encryption process//1. Create MD5 object Cc_md5_ctx MD5;        2. Initialize the MD5 object Cc_md5_init (&AMP;MD5);        3. Prepare to begin data encryption Cc_md5_update (&AMP;MD5, Data.bytes, (Cc_long) data.length);    4. End MD5 encryption//prepare a string array to store the results unsigned char result[cc_md5_digest_length];    Cc_md5_final (result, &AMP;MD5);    5. Get results nsmutablestring *mstr = [[Nsmutablestring alloc] initwithcapacity:cc_md5_digest_length];    Iterate through an array to assign a variable string for (int i = 0; i< cc_md5_digest_length; i++) {[Mstr appendformat:@ "%02x", Result[i]]; } NSLog (@ "%@", MSTR); 

Note:

    • Hash algorithm is a digest algorithm, the main function is to obtain a summary of the data. Not a cryptographic algorithm in the strictest sense (because there is no decryption process)
    • Getting the MD5 value of a string is simpler, and other objects can be converted into NSData objects before they are manipulated.
    • You can get the file data directly from the path, or you can write the object to the NSData object after it is written to the file
    • iOS also supports SHA1, base64, AES, keychain, and other ways to encrypt data

Three, key string encryption

1, Keychain Introduction: Keychain: (English: Keychain) is Apple Mac OS in the password management system. It was imported after Mac OS 8.6 and IOS7, and was included in all subsequent releases. A keychain can contain multiple types of data: passwords (including websites, FTP servers, SSH accounts, network shares, wireless networks, group software, encrypted disk images, etc.), private keys, electronic certificates, and encrypted notes.

2. Keychain Encryption:

    • The Apple IOS and Mac OS X system comes with a set of sensitive information preservation schemes: "Keychain" (Keychain).
    • The content stored in the keychain is equivalent to the system's protection and is encrypted when the device is locked.
    • The entry in the keychain is called Secitem, but it is stored in the cfdictionary. The Secitemref type does not exist. Secitem has five categories: Universal password Internet password, certificate, key and identity. In most cases, all we use is a universal password.
    • The use of keychains is very similar to a dictionary.
    • The access and reading and writing of keychain can be realized by using native security.framework. But it can only be done on the real machine. Usually we use Keychainitemwrapper (GitHub) to complete the encryption of the keychain.

3, Keychain use:

    • Copying keychain classes into the project
    • Introduction of standard header files
    • Generating Keychain Objects
    • Storage of encrypted data
    • Get Keychain Objects
    • Get the encrypted data
    • code example:
    First need to import Keychain third party keychainitemwrapper.h/m    //Create Keychain object//    parameter 1: identification, used to identify the content behind the encryption (callback identifier)    //Parameter 2: grouping, generally nil    Keychainitemwrapper *keychainitem = [[Keychainitemwrapper alloc] Initwithidentifier:identifier AccessGroup:nil];    Commonly used with encrypted user name and password    //system provided by the key value pair of two keys, non-system keys are not able to add to the dictionary    id kusername = (__bridge id) ksecattraccount;    ID kpasswordname = (__bridge id) ksecvaluedata;    [Keychainitem setobject:@ "user" forkey:kusername];    [Keychainitem setobject:@ "123456" forkey:kpasswordname];    The keychain created by the same identity has the same data    keychainitemwrapper *keychainitem2 = [[Keychainitemwrapper alloc] Initwithidentifier: 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 retrieving objects
    • The non-system key value cannot be added to the dictionary.

Four, public key encryption

1. Introduction to Public Key cryptography:

    • Public key cryptography is also called asymmetric encryption.
    • Common algorithms are RSA, ElGamal, Knapsack algorithm, Rabin and so on, the most used in iOS is RSA (GitHub).
    • IOS uses RSA encryption and requires only the public key.
    • The first step is to introduce a third-party RSA.h.

2. Public Key cryptography: (How to generate public and private keys)

Both the public and private keys are generated using certificates, not our custom strings. We are using a generated public key and a private key//Where the-----BEGIN to public key-----and-----END Public key-----Not part of the key//key: iOS client use, we get the key You can    //get the data for the public key by simply processing the data according to the public key    nsstring *publickey = @ "-----BEGIN publicly KEY-----migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdfzvl2zazvmsgal6j3fxsn1aqyq1gbdhqgzielxdwh5fvndivgife/ s3wltio8lhlc9iacd894gg6aqlfs24otgkehgciiabkb7x3g458/gbwsioryunvxjkfkv+lkb9tljjw4egchiein/ M1xknlkmrsgltjyyoy7nhihyc8haqidaqab-----END Public KEY-----";    Create string    nsstring *teststr = @ "encryption example";    Create a string that stores the public key, encrypt    nsstring *encpublickey = [RSA encryptstring:teststr publickey:publickey];    NSLog (@ "encpublic =%@", Encpublickey);

3, private key decryption: (The secret key decryption string needs to be provided by Java background,)

 Private key: Used to decrypt data. Note: Do not leak, otherwise the data is not safe! NSString *privatekey = @ "-----BEGIN PRIVATE KEY-----miiceaibadanbgkqhkig9w0baqefaascamiwggjeageaaogban/nuvzlpm+ Ziycx qpcxgyfvqpirwbsofazkh4vepchkvu10i8ygv79lfcvmg7yuevz0gaipz3gybocqv+ zbihoap4cyiijoeohvhedjnz8zvbki6vjsdxekowrx6uoh1ouklbh6bwej6i3+ bxeqeuqzgwavmljkhjs2gkhjzwcbagmbaaecgyeajpjiv3kbounb4bqjhqn+rjygfincsr1kq0qawztsq52bw24u4tbzutz9vxg7fzccv/ it9dh01xo79dhtq44qbe7gkxy9slk/uko6ffnyxwxx0/l6ywtpliwrfzvi1binnxf24uon/ Qe1wzpbg305y3es2mdiem5kko7svhqtlyecqqdzd4cxiycoziyvwjtcipwc6w45yrbndbbpt4gpgoz6 HGQ8eeFHpZjLnJgHWISnCvCG76PWBFG +4fwewl7/5mnjakea61klr4wnmcuyrkjapk+pt9yqlb71qoobendlfd1boyl1fznar3ntkq0bp4ab+mkws2dzvxajkxttyw9fbh/n+ qjbakwxbop5gvfvevmibypb1flrux51wu8464laqnkdxmzzdjazh/f4wuwk4bsxinladmust+5tf0ujj6bdnateqkecq+    Dujlt7bwm2tvzorrofkwmgewrympssb8dfl9lntuekuiiqafrxwuv5xgemef0bcasmfdodsklw3aenljhv5kcqqc4fjk6    nb02fk7f1co1254olayhdmd7neryaazqet+kvhzjv76ro6bgeldy+snxtzlrwgbijxgyr1bftxl+0ai/-----END PRIVATE KEY-----"; Create a string that stores the private key NSString *result = @ "";//after encryption, you need to send the encrypted content to the background, when the background will return you a string//parameter 1: Provided by Java background//parameter 2: Private key NSString *encprivatekey = [RSA de    Cryptstring:result Privatekey:privatekey]; NSLog (@ "(PHP enc) encprivate =%@", Encprivatekey);

Wu, KVO

1, KVO Introduction:

    • KVO: (key-value-observer) Key-value observer, is a specific implementation of the observer design pattern.
    • KVO trigger mechanism: An object (Observer) that monitors the change of a property of another object (the observer) and, if changed, triggers a method of the Observer (fixed method name, similar to proxy method).

2, KVO use steps:

    • Registering the Observer (specifying the observer and the observed attribute for the observed person)?;
    • Implement callback method?;
    • Trigger callback method (the observed attribute is changed);
    • Remove the viewer.
    • code example:
-(void) viewdidload {[Super viewdidload];     Additional setup after loading the view, typically from a nib. First step: Register the Observer//Parameter 1: Add the Observer object//Parameter 2: The string identifies the key//Parameter 3: When to trigger the Add observer object//nskeyvalueobservingoptionne W key and value will trigger//nskeyvalueobservingoptionold//nskeyvalueobservingoptioninitial if there is an update//nskeyv Alueobservingoptionprior//Parameter 4: text content is generally nil [self addobserver:self forkeypath:@ "array" options:nskeyvalueobse Rvingoptionnew Context:nil];} When the view is going to disappear-(void) Viewwilldisappear: (BOOL) animated{//When no observer is needed [self removeobserver:self forkeypath:@ "array"];} Step two: Implement the callback Method-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary<    NSString *,id> *) Change context: (void *) context{NSLog (@ "keypath =%@", keypath);    NSLog (@ "object =%@", object);    NSLog (@ "change =%@", change); The ability to refresh the UI}//step three: Trigger variable array to change-(void) Touchesbegan: (Nsset<uitouch *> *) touchesWithevent: (uievent *) event{nsarray *subarr = @[@ "1", @ "2", @ "3"];    SetArray sets the data for a mutable array object [[Self mutablearrayvalueforkeypath:@ "array] Setarray:subarr] based on the KeyPath obtained to the mutable data object; NSLog (@ "Subarr =%@", [Self mutablearrayvalueforkeypath:@ "array"]);}

Advanced iOS Learning-network data security

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.