時間戳密碼

基本介紹

動態密碼

相同的密碼明文+相同的加密算法–>因爲每次登陸時間都不同,所以每次計算出的結果也都不相同.可以充分保證密碼的安全性.

服務器會計算兩個時間值,當期時間和前一分鐘的時間(比如:第59S發送的網絡請求,一秒鐘後服務器收到並作出響應,這時服務器當前時間比客戶端發送時間晚一分鐘,仍然能夠判斷準確的值)

使用步驟

獲取MD5 首次加密的密碼

  // 1. 當前密碼
  NSString *password = @"zhang";

  // 2. hmacKey值,是對“WangPengfei” 進行 MD5加密之後的值(動態生成的)
  NSString *hmacKey = @"d3bba33b51acaa0a272de7a2f6dfa233";

加密過程

  // 1. 第一次加密:第一次 HMAC 運算
  password = [password hmacMD5StringWithKey:hmacKey];

  // 2.1 獲得當前的時間
  NSDate *date = [NSDate date];

  // 2.2 獲得當前時間的字符串
  // 實例化時間格式器
  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

  // 設置時間格式
  formatter.dateFormat = @"yyyy-MM-dd HH:mm";

  // 獲取當前時間(要和服務器保持一致)
  NSString *dateStr = [formatter stringFromDate:date];

  // 3. 將第一次加密後的密碼與當前時間的字符串拼接在一起
  password = [password stringByAppendingString:dateStr];

  // 4. 進行第二次 HMAC 加密
  password = [password hmacMD5StringWithKey:hmacKey];

訪問 loginhmac.php 接口,發送請求

創建請求

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

    // POST 要手動設置方法,因此爲可變
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    // 設置請求方法
    request.HTTPMethod = @"POST";

    // 設置請求體內容
    NSString *body = [NSString stringWithFormat:@"username=zhangsan&password=%@", password];
    request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];

    發送請求

    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }] resume];
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章