通過ios實現RSA加密和解密
在加密和解密中,我們需要了解的知識有什麼事openssl;RSA加密演算法的基本原理;如何通過openssl生成最後我們需要的der和p12檔案。
廢話不多說,直接寫步驟:
第一步:openssl來生成公鑰和私鑰證書,最後需要得到公鑰證書和私鑰證書。這是在mac OX系統下顯示的證書,如果我們用文字編輯器開啟它,會發現裡面是----BEGIN RSA 開頭 並且----END RSA 結尾的一串字串。
第二步:我們需要在程式碼中寫我們的加密和機密方法,加密的字串通過公鑰進行加密,加密後的字串也可以通過私鑰進行解密。
1.在命令列下通過openssl指令獲得證書
#!/usr/bin/env bash在命令列種可能需要你的一些資訊去生成公鑰和私鑰echo "Generating RSA key pair ..." echo "1024 RSA key: private_key.pem" openssl genrsa -out private_key.pem 1024 echo "create certification require file: rsaCertReq.csr" openssl req -new -key private_key.pem -out rsaCertReq.csr echo "create certification using x509: rsaCert.crt" openssl x509 -req -days 3650 -inrsaCertReq.csr -signkey private_key.pem -out rsaCert.crt echo "create public_key.der For IOS" openssl x509 -outform der -in rsaCert.crt -out public_key.der echo "create private_key.p12 For IOS. Please remember your password. The password will be used in iOS." openssl pkcs12 -export -out private_key.p12 -inkey private_key.pem -inrsaCert.crt echo "create rsa_public_key.pem For Java" openssl rsa -in private_key.pem -out rsa_public_key.pem -pubout echo "create pkcs8_private_key.pem For Java" openssl pkcs8 -topk8 -in private_key.pem -out pkcs8_private_key.pem -nocrypt echo "finished."
Country Name (2 letter code) [AU]:CN// 國家碼
State or Province Name (full name) [Some-State]:china//地區碼
Locality Name (eg, city) []:wuhan// 本地碼
Organization Name (eg, company) [Internet Widgits Pty Ltd]:airway// 公司名稱
Organizational Unit Name (eg, section) []:airway// 部門
Common Name (eg, YOUR name) []:airway// 名字
Email Address []://郵箱
通過在命令列中的操作,我們最後可以得到我們需要的公鑰和私鑰檔案。
2.我們需要完善我們的程式碼來實現RSA加密和解密
①先請你把 public_key.der 和 private_key.p12 拖進你的Xcode專案裡去 ;
②請引入 Security.framework 以及 NSData+Base64.h/m 到專案裡;(具體程式碼看我的相關部落格)
③寫RSAEncryptor.h/m檔案到專案裡; (具體程式碼看我相關部落格)
④寫加密解密方法
加密資料
Cpp程式碼- RSAEncryptor *rsa = [[RSAEncryptor alloc] init];
- NSLog(@"encryptor using rsa");
- NSString *publicKeyPath = [[NSBundle mainBundle] pathForResource:@"public_key" ofType:@"der"];
- NSLog(@"public key: %@", publicKeyPath);
- [rsa loadPublicKeyFromFile:publicKeyPath];
- NSString *securityText = @"hello ~";
- NSString *encryptedString = [rsa rsaEncryptString:securityText];
- NSLog(@"encrypted data: %@", encryptedString);
__[rsa rsaEncryptString:securityText]__會返回decrypted base64編碼的字串:
console out 寫道 encrypted data: I1Mnu33cU7QcgaC9uo2bxV0vyfJSqAwyC3DZ+p8jm0G2EmcClarrR5R2xLDdXqvtKj+UJbES7TT+AgkK1NDoQvOJBY+jkmrpAchmRbV2jvi3cEZYQG955jrdSAu21NzQe8xWtEc3YzP+TACPdP4B3Cyy0u8N2RcSFWyxu0YKPXE=解密資料
在iOS下解碼需要先載入private key, 之後在對資料解碼. 解碼的時候先進行Base64 decode, 之後在用private key decrypt加密資料.
Cpp程式碼- NSLog(@"decryptor using rsa");
- [rsa loadPrivateKeyFromFile:[[NSBundle mainBundle] pathForResource:@"private_key" ofType:@"p12"] password:@"123456"];
- NSString *decryptedString = [rsa rsaDecryptString:encryptedString];
- NSLog(@"decrypted data: %@", decryptedString);
之後會輸出解密後的資料:
console 寫道 decryptor using rsadecrypted data: hello ~