The common encryption method is to encrypt the password and save it to the user preferences.
The keychain is kept in clear text, but it is not known where it is stored.
1base64 encryption
Base64 coding is the foundation of modern cryptography
Basic principle:
Originally 8 bit A group of representations of data, to 6 bit a set of data, the insufficient part of 0, every two 0 with one = expression
After encoding with Base64, the length of the data increases by about 1/3. (8-6)/6 can be reverse decrypted
Xcode7.0 after the show.
The code has a very significant feature, with a = number at the end.
Encrypt 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];
Storing 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"];
Decrypting base64 data
NSData *basedata = [[NSData alloc] Initwithbase64encodeddata:base64data options:0];
Write to 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 encoded result of the string "Hello": Agvsbg8=cho "Hello" | Base64
Base64 the result agvsbg8= after encoding to a string
echo agvsbg8= | Base64-d
2post encryption
A. Build A UI Framework
Login.storyboard
Two uitextfiled: Enter user name and password separately
UIButton: Login button
Main.storyboard
Just drag a Navigationcontroller->tableviewcontroller
Navigationitem + Logout button
B. Implementing basic encryption
Extracting methods for reading data
-(void) Readlocaluserinfo {
1. Instantiating a Preference object
Nsuserdefaults *userdefaults = [Nsuserdefaults standarduserdefaults];
2. Take out data to assign value
Self.userName.text = [Userdefaults Objectforkey:kusernamekey];
The encrypted password is read at this time
Self.password.text = [Userdefaults Objectforkey:kpasswordkey];
}
Extracting methods for storing data
-(void) Savelocaluserinfo {
1. Instantiating a Preference object
Nsuserdefaults *userdefaults = [Nsuserdefaults standarduserdefaults];
2. Store User Name
[Userdefaults SetObject:self.userName.text Forkey:kusernamekey];
3. Encrypt the password base64
Converts a password into binary data
NSData *data = [Self.password.text datausingencoding:nsutf8stringencoding];
For encryption
NSString *BASE64STR = [data base64encodedstringwithoptions:0];
4. Store the encrypted password in a preference setting
[Userdefaults setobject:base64str Forkey:kpasswordkey];
5. To ensure thread consistency, both storing and reading data are synchronized
[Userdefaults Synchronize];
}
Login action in the Click event
-(Ibaction) Btnlogindidclick: (UIButton *) Sender {
If two text boxes are not empty, sign in
if (self.userName.text.length && self.password.text.length) {
1. Create a request
NSString *urlstring = @ "http://localhost/login/login.php";
Nsurl *url = [Nsurl urlwithstring:urlstring];
POST requests need to set the request method manually, so 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 strings to 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 successful!");
Nsdictionary *dict = [nsjsonserialization jsonobjectwithdata:data options:0 Error:nil];
if (dict[@ "UserID"]) {
[Self savelocaluserinfo];
}
Jump to app main interface, send notification in main thread
Dispatch_async (Dispatch_get_main_queue (), ^{
[[Nsnotificationcenter Defaultcenter] postnotificationname:@ "loginsuccess" object:nil];
});
} else {
NSLog (@ "Network request failed!");
}
}] resume];
} else {
NSLog (@ "username or password cannot be blank!");
}
}
C. To achieve a jump between pages
Use notifications to set page jumps in APPDELEGATE.M files
The main method of switching
-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchOptions {
1. Registered login successful notification Observer
[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (loginsuccess) name:@ "Loginsuccess" Object : nil];
2. Registered login successful notification Observer
[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (logoutsuccess) name:@ "Logoutsuccess" Object:nil];
Each time the app opens, it should show the user which interface
3. Use the information saved by the user in the 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 interface
[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];
Switching controllers
Self.window.rootViewController = Mainsb.instantiateinitialviewcontroller;
}
Logout successful
-(void) logoutsuccess {
NSLog (@ "logout successful!");
Get Login Interface
Uistoryboard *LOGINSB = [Uistoryboard storyboardwithname:@ "Login" bundle:nil];
Switching controllers
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 information, switch controllers
[[Nsnotificationcenter Defaultcenter] postnotificationname:@ "logoutsuccess" object:nil];
3Token value Introduction
token value : Login token. Use the token value to determine the user's login status. Similar to the long string after MD5 encryption.
After a user logs on successfully, a unique value is generated on the backend (server side) based on user information. This value is the token value.
Basic Use :
The token value is saved on the server side (the database), and the token value is used later to retrieve the corresponding user information and to determine the user's login status.
After the user logs on successfully, the server returns the generated token value to the client, and the token value is also saved on the client. (Typically, you can save it in a cookie, or you can manually determine where you saved it, such as preferences.).
This token value (passed as a parameter to the server) is automatically attached by default to the client when it sends a new network request. The server takes the token value passed by the client in contrast to the token value saved in the database to determine the user identity and login status.
To determine the login status :
If the client does not have this token value, it means that no login has been successful and prompts the user to log in.
If the client has a token value, the login is generally considered successful. No user is required to log in again (Enter account and password information).
token value Extension :
token value has expiration time :
The general app, token, is worth more than 1 years of failure time.
Special app: Bank app/Payment class App:token value expiration time is about 15 minutes.
Once the user information changes (password change), the new token value will be generated on the server, and the original token value will be invalidated. You need to re-enter the account and password to get the new token value generated.
Uniqueness Judgment: Each time you log in, a new token value is generated. The original token value is invalidated. Use time to determine the difference between logins.
4MD5 Encryption--(Information-Digest algorithm) one of the hashing algorithms
Transforms an arbitrary length byte string into a hexadecimal large integer of a certain length.