// // ViewController.m // 公钥密钥加密解密 // // Created by dllo on 16/1/12. // Copyright © 2016年 HaiTeng. All rights reserved. // #import "ViewController.h" #import "RSA.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor yellowColor]; /* //公钥秘钥加密解密: //非对称加密解密(公钥,加密后,只有密钥能解),通过公钥进行加密,秘钥进行解密. //通常,公钥放在客户端, 秘钥存放在数据库. **密钥必须要保密**,不能泄露. //通常用于支付,如:微信,QQ,支付宝,银联..都使用非对称加密,解密方式. */ //公钥字符串 NSString *publicKey = @"-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEChqe80lJLTTkJD3X3Lyd7Fj+\nzuOhDZkjuLNPog3YR20e5JcrdqI9IFzNbACY/GQVhbnbvBqYgyql8DfPCGXpn0+X\nNSxELIUw9Vh32QuhGNr3/TBpechrVeVpFPLwyaYNEk1CawgHCeQqf5uaqiaoBDOT\nqeox88Lc1ld7MsfggQIDAQAB\n-----END PUBLIC KEY-----"; //公钥加密 NSString *string = @"海腾"; /*要加密的东西*/ //加密 NSString *encryStr = [RSA encryptString:string publicKey:publicKey]; NSLog(@"%@",encryStr); /*打印看看,加密后的字符串*/ //私钥解密 //私钥字符串 NSString *privateKey = @"-----BEGIN RSA PRIVATE KEY-----\nMIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMQKGp7zSUktNOQk\nPdfcvJ3sWP7O46ENmSO4s0+iDdhHbR7klyt2oj0gXM1sAJj8ZBWFudu8GpiDKqXw\nN88IZemfT5c1LEQshTD1WHfZC6EY2vf9MGl5yGtV5WkU8vDJpg0STUJrCAcJ5Cp/\nm5qqJqgEM5Op6jHzwtzWV3syx+CBAgMBAAECgYEApSzqPzE3d3uqi+tpXB71oY5J\ncfB55PIjLPDrzFX7mlacP6JVKN7dVemVp9OvMTe/UE8LSXRVaFlkLsqXC07FJjhu\nwFXHPdnUf5sanLLdnzt3Mc8vMgUamGJl+er0wdzxM1kPTh0Tmq+DSlu5TlopAHd5\nIqF3DYiORIen3xIwp0ECQQDj6GFaXWzWAu5oUq6j1msTRV3mRZnx8Amxt1ssYM0+\nJLf6QYmpkGFqiQOhHkMgVUwRFqJC8A9EVR1eqabcBXbpAkEA3DQfLVr94vsIWL6+\nVrFcPJW9Xk28CNY6Xnvkin815o2Q0JUHIIIod1eVKCiYDUzZAYAsW0gefJ49sJ4Y\niRJN2QJAKuxeQX2s/NWKfz1rRNIiUnvTBoZ/SvCxcrYcxsvoe9bAi7KCMdxObJkn\nhNXFQLav39wKbV73ESCSqnx7P58L2QJABmhR2+0A5EDvvj1WpokkqPKmfv7+ELfD\nHQq33LvU4q+N3jPn8C85ZDedNHzx57kru1pyb/mKQZANNX10M1DgCQJBAMKn0lEx\nQH2GrkjeWgGVpPZkp0YC+ztNjaUMJmY5g0INUlDgqTWFNftxe8ROvt7JtUvlgtKC\nXdXQrKaEnpebeUQ=\n-----END RSA PRIVATE KEY-----"; //私钥解密 NSString *decryStr = [RSA decryptString:encryStr privateKey:privateKey]; NSLog(@"%@",decryStr); /* 打印看看 */ //字典. 进行加密解密 NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"James",@"name", nil]; //转化为NSData(NSData万能转化) NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil]; //公钥加密 NSData *encryData = [RSA encryptData:data publicKey:publicKey]; NSLog(@"%@",encryData); /*看下加密后的Data也就是字典*/ //服务器 //私钥解密 NSData *dencryData = [RSA decryptData:encryData privateKey:privateKey]; //Data -> 字典 NSDictionary *dic1 = [NSJSONSerialization JSONObjectWithData:dencryData options:0 error:nil]; NSLog(@"%@",dic1); /*打印看看解密后的字典*/ //练习,解密,服务器加密返回的字符串,所有这里用公钥进行解密 // 服务器用私钥已经加过密的签名 NSString *encryptStr = @"F+feHOH6807tUV/drvepAMzKlVKRsoDFRkFNfhS9kgVoBt2E6OnUIVw12l608yQGWiqtq8rgZgMY/VCQYZB+3r2rhDlyZ2fjo00sUFOp5BkNPFTs/NpQAolD6V3ifNgDmBQP92uVbxbod1pLRwLC0wLOhr5flQXvvobeg5KrDeE="; NSString *a = [RSA decryptString:encryptStr publicKey:publicKey]; NSLog(@"------ %@",a); }
时间: 2024-12-28 01:38:29