// // LoginViewController.m // YHScrollView_Test // // Created by Jim on 2021/9/4. // #import "LoginViewController.h" #import "AppDelegate.h" #import <OpenVPNAdapter/OpenVPNAdapterPacketFlow.h> #import "ZZWHudHelper.h" #import <CommonCrypto/CommonCrypto.h> #import <GTMBase64/GTMBase64.h> static NSString * const serviceName = @"qlvpn.vpn_config"; #define gkey @"7A57A5A743894A0E" //自行修改 #define gIv @"361DB34E68A4A9B3" //自行修改 @interface LoginViewController ()<UITextFieldDelegate>{ CGFloat subHeight; } @property (nonatomic,strong)UITextField * accountTextField; @property (nonatomic,strong)UITextField * passwordTextField; @end @implementation LoginViewController -(void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self]; } -(void)stopVpn:(NSNotification *)notification{ NSLog(@"关闭VPN"); [self.providerManager.connection stopVPNTunnel]; } //键盘回收 -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { for(UIView *view in self.view.subviews) { [view resignFirstResponder]; } } //移动UIView -(void)transformView:(NSNotification *)aNSNotification { //获取键盘弹出前的Rect NSValue *keyBoardBeginBounds=[[aNSNotification userInfo]objectForKey:UIKeyboardFrameBeginUserInfoKey]; CGRect beginRect=[keyBoardBeginBounds CGRectValue]; //获取键盘弹出后的Rect NSValue *keyBoardEndBounds=[[aNSNotification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey]; CGRect endRect=[keyBoardEndBounds CGRectValue]; //获取键盘位置变化前后纵坐标Y的变化值 CGFloat deltaY=endRect.origin.y-beginRect.origin.y; NSLog(@"看看这个变化的Y值:%f",deltaY); //在0.25s内完成self.view的Frame的变化,等于是给self.view添加一个向上移动deltaY的动画 [UIView animateWithDuration:0.25f animations:^{ [self.view setFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y+deltaY, self.view.frame.size.width, self.view.frame.size.height)]; }]; // //获取键盘的高度 // [UIView animateWithDuration:0.2 animations:^{ // self.view.transform = CGAffineTransformMakeTranslation(0, -190); // }]; } - (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(stopVpn:) name:@"applicationWillTerminate" object:nil]; //键盘弹出和收起通知 // [[NSNotificationCenter defaultCenter] addObserver:self // selector:@selector(keyboardWillShow:) // name:UIKeyboardWillShowNotification // object:nil]; // // [[NSNotificationCenter defaultCenter] addObserver:self // selector:@selector(keyboardWillHide:) // name:UIKeyboardWillHideNotification // object:nil]; //注册观察键盘的变化 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(transformView:) name:UIKeyboardWillChangeFrameNotification object:nil]; UIImageView *topbackImageV = [[UIImageView alloc] init]; topbackImageV.image = [UIImage imageNamed:@"top_back_image"]; [self.view addSubview:topbackImageV]; [topbackImageV mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(0); make.centerX.mas_equalTo(0); make.width.mas_equalTo(KScreenWidth); make.height.mas_equalTo(Auto_Width(300)); }]; UIImageView *titleImageV = [[UIImageView alloc] init]; titleImageV.image = [UIImage imageNamed:@"title_image"]; [self.view addSubview:titleImageV]; [titleImageV mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(topbackImageV.mas_bottom).offset(2); make.centerX.equalTo(topbackImageV); make.width.mas_equalTo(Auto_Width(206)); make.height.mas_equalTo(Auto_Width(32)); }]; UIView *lineViewOne = [UIView new]; lineViewOne.backgroundColor = UIColorFromRGB(0xcccccc); [self.view addSubview:lineViewOne]; [lineViewOne mas_makeConstraints:^(MASConstraintMaker *make) { make.centerX.equalTo(titleImageV); make.width.mas_equalTo(Auto_Width(270)); make.top.equalTo(titleImageV.mas_bottom).offset(IS_iPhoneX ? 110 : 55); make.height.mas_equalTo(1); }]; UIImageView *userIcon = [UIImageView new]; userIcon.image = [UIImage imageNamed:@"username_icon"]; [self.view addSubview:userIcon]; [userIcon mas_makeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(lineViewOne.mas_left).offset(0); make.bottom.equalTo(lineViewOne.mas_bottom).offset(-15); make.size.mas_equalTo(CGSizeMake(15, 15.5)); }]; _accountTextField = [[UITextField alloc]init]; _accountTextField.textColor = UIColorFromRGB(0x333333); _accountTextField.tintColor = UIColorFromRGB(0x333333); _accountTextField.returnKeyType=UIReturnKeyNext; _accountTextField.autocapitalizationType = UITextAutocapitalizationTypeNone; _accountTextField.autocorrectionType = UITextAutocorrectionTypeNo;//去掉首字母大写 _accountTextField.delegate=self; _accountTextField.font=[UIFont systemFontOfSize:13]; _accountTextField.backgroundColor=[UIColor clearColor]; _accountTextField.keyboardType = UIKeyboardTypeASCIICapable; _accountTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入用户名" attributes:@{NSForegroundColorAttributeName:UIColorFromRGB(0xcccccc),NSFontAttributeName:[UIFont systemFontOfSize:13]}]; [_accountTextField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged]; [self.view addSubview:_accountTextField]; [_accountTextField mas_makeConstraints:^(MASConstraintMaker *make) { make.left.mas_equalTo(userIcon.mas_right).offset(5.0); make.centerY.equalTo(userIcon.mas_centerY).offset(0); make.right.equalTo(lineViewOne.mas_right).offset(-10.0);; make.height.mas_equalTo(30.0); }]; UIView *lineViewTwo = [UIView new]; lineViewTwo.backgroundColor = UIColorFromRGB(0xcccccc); [self.view addSubview:lineViewTwo]; [lineViewTwo mas_makeConstraints:^(MASConstraintMaker *make) { make.centerX.equalTo(lineViewOne); make.width.mas_equalTo(Auto_Width(270)); make.top.equalTo(lineViewOne.mas_bottom).offset(70); make.height.mas_equalTo(1); }]; UIImageView *passIcon = [UIImageView new]; passIcon.image = [UIImage imageNamed:@"password_icon"]; [self.view addSubview:passIcon]; [passIcon mas_makeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(lineViewTwo.mas_left).offset(0); make.bottom.equalTo(lineViewTwo.mas_bottom).offset(-15); make.size.mas_equalTo(CGSizeMake(15, 15.5)); }]; _passwordTextField = [[UITextField alloc]init]; _passwordTextField.textColor = UIColorFromRGB(0x333333); _passwordTextField.tintColor = UIColorFromRGB(0x333333); _passwordTextField.returnKeyType=UIReturnKeyNext; _passwordTextField.delegate=self; _passwordTextField.font=[UIFont systemFontOfSize:13]; _passwordTextField.backgroundColor=[UIColor clearColor]; _passwordTextField.autocapitalizationType = UITextAutocapitalizationTypeNone; _passwordTextField.autocorrectionType = UITextAutocorrectionTypeNo;//去掉首字母大写 _passwordTextField.keyboardType = UIKeyboardTypeASCIICapable; _passwordTextField.secureTextEntry = YES; [_passwordTextField setAutocapitalizationType:UITextAutocapitalizationTypeNone]; _passwordTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入密码" attributes:@{NSForegroundColorAttributeName:UIColorFromRGB(0xcccccc),NSFontAttributeName:[UIFont systemFontOfSize:13]}]; [_passwordTextField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged]; [self.view addSubview:_passwordTextField]; [_passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) { make.left.mas_equalTo(passIcon.mas_right).offset(5.0); make.centerY.equalTo(passIcon.mas_centerY).offset(0); make.right.equalTo(lineViewTwo.mas_right).offset(-10.0);; make.height.mas_equalTo(30.0); }]; UIButton *selectBtn = [UIButton buttonWithType:UIButtonTypeCustom]; selectBtn.tag = 339; [selectBtn setBackgroundImage:[UIImage imageNamed:@"sure_select_icon"] forState:UIControlStateSelected]; [selectBtn setBackgroundImage:[UIImage imageNamed:@"sure_normal_icon"] forState:UIControlStateNormal]; [selectBtn addTarget:self action:@selector(rememberPassword:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:selectBtn]; [selectBtn mas_makeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(lineViewTwo.mas_left).offset(0); make.top.equalTo(lineViewTwo.mas_bottom).offset(20); make.size.mas_equalTo(CGSizeMake(15, 15)); }]; UILabel *tipLabel = [UILabel new]; tipLabel.textColor = UIColorFromRGB(0x333333); tipLabel.font = [UIFont systemFontOfSize:13]; tipLabel.text = @"记住密码"; [self.view addSubview:tipLabel]; [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) { make.centerY.mas_equalTo(selectBtn); make.left.equalTo(selectBtn.mas_right).offset(5); make.height.mas_equalTo(15); }]; UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom]; [loginBtn setBackgroundColor:UIColorFromRGB(0x1679FF)]; [loginBtn setTitle:@"登 录" forState:UIControlStateNormal]; [loginBtn setTitleColor:UIColorFromRGB(0xFFFFFF) forState:UIControlStateNormal]; loginBtn.titleLabel.font = [UIFont systemFontOfSize:17]; [loginBtn addTarget:self action:@selector(clickLoginHandleEvent) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:loginBtn]; [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(lineViewTwo.mas_left).offset(0); make.top.equalTo(selectBtn.mas_bottom).offset(40); make.right.equalTo(lineViewTwo.mas_right).offset(0); make.height.mas_equalTo(40); }]; if ([[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"kuid_password"]]) { self.passwordTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"kuid_password"]]; selectBtn.selected = YES; } if ([[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"kuid_userID"]]) { self.accountTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"kuid_userID"]]; } } -(void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; NSDictionary *dic =[[NSUserDefaults standardUserDefaults] objectForKey:@"token"]; NSLog(@"viewWillAppear NSUserDefaults 的token数据 %@",dic); self.zx_navBarBackgroundColor = [UIColor clearColor]; self.zx_navLineViewBackgroundColor = [UIColor clearColor]; // [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault]; // self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init]; // [self.navigationController setNavigationBarHidden:YES animated:YES]; //// self.navigationController.navigationBar.layer.masksToBounds = YES; // UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"]; // if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) { // statusBar.backgroundColor = [UIColor clearColor]; // } } -(void)viewWillDisappear:(BOOL)animated{ [super viewWillDisappear:animated]; NSDictionary *dic =[[NSUserDefaults standardUserDefaults] objectForKey:@"token"]; NSLog(@"viewWillDisappear NSUserDefaults 的token数据 %@",dic); // [self.navigationController setNavigationBarHidden:NO animated:YES]; } //-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ // [self.view endEditing:YES]; //} //记录键盘是否移动过; static bool isMove; - (void)keyboardWillShow:(NSNotification *)notification { //获取键盘的高度 NSDictionary *userInfo = [notification userInfo]; NSValue *value = [userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey]; CGRect keyboardRect = [value CGRectValue]; int height = keyboardRect.size.height; [UIView animateWithDuration:0.2 animations:^{ //view的最大y值 CGFloat maxY = CGRectGetMaxY(self.view.frame); //比较view和键盘的y判断是否需要移动 isMove = maxY > height ? YES:NO; if (isMove) { // //移动的距离 // self->subHeight = maxY-2*height; // //移动,注意不能直接改frame; // self.view.transform = CGAffineTransformMakeTranslation(0, self.view.transform.ty-self->subHeight); } self.view.transform = CGAffineTransformMakeTranslation(0, -190); }]; } - (void)keyboardWillHide:(NSNotification *)notification { [UIView animateWithDuration:0.1 animations:^{ //如果移动了,移动回来. if (isMove) { // self.view.transform =CGAffineTransformMakeTranslation(0,self.view.transform.ty+self->subHeight); } self.view.transform =CGAffineTransformMakeTranslation(0,0); }]; } #pragma mark - 控制字符输入 - (void)textFieldChange:(UITextField *)textField{ NSString *toBeString = textField.text; if (textField==self.passwordTextField) { if (toBeString.length>64) { textField.text = [toBeString substringToIndex:64]; } } if (textField==self.accountTextField) { if (toBeString.length>64) { textField.text = [toBeString substringToIndex:64]; } } } -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if([[[textField textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textField textInputMode] primaryLanguage]) { return NO; } if (textField==self.passwordTextField) { if ([Untis Fish_haveEmoji:string]) {//表情不能输入 return NO; } if(string.length>1) { if ([Untis Fish_haveChinese:string]) {//有中文不能输入 return NO; } } }else if (textField==self.accountTextField){ return YES; } return YES; } -(BOOL)textFieldShouldReturn:(UITextField *)textField { if (textField==self.accountTextField) { [self.passwordTextField becomeFirstResponder]; } if (textField==self.passwordTextField) { [self.view endEditing:YES]; } return YES; } #pragma mark --- 记住密码 -(void)rememberPassword:(UIButton *)sender{ if (!self.accountTextField.text.length) { [self.view makeToast:@"您还没有输入用户名哦!"]; return; } if (!self.passwordTextField.text.length) { [self.view makeToast:@"您还没有输入密码哦!"]; return; } sender.selected = !sender.selected; if (sender.selected) { [[NSUserDefaults standardUserDefaults] setObject:self.accountTextField.text forKey:[NSString stringWithFormat:@"kuid_userID"]]; // 记住密码 [[NSUserDefaults standardUserDefaults] setObject:self.passwordTextField.text forKey:[NSString stringWithFormat:@"kuid_password"]]; [[NSUserDefaults standardUserDefaults] synchronize]; }else{ [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:[NSString stringWithFormat:@"kuid_userID"]]; [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:[NSString stringWithFormat:@"kuid_password"]]; [[NSUserDefaults standardUserDefaults] synchronize]; } } #pragma mark--- 登录 -(void)clickLoginHandleEvent{ if (!self.accountTextField.text.length) { [self.view makeToast:@"您还没有输入账号哦!"]; return; } if (!self.passwordTextField.text.length) { [self.view makeToast:@"您还没有输入密码哦!"]; return; } //收起键盘 [self.view endEditing:YES]; ZZWHudHelper *hud = [ZZWHudHelper shareInstance]; [hud showHudInSuperView:self.view withText:@"登录中" withType:HudModeDefault]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; request.timeoutInterval = 15; [request setHTTPMethod:@"POST"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; if (Development == 1) { [request setURL:[NSURL URLWithString:@"http://192.168.20.110:8083/api/logininfo/login"]]; }else{ [request setURL:[NSURL URLWithString:@"http://www.xy-zhsw.cn/common/logininfo/login"]]; } //保存账号密码 [[NSUserDefaults standardUserDefaults] setValue:self.accountTextField.text forKey:@"account"]; [[NSUserDefaults standardUserDefaults] setValue:self.passwordTextField.text forKey:@"password"]; [[NSUserDefaults standardUserDefaults] synchronize]; //新增密码AES加密 NSString *password = [self AES128Encrypt:self.passwordTextField.text]; // NSString *password =self.passwordTextField.text; NSDictionary *requestDic = @{@"userNo":self.accountTextField.text, @"password":password }; [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:requestDic options:NSJSONWritingPrettyPrinted error:nil]]; NSURLSession *session = [NSURLSession sharedSession]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW,HudDuration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (!error) { dispatch_async(dispatch_get_main_queue(), ^{ NSString *respJSON = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog(@"返回数据JSON: %@", respJSON); NSString *results = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding]; NSDictionary *dataInfo=[results jsonValue]; NSLog(@"info == %@",dataInfo); if ([dataInfo[@"code"] integerValue] == 200) { NSDictionary *dataDic = dataInfo[@"data"]; NSMutableDictionary *dict = [NSMutableDictionary dictionary]; [dict setValue:password forKey:@"password"]; [dict setValue:dataDic[@"token"] forKey:@"token"]; [dict setValue:dataDic[@"userNo"] forKey:@"userNo"]; [dict setValue:dataDic[@"highest"] forKey:@"highest"]; [dict setValue:dataDic[@"isRestPassword"] forKey:@"isRestPassword"]; [[NSUserDefaults standardUserDefaults] setObject:dict forKey:@"token"]; [[NSUserDefaults standardUserDefaults] synchronize]; hud.text = @"登录成功"; hud.mode = HudModeTitle; dispatch_after(dispatch_time(DISPATCH_TIME_NOW,0.75 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ [hud hideHudInSuperView:self.view]; [NETunnelProviderManager loadAllFromPreferencesWithCompletionHandler:^(NSArray<NETunnelProviderManager *> * _Nullable managers, NSError * _Nullable error) { self.providerManager = managers.firstObject; if (self.providerManager == nil) { self.providerManager = [[NETunnelProviderManager alloc] init]; self.providerManager.localizedDescription = @"myVPN"; } [self connectTOVPN]; }]; }); }else{ hud.text = dataInfo[@"message"]; hud.mode = HudModeTitle; dispatch_after(dispatch_time(DISPATCH_TIME_NOW,HudDuration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ [hud hideHudInSuperView:self.view]; }); } }); }else{ hud.text = @"登录失败"; hud.mode = HudModeTitle; dispatch_after(dispatch_time(DISPATCH_TIME_NOW,HudDuration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ [hud hideHudInSuperView:self.view]; }); NSLog(@"error == %@",error); } }]; [dataTask resume]; }); } -(void)connectTOVPN{ ZZWHudHelper *hud = [ZZWHudHelper shareInstance]; [hud showHudInSuperView:self.view withText:@"VPN连接中" withType:HudModeDefault]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW,HudDuration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ [self.providerManager loadFromPreferencesWithCompletionHandler:^(NSError * _Nullable error) { if (error != nil) { // return; } NSURL *configurationFileURL = [[NSBundle mainBundle] URLForResource:@"vpn_config" withExtension:@"ovpn"]; NSData *configurationFileContent = [NSData dataWithContentsOfURL:configurationFileURL]; NETunnelProviderProtocol *tunnelProtocol = [[NETunnelProviderProtocol alloc] init]; tunnelProtocol.serverAddress = @"36.133.215.233"; tunnelProtocol.providerBundleIdentifier = [[[NSBundle mainBundle] bundleIdentifier] stringByAppendingString:@".PacketTunnelProvider"]; tunnelProtocol.providerConfiguration = @{@"ovpn" : configurationFileContent}; tunnelProtocol.username = self.accountTextField.text; self.providerManager.protocolConfiguration = tunnelProtocol; // self.providerManager.localizedDescription = @""; [self.providerManager setEnabled:YES]; [self.providerManager saveToPreferencesWithCompletionHandler:^(NSError * _Nullable error) { [self.providerManager loadFromPreferencesWithCompletionHandler:^(NSError * _Nullable error) { if (error != nil) { return; } NSError *error2 = nil; // [self.providerManager.connection startVPNTunnelWithOptions:nil andReturnError:&error2]; [self.providerManager.connection startVPNTunnelAndReturnError:&error2]; if (error2 == nil) { // NSLog(@"ymf:::%@",error2); /** 进入主页*/ hud.text = @"VPN连接成功"; hud.mode = HudModeTitle; dispatch_after(dispatch_time(DISPATCH_TIME_NOW,0.75 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ [hud hideHudInSuperView:self.view]; [AppDelegate startMainViewController]; }); } }]; }]; }]; }); } -(void)goToMainView{ [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"login"]; [[NSUserDefaults standardUserDefaults] synchronize]; [AppDelegate startMainViewController]; } -(NSMutableDictionary*)newSearchDictionary:(NSString*)identifier{ NSMutableDictionary *searchDictionary = [[NSMutableDictionary alloc] init]; [searchDictionary setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass]; NSData *encodedIdentifier = [identifier dataUsingEncoding:NSUTF8StringEncoding]; [searchDictionary setObject:encodedIdentifier forKey:(__bridge id)kSecAttrGeneric]; [searchDictionary setObject:encodedIdentifier forKey:(__bridge id)kSecAttrAccount]; [searchDictionary setObject:serviceName forKey:(__bridge id)kSecAttrService]; return searchDictionary; } -(NSData*)searchKeychainCopyMatching:(NSString*)identifier{ NSMutableDictionary *searchDictionary = [self newSearchDictionary:identifier]; // Add search attributes [searchDictionary setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit]; // Add search return types // Must be persistent ref !!!! [searchDictionary setObject:@YES forKey:(__bridge id)kSecReturnPersistentRef]; CFTypeRef result = NULL; SecItemCopyMatching((__bridge CFDictionaryRef)searchDictionary, &result); return (__bridge_transfer NSData *)result; } -(BOOL)createKeychainValue:(NSString*)password forIdentifier:(NSString*)identifier{ NSMutableDictionary *dictionary = [self newSearchDictionary:identifier]; OSStatus status = SecItemDelete((__bridge CFDictionaryRef)dictionary); NSData *passwordData = [password dataUsingEncoding:NSUTF8StringEncoding]; [dictionary setObject:passwordData forKey:(__bridge id)kSecValueData]; status = SecItemAdd((__bridge CFDictionaryRef)dictionary, NULL); if (status == errSecSuccess) { return YES; } return NO; } -(NSString *)AES128Encrypt:(NSString *)plainText { char keyPtr[kCCKeySizeAES128+1]; memset(keyPtr, 0, sizeof(keyPtr)); [gkey getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; char ivPtr[kCCBlockSizeAES128+1]; memset(ivPtr, 0, sizeof(ivPtr)); [gIv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding]; NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding]; NSUInteger dataLength = [data length]; int diff = kCCKeySizeAES128 - (dataLength % kCCKeySizeAES128); int newSize = 0; if(diff > 0) { newSize = dataLength + diff; } char dataPtr[newSize]; memcpy(dataPtr, [data bytes], [data length]); for(int i = 0; i < diff; i++) { dataPtr[i + dataLength] = 0x00; } size_t bufferSize = newSize + kCCBlockSizeAES128; void *buffer = malloc(bufferSize); memset(buffer, 0, bufferSize); size_t numBytesCrypted = 0; CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, 0x0000, //No padding keyPtr, kCCKeySizeAES128, ivPtr, dataPtr, sizeof(dataPtr), buffer, bufferSize, &numBytesCrypted); if (cryptStatus == kCCSuccess) { NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted]; return [GTMBase64 stringByEncodingData:resultData]; } free(buffer); return nil; } -(NSString *)AES128Decrypt:(NSString *)encryptText { char keyPtr[kCCKeySizeAES128 + 1]; memset(keyPtr, 0, sizeof(keyPtr)); [gkey getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; char ivPtr[kCCBlockSizeAES128 + 1]; memset(ivPtr, 0, sizeof(ivPtr)); [gIv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding]; NSData *data = [GTMBase64 decodeData:[encryptText dataUsingEncoding:NSUTF8StringEncoding]]; NSUInteger dataLength = [data length]; size_t bufferSize = dataLength + kCCBlockSizeAES128; void *buffer = malloc(bufferSize); size_t numBytesCrypted = 0; CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, 0x0000, keyPtr, kCCBlockSizeAES128, ivPtr, [data bytes], dataLength, buffer, bufferSize, &numBytesCrypted); if (cryptStatus == kCCSuccess) { NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted]; return [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding] ; } free(buffer); return nil; } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end