Several encryption methods for IOS

Source: Internet
Author: User
Tags decrypt hmac md5 encryption save file

Several encryption methods common to iOS

The normal encryption method is to encrypt the password and save it to user preferences.

The keychain is saved in clear text, but does not know the exact location of the storage

1, base64 encryption

Base64 coding is the foundation of modern cryptography

Basic principle:

    • Originally 8 bit a set of data, instead of 6 bit a set of data, the insufficient portion of 0, every two 0 with a =

    • With base64 encoding, the length of the data becomes larger and increases by around 1/3. (8-6)/6 can be reverse decrypted

Xcode7.0 after the show.

Coding has a very significant feature, at the end there is a = number

Encrypting a File

Get binary data that requires encrypted files

NSData *data = [NSData datawithcontentsoffile:@ "/users/wangpengfei/desktop/photo/img_5551.jpg"];

or base64encodedstringwithoptions

NSData *base64data = [data base64encodeddatawithoptions:0];

Store encrypted files to the desktop

[Base64data writetofile:@ "/users/wangpengfei/desktop/123" atomically:yes];

To decrypt a file

Get encrypted binary data

NSData *base64data = [NSData datawithcontentsoffile:@ "/users/wangpengfei/desktop/123"];

Decrypt Base64 data

NSData *basedata = [[NSData alloc] Initwithbase64encodeddata:base64data options:0];

Writing to the desktop

[Basedata writetofile:@ "/users/wangpengfei/desktop/img_5551.jpg" atomically:yes];

Using terminal commands for Base64 operations:

Save file Meinv.jpg as Meinv.txt after base64 operation

Base64 Meinv.jpg-o Meinv.txt

Speaking meinv.txt decoding generation Meinv.png

base64-d Meinv.txt-o Meinv.png

Base 64 encoding result of string "Hello": Agvsbg8=cho "Hello" | Base64

Agvsbg8= The result of Base64 encoding back to a string

echo agvsbg8= | Base64-d

2. Post Encryption

A. Building A UI Framework

Login.storyboard

Two uitextfiled: Enter user name and password separately

UIButton: Login button

Main.storyboard

Drag a Navigationcontroller->tableviewcontroller directly

Navigationitem + Logout button

B. Implementing basic encryption

Extracting a method of reading data

-(void) Readlocaluserinfo {

1. Instantiating preference Objects

Nsuserdefaults *userdefaults = [Nsuserdefaults standarduserdefaults];

2. Take out the data and assign the value

Self.userName.text = [Userdefaults Objectforkey:kusernamekey];

The encrypted password is read at this time

Self.password.text = [Userdefaults Objectforkey:kpasswordkey];

}

Extracting a method of storing data

-(void) Savelocaluserinfo {

1. Instantiating preference Objects

Nsuserdefaults *userdefaults = [Nsuserdefaults standarduserdefaults];

2. Store User Name

[Userdefaults SetObject:self.userName.text Forkey:kusernamekey];

3. Base64 Encryption of passwords

Convert a password into binary data

NSData *data = [Self.password.text datausingencoding:nsutf8stringencoding];

To encrypt

NSString *BASE64STR = [data base64encodedstringwithoptions:0];

4. Store encrypted passwords to preferences

[Userdefaults setobject:base64str Forkey:kpasswordkey];

5. To ensure thread consistency, both store and read data are synchronized

[Userdefaults Synchronize];

}

Sign in from a click event

-(Ibaction) Btnlogindidclick: (UIButton *) Sender {

If none of the two text boxes are empty, then the login operation

if (self.userName.text.length && self.password.text.length) {

1. Create request

NSString *urlstring = @ "http://localhost/login/login.php";

Nsurl *url = [Nsurl urlwithstring:urlstring];

The POST request requires that the request method be set manually, so that the variable request

Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];

Set Request method

Request. HttpMethod = @ "POST";

Set Request parameters

NSString *body = [NSString stringwithformat:@ "username=%@&password=%@", Self.userName.text, Self.password.text];

Converting a string into binary data

NSData *bodydata = [Body datausingencoding:nsutf8stringencoding];

Set the request body (binary data)

Request. Httpbody = Bodydata;

2. Send Request

[[[Nsurlsession Sharedsession] datataskwithrequest:request completionhandler:^ (NSData * _Nullable data, NSURLResponse * _nullable response, Nserror * _nullable error) {

Print Request Results

NSLog (@ "data:%@", [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]);

Determine if login is successful

if (data &&!error) {

NSLog (@ "Network request succeeded!");

Nsdictionary *dict = [nsjsonserialization jsonobjectwithdata:data options:0 Error:nil];

if (dict[@ "UserID"]) {

[Self savelocaluserinfo];

}

Jump to the main app screen to send notifications in the main thread

Dispatch_async (Dispatch_get_main_queue (), ^{

[[Nsnotificationcenter Defaultcenter] postnotificationname:@ "loginsuccess" object:nil];

});

} else {

NSLog (@ "Network request failed!");

}

}] [resume];

} else {

NSLog (@ "User name or password cannot be empty!");

}

}

C. Implementing a jump between pages

Use the Notification Settings page in the APPDELEGATE.M file to jump

Main method of switching

-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchOptions {

1. Notification viewer for registered successful login

[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (loginsuccess) name:@ "Loginsuccess" Object : nil];

2. Notification viewer for registered successful login

[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (logoutsuccess) name:@ "Logoutsuccess" Object:nil];

Each time the app opens, it should show to the user which interface

3. Use user-saved information in preferences to determine the user's login status

NSString *username = [[Nsuserdefaults standarduserdefaults] objectforkey:kusernamekey];

NSString *password = [[Nsuserdefaults standarduserdefaults] objectforkey:kpasswordkey];

if (userName && password) {

Show App main screen

[Self loginsuccess];

} else {

[Self logoutsuccess];

}

return YES;

}

Login successful

-(void) loginsuccess {

NSLog (@ "Login successful!");

Get the main interface

Uistoryboard *MAINSB = [Uistoryboard storyboardwithname:@ "Main" bundle:nil];

Switch Controller

Self.window.rootViewController = Mainsb.instantiateinitialviewcontroller;

}

Logoff success

-(void) logoutsuccess {

NSLog (@ "Logout succeeded!");

Get Login Interface

Uistoryboard *LOGINSB = [Uistoryboard storyboardwithname:@ "Login" bundle:nil];

Switch Controller

Self.window.rootViewController = Loginsb.instantiateinitialviewcontroller;

}

Set the Logout button's Click event in the Main.storyboard associated controller

1. Clear Local Information

[[Nsuserdefaults Standarduserdefaults] removeobjectforkey:kusernamekey];

[[Nsuserdefaults Standarduserdefaults] removeobjectforkey:kpasswordkey];

Synchronizing information

[[Nsuserdefaults standarduserdefaults] synchronize];

2. Send message, switch controller

[[Nsnotificationcenter Defaultcenter] postnotificationname:@ "logoutsuccess" object:nil];

3. Token value Introduction

token value : The login token. Use the token value to determine the user's login status. A long string similar to MD5 encryption.

After the user has successfully logged on, the backend (server side) generates a unique value based on the user information. This value is the token value.

Basic Use :

    • The token value is stored on the server side (database), which is used to retrieve the corresponding user information and determine the user's login status.

    • After the user logs in successfully, the server returns the generated token value to the client, and the token value is also saved at the client. (It can be stored in a cookie, or you can manually determine where to save it (e.g. preferences)).

    • The token value (passed to the server as a parameter) will be automatically shipped by default when the client sends a new network request. The server gets the token value passed by the client and compares it to the token value stored in the database to determine the user identity and login status.

To determine the logon status :

    • If the client does not have this token value, it means that the user is not logged in successfully and is prompted to log in.

    • If the client has a token value, the login is generally considered successful. No user login required (enter account and password information).

token value Extension :

token value has expiry time :

    • In general apps, tokens are worth more than 1 years of expiry time.

    • Special app: Bank app/Payment class App:token value expiration time is about 15 minutes.

    • Once the user information changes (password change), the server will generate a new token value, the original token value will be invalidated. You need to enter your account and password again to get the new token value generated.

    • Uniqueness Judgment: Each time you log in, a new token value will be generated. The original token value is invalidated. Use time to determine the difference between logins.

4. MD5 Encryption--(Information-Digest algorithm) one of the hashing algorithms

Transforms an arbitrary-length byte string into a hexadecimal large integer of a certain length.

Note that the conversion process of a string is irreversible and cannot be reversed by encrypting the result, the original content is deduced

Basic introduction

Need to import a third-party framework: Nsstring+hash

MD5 features :

    1. Compressibility: Any length of data, the calculated length of the MD5 value is fixed.

    2. Easy to calculate: It is easy to calculate the MD5 value from the original data.

    3. Anti-modification: Make any changes to the original data, even if only one byte is modified, the resulting MD5 value is very different.

    4. Weak anti-collision: known raw data and its MD5 value, it is very difficult to find a data with the same MD5 value (that is, forgery data).

    5. Strong anti-collision: To find two different data, so that they have the same MD5 value, is very difficult

MD5 Applications :

Conformance verification: MD5 the entire file as a large text message, and generates a unique MD5 message digest with an irreversible string transform algorithm. Just like everyone has their own unique fingerprint, MD5 produces a unique digital fingerprint of any file.

The use of MD5 for file verification, is widely used in software download station, forum database, System file security and other aspects (whether to add Trojans, tampering with the contents of the file, etc.). Baidu ' MD5 ' the first site to go in, using Database pseudo-decryption, that is, anti-query

digital Signature ;

Secure access authentication ;

How to use

Using MD5 to encrypt a string

NSString *password = @ "Wangpengfei";

Password = [password md5string];

NSLog (@ "password1:%@", password);

Add salt: To ensure MD5 encryption after the more secure

NSString *salt = @ "[email protected]#$%^&* () _+qwertyuiop{asdfghjkl:xcvbnm<>";

[Password Stringbyappendingstring:salt];

Password = [password md5string];

NSLog (@ "password2:%@", password);

Each company has its own "salt value", the more complex the salt value, the more secure

5. time stamp password

Basic introduction

Dynamic Password: same password plaintext + same encryption algorithm--because each landing time is different, so each calculated results are not the same. The security of the password can be fully guaranteed.

The server calculates two time values, when the period and the previous minute (for example: 59th S sends a network request, a second after the server receives and responds, the server current time than the client sent a minute later, still able to determine the exact value)

Use steps

Get MD5 password for first time encryption

1. Current password

NSString *password = @ "Zhang";

2. Hmackey value, which is the value after MD5 encryption for "Wangpengfei" (dynamically generated)

NSString *hmackey = @ "d3bba33b51acaa0a272de7a2f6dfa233";

Encryption process

1. First time encryption: first HMAC operation

Password = [password Hmacmd5stringwithkey:hmackey];

2.1 Getting the current time

NSDate *date = [NSDate Date];

2.2 Getting the current time string

Instantiating a time formatter

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

Set the time format

Formatter.dateformat = @ "Yyyy-mm-dd hh:mm";

Get the current time (to be consistent with the server)

NSString *datestr = [Formatter stringfromdate:date];

3. The first encrypted password is stitched together with the string of the current time

Password = [password stringbyappendingstring:datestr];

4. For the second HMAC encryption

Password = [password Hmacmd5stringwithkey:hmackey];

Access Loginhmac. PHP interface, sending requests

Create request

Nsurl *url = [Nsurl urlwithstring:@ "http://localhost/login/loginhmac.php"];

POST to manually set the method, so the variable

Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];

Set Request method

Request. HttpMethod = @ "POST";

Set the content of the request body

NSString *body = [NSString stringwithformat:@ "username=zhangsan&password=%@", password];

Request. Httpbody = [Body datausingencoding:nsutf8stringencoding];

Send Request

[[[Nsurlsession Sharedsession] datataskwithrequest:request completionhandler:^ (NSData * _Nullable data, NSURLResponse * _nullable response, Nserror * _nullable error) {

NSLog (@ "%@", [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]);

}] [resume];

6. Keychain Access

Basic introduction

    • Apple publishes the SDK for keychain access after IOS 7.0.3. The Keychain access interface is pure C language.

    • The keychain uses the AES 256 encryption algorithm to ensure the security of the user's password.

    • Keychain access to the third-party framework, Sskeychain, is the encapsulation of the C language framework. Note: Do not need to see the source code.

    • Where is the password for keychain access? Only Apple knows it. This further guarantees the user's password security.

Simple to use

Parameter introduction

    • Password: The password information that needs to be stored.

    • Service: A unique identifier used to identify the app and the app.

    • Accounts: Account information, the account number that corresponds to the current password.

Encrypt with Keychain

Gets the application unique identity.

NSString *bundleid = [NSBundle mainbundle].bundleidentifier;

Use a third-party framework to store user passwords in Keychain

[Sskeychain setPassword:self.pwdText.text forservice:bundleid account:@ "WPF"];

Load password from keychain

Self.pwdText.text = [Sskeychain passwordforservice:bundleid account:@ "WPF"];

7. Fingerprint identification

Simple Introduction

The fingerprint recognition feature was launched after the iphone 5S. The SDK is available in IOS 8.0!

The purpose of the fingerprint recognition function is to simplify the mobile payment process and occupy the mobile payment market.

Use steps

Import Frame

#import <LocalAuthentication/LocalAuthentication.h>

Get the current system version number

float Version = [Uidevice currentdevice].systemversion.floatvalue;

if (version < 8.0)//Determine current system version {

NSLog (@ "system version is too low, please upgrade to the latest system");

Return

}

Instantiate fingerprint recognition object to determine whether the current device supports fingerprint recognition (with TouchID)

1> instantiating a fingerprint recognition object

Lacontext *lactx = [[Lacontext alloc] init];

2> determines whether the current device supports fingerprint recognition.

if (![ Lactx Canevaluatepolicy:lapolicydeviceownerauthenticationwithbiometrics Error:null]) {

If the device does not support the fingerprint recognition feature

NSLog (@ "The device does not support the fingerprint recognition function");

Return

};

Fingerprint Login (default is Async method)

[Lactx evaluatepolicy:lapolicydeviceownerauthenticationwithbiometrics localizedreason:@ "Fingerprint login" reply:^ (BOOL success , Nserror *error) {

If successful, indicates that the fingerprint is entered correctly.

if (success) {

NSLog (@ "Fingerprint recognition succeeds!");

} else {

NSLog (@ "Fingerprint identification error, please try again");

}

}];

Several encryption methods for IOS

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.