公私钥加密

下面是代码实现 步骤是粗暴简单

//公钥,用于加密数据. 用于公开, 一般存放在数据提供方, 例如iOS客户端.

NSString *pubkey = @"-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEChqe80lJLTTkJD3X3Lyd7Fj+\nzuOhDZkjuLNPog3YR20e5JcrdqI9IFzNbACY/GQVhbnbvBqYgyql8DfPCGXpn0+X\nNSxELIUw9Vh32QuhGNr3/TBpechrVeVpFPLwyaYNEk1CawgHCeQqf5uaqiaoBDOT\nqeox88Lc1ld7MsfggQIDAQAB\n-----END PUBLIC KEY-----";

//私钥,用于解密数据. 必须保密, 私钥泄露会造成安全问题.

NSString *privkey = @"-----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 *string = @"王新行";

NSString *encPubKey; // 公钥加密

NSString *decPrivKey; // 私钥解密

//使用RSA进行加密

// 第一个参数 : 要加密的数据

// 第二个参数 : 公钥

// RSA加密之后得到的结果 每一次都不一样,但是 都可以通过同一个私钥进行解密

encPubKey = [RSA encryptString:string publicKey:pubkey];

NSLog(@"encPudKey === %@", encPubKey);

decPrivKey = [RSA decryptString:encPubKey privateKey:privkey];

NSLog(@"decPuivkey ===== %@", decPrivKey);

NSString *resultString = @"Y3nWGRaQzldfNtbuUZE9RH73LUGIHOtjg6hE25cLSisNPMBKm0Ikps0gEgPBLdDmysWWwmkPZfsMwG1tt3S9+OnSct/BhaT4bGt5pBZ11Db915a+FTe2RvaIM59nKmTG66b9NOo6CoYp+rZimFamQkdNnxW4SMQleujoRlZjyL0=";

decPrivKey = [RSA decryptString:resultString privateKey:privkey];

NSLog(@"decPrivKey ======= %@",decPrivKey);

你可能感兴趣的:(公私钥加密)