car in 場站查車鎖車 ios
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

247 行
10KB

  1. //
  2. // CarSecurityViewController.m
  3. // goodpk
  4. //
  5. // Created by 歐特儀 on 2020/2/11.
  6. // Copyright © 2020 Altob. All rights reserved.
  7. //
  8. #import "CarSecurityViewController.h"
  9. #import <CommonCrypto/CommonDigest.h>
  10. #import "CarSecurityModdel.h"
  11. #import "LockCarViewController.h"
  12. #import "CocoaSecurity.h"
  13. #import "Util.h"
  14. #define APIURL @"https://cloudservice.altob.com.tw/LockCarSerivce/api/JumpApi"
  15. #define CARSECURITY @"/CARSECURITY?"
  16. #define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
  17. @interface CarSecurityViewController ()<UITextFieldDelegate>
  18. @property (weak, nonatomic) IBOutlet UITextField *AcctInput;
  19. @property (weak, nonatomic) IBOutlet UITextField *PwdInput;
  20. @property (weak, nonatomic) IBOutlet UIButton *okBtn;
  21. @end
  22. @implementation CarSecurityViewController
  23. - (void)viewDidLoad {
  24. [super viewDidLoad];
  25. // Do any additional setup after loading the view.
  26. self.title = @"會員防竊車";
  27. [self.okBtn addTarget:self
  28. action:@selector(okButtonClicked:)
  29. forControlEvents:UIControlEventTouchUpInside
  30. ];
  31. //注册截圖通知
  32. [[NSNotificationCenter defaultCenter] addObserver:self
  33. selector:@selector(userDidTakeScreenshot:)
  34. name:UIApplicationUserDidTakeScreenshotNotification object:nil];
  35. self.AcctInput.delegate = self;
  36. self.PwdInput.delegate = self;
  37. self.AcctInput.keyboardType = UIKeyboardTypeASCIICapable;
  38. self.PwdInput.keyboardType = UIKeyboardTypeASCIICapable;
  39. }
  40. - (BOOL)textField:(UITextField* )textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString* )string
  41. {
  42. if (textField == self.AcctInput)
  43. {
  44. NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];
  45. NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
  46. if([string isEqualToString:filtered]){
  47. NSUInteger newLength = [textField.text length] + [string length] - range.length;
  48. return (newLength > 10 ) ? NO : YES;
  49. }else{
  50. return NO;
  51. }
  52. }else if(textField == self.PwdInput){
  53. NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];
  54. NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
  55. if([string isEqualToString:filtered]){
  56. NSUInteger newLength = [textField.text length] + [string length] - range.length;
  57. return (newLength > 20 ) ? NO : YES;
  58. }else{
  59. return NO;
  60. }
  61. }
  62. else
  63. {
  64. return true;
  65. }
  66. }
  67. - (void) okButtonClicked:(id)sender {
  68. if([self.AcctInput.text length] == 0){
  69. [self showAlert:@"錯誤" :@"請輸入帳號" :nil];
  70. }else if([self.PwdInput.text length] == 0){
  71. [self showAlert:@"錯誤" :@"請輸入密碼" :nil];
  72. }else{
  73. //打API
  74. [self Login:self.AcctInput.text :self.PwdInput.text];
  75. }
  76. }
  77. -(void)showAlert:(NSString *)title :(NSString *)text: (NSInteger *)type{
  78. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title
  79. message:text
  80. preferredStyle:UIAlertControllerStyleAlert ];
  81. UIAlertAction *sinupAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
  82. }];
  83. [alertController addAction:sinupAction];
  84. [self presentViewController:alertController animated:YES completion:nil];
  85. }
  86. -(void) Login:(NSString *)acct :(NSString *)pwd {
  87. CocoaSecurityResult *Nacct = [CocoaSecurity aesEncrypt:acct key:[Util sha256HashFor:@"Altob"]];
  88. NSString *mPwd = [self md5:pwd];
  89. NSString *status = @"2";
  90. //NSLog(@"加密字串:%@", [NSString stringWithFormat:@"%@%@%@%@%@", acct, @"i", mPwd, @"iii", status]);
  91. NSString *key = [self md5: [NSString stringWithFormat:@"%@%@%@%@%@", acct, @"i", mPwd, @"iii", status]];
  92. NSString *carUrl = [NSString stringWithFormat:@"%@%@acct=%@&pwd=%@&status=%@&key=%@&station=%@", APIURL, CARSECURITY, Nacct.base64, mPwd, status, key, self.station];
  93. //第一步,创建URL
  94. NSURL *url = [NSURL URLWithString:carUrl];
  95. //NSDictionary *jsonBodyDict = @{};
  96. //NSLog(@"URL: %@", url);
  97. //第二步,创建请求
  98. NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
  99. //设置请求方式为POST,默认为GET
  100. [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  101. [request setValue:@"Bearer 9a406a82bd551e6ef8e845f42f788af4" forHTTPHeaderField:@"Authorization"];
  102. [request setHTTPMethod:@"GET"];
  103. //设置参数
  104. //NSData *jsonBodyData = [NSJSONSerialization dataWithJSONObject:jsonBodyDict options:kNilOptions error:nil];
  105. //[request setHTTPBody:jsonBodyData];
  106. //新作法
  107. NSURLSession *sesson = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
  108. // 2.创建 NSURLSessionDataTask
  109. NSURLSessionDataTask *dataTask = [sesson dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  110. if (error) {
  111. NSLog(@"%@", error);
  112. // error
  113. dispatch_async(dispatch_get_main_queue(), ^{
  114. [self showAlert: @"注意" : @"您所使用的連線加密(SSL)異常,基於安全考量不提供相關功能。請確認您的連線環境及App下載來源安全。" : 0];
  115. });
  116. }else {
  117. // 获得数据后,返回到主线程更新 UI
  118. dispatch_async(dispatch_get_main_queue(), ^{
  119. NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  120. CarSecurityModdel *CS = [[CarSecurityModdel alloc] initWithString:responseString error:nil];
  121. if([CS.result_code isEqual:@"OK"]){
  122. //鎖車頁面
  123. UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"LockCar" bundle:[NSBundle mainBundle]];
  124. LockCarViewController *HelpController = [storyboard instantiateViewControllerWithIdentifier:@"LockCar"];
  125. HelpController.status = CS.result_msg;
  126. HelpController.acct = acct;
  127. HelpController.pwd = mPwd;
  128. HelpController.station = self.station;
  129. [self.navigationController pushViewController:HelpController animated:YES];
  130. }else{
  131. [self showAlert:@"錯誤" :@"登入失敗,請稍後再試" :nil];
  132. }
  133. });
  134. }
  135. }];
  136. // 3.执行 Task
  137. [dataTask resume];
  138. /*
  139. //第三步,连接服务器
  140. NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
  141. NSString *jsonString = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
  142. //NSLog(@"CAR LOGIN:%@", jsonString);
  143. CarSecurityModdel *CS = [[CarSecurityModdel alloc] initWithString:jsonString error:nil];
  144. if([CS.result_code isEqual:@"OK"]){
  145. //鎖車頁面
  146. UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"LockCar" bundle:[NSBundle mainBundle]];
  147. LockCarViewController *HelpController = [storyboard instantiateViewControllerWithIdentifier:@"LockCar"];
  148. HelpController.status = CS.result_msg;
  149. HelpController.acct = acct;
  150. HelpController.pwd = mPwd;
  151. [self.navigationController pushViewController:HelpController animated:YES];
  152. }else{
  153. [self showAlert:@"錯誤" :@"登入失敗,請稍後再試" :nil];
  154. }
  155. */
  156. }
  157. - (NSString *) md5:(NSString *) input
  158. {
  159. const char *cStr = [input UTF8String];
  160. unsigned char digest[16];
  161. CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
  162. NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
  163. for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
  164. [output appendFormat:@"%02x", digest[i]];
  165. return output;
  166. }
  167. //截屏响应
  168. - (void)userDidTakeScreenshot:(NSNotification *)notification
  169. {
  170. [self showAlert: @"注意" : @"偵測到截圖,請妥善保管截圖,避免重要資訊外流" : 0];
  171. }
  172. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler//通过调用block,来告诉NSURLSession要不要收到这个证书
  173. {
  174. // Get remote certificate
  175. SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
  176. SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
  177. // Set SSL policies for domain name check
  178. NSMutableArray *policies = [NSMutableArray array];
  179. [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)challenge.protectionSpace.host)];
  180. SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
  181. // Evaluate server certificate
  182. SecTrustResultType result;
  183. SecTrustEvaluate(serverTrust, &result);
  184. BOOL certificateIsValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
  185. // Get local and remote cert data
  186. NSData *remoteCertificateData = CFBridgingRelease(SecCertificateCopyData(certificate));
  187. NSString *hash = [[self doSha256:remoteCertificateData] base64EncodedStringWithOptions:0];
  188. // The pinnning check
  189. if ([hash isEqualToString:@"FHloZIw4i6+30lmxrUujLieHlIDpxHySL1niMxvgmpU="] && certificateIsValid) {
  190. NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
  191. completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
  192. } else {
  193. completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, NULL);
  194. }
  195. }
  196. - (NSData *)doSha256:(NSData *)dataIn {
  197. NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
  198. CC_SHA256(dataIn.bytes, dataIn.length, macOut.mutableBytes);
  199. return macOut;
  200. }
  201. @end