RSA algorithm is an asymmetric encryption algorithm, which is often used for encrypting data transmission. If the number digest algorithm is combined, it can also be used for file signing.
This article discusses how to use RSA to transfer encrypted data in iOS.
This article environment
- Mac OS
- OPENSSL-1.0.1J, OpenSSL requires a 1.x version and is recommended for use with [homebrew] (http://brew.sh/) installation.
- Java 8
RSA Fundamentals
RSA encrypts the data using the "key pair". Before encrypting and decrypting data, you need to be a public key and private key.
- Public key: Used to encrypt data. Used for public, typically stored in data providers, such as iOS clients.
- Private key: Used to decrypt data. Must be kept secret and private key leaks can create security issues.
The Security.framework in iOS provides support for the RSA algorithm. This method requires the key pair to be processed, the certificate is generated according to public key, and the secret key of the P12 format is generated by private key.
In addition to Secruty.framework, the OpenSSL library can be compiled into an iOS project, which provides a more flexible way to use it.
This article uses the security.framework approach to RSA.
Using OpenSSL to generate a key pair
Github gist:https://gist.github.com/lvjian700/635368d6f1e421447680
Shell Code
- #!/usr/bin/env Bash
- echo "generating RSA key pair ..."
- echo "1024x768 RSA Key:private_key.pem"
- OpenSSL genrsa-out Private_key.pem 1024x768
- 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-in rsacertreq.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 is used in IOS. "
- OpenSSL pkcs12-export-out Private_key.p12-inkey private_key.pem-in rsacert.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."
Tips:
- When the certificate is created, Terminal prompts for the certificate information. Enter the corresponding information according to the wizard OK.
- When you create a P12 key, you are prompted for a password, which must be remembered and then used.
- If there is a problem with the above instructions, please refer to the latest OpenSSL official documentation, whichever is official. Before searching for instructions on the Internet, after being caught in a lap, they would still be chewing on official documents. Each instruction document will have a few sample at the end, refer to sample.
How iOS loads Use certificates
Add the following code to the project:
https://gist.github.com/lvjian700/204c23226fdffd6a505d
The code relies on the BASE64 encoding library, and if you use Cocoapods, you can say the following dependencies added to Podfile:
Ruby Code
- Pod ' base64nl ', ' ~> 1.2 '
Encrypt data
CPP Code
- 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]__ returns the decrypted Base64 encoded string:
Console out wrote encrypted data:i1mnu33cu7qcgac9uo2bxv0vyfjsqawyc3dz+p8jm0g2emcclarrr5r2xlddxqvtkj+ujbes7tt+ Agkk1ndoqvojby+jkmrpachmrbv2jvi3cezyqg955jrdsau21nzqe8xwtec3yzp+tacpdp4b3cyy0u8n2rcsfwyxu0ykpxe=
Decrypt data
Decoding under iOS requires the private key to be loaded before decoding the data. Decode the time first Base64 decode, and then in the private key decrypt encrypted data.
CPP Code
- NSLog (@"decryptor using RSA");
- [RSA Loadprivatekeyfromfile:[[nsbundle Mainbundle] pathforresource:@"Private_key" oftype:@"P12"] password:@ "123456"];
- NSString *decryptedstring = [RSA rsadecryptstring:encryptedstring];
- NSLog (@"decrypted data:%@", decryptedstring);
The decrypted data is then output:
Console writes decryptor using RSA
Decrypted Data:hello ~
Decoding data on the server side (Java)
Decoding in Java requires the PKCS8 private key generated using the following instructions:
Gen Shell wrote the OpenSSL pkcs8-topk8-in private_key.pem-out pkcs8_private_key.pem-nocrypt
Specific decoding steps:
- Load PKCS8 private key:
- Read private key file
- Remove the "-----begin private Key-----" and "-----begin private Key-----" from the private key tail
- Remove a line break from private key
- BASE64 decoding of processed data
- Generates a private key using the decoded data.
- Decrypt data:
- BASE64 Decoding of data
- Use RSA decrypt data.
Here I decode "Hello ~" encrypted data from iOS in Java:
Java code
- Import javax.crypto.BadPaddingException;
- Import Javax.crypto.Cipher;
- Import javax.crypto.IllegalBlockSizeException;
- Import javax.crypto.NoSuchPaddingException;
- Import java.io.IOException;
- Import Java.nio.charset.Charset;
- Import Java.nio.file.Files;
- Import java.nio.file.Paths;
- Import java.security.InvalidKeyException;
- Import Java.security.KeyFactory;
- Import java.security.NoSuchAlgorithmException;
- Import Java.security.PrivateKey;
- Import java.security.spec.InvalidKeySpecException;
- Import Java.security.spec.PKCS8EncodedKeySpec;
- Import java.util.Base64;
- Import static Java.lang.String.format;
- Public class Encryptor {
- public static void Main (string[] args) throws IOException, NoSuchAlgorithmException, Invalidkeyspecexception, Nosuchpaddingexception, InvalidKeyException, Badpaddingexception, illegalblocksizeexception {
- Privatekey Privatekey = Readprivatekey ();
- String message = "afppafptbmbomzd55cjcfrvawuw7+hzkaq16od+6fp0lwz/yc+rshb/ 8cf5bpbluao2eunchnzekxzpipqtcccitkvk6hcfkzs0sn9wohlqfyt+i4f/czitwbvajaldz7mkyoiuvm+raxmwrs+ 7mlkgyxkd5cfpxestxpmsa5nk= ";
- SYSTEM.OUT.PRINTLN (Format ("-Decrypt RSA encrypted base64 message:%s", message));
- //Hello ~, encrypted and encoded with BASE64:
- byte[] data = encrypteddata (message);
- String Text = Decrypt (privatekey, data);
- System.out.println (text);
- }
- private static String decrypt (Privatekey Privatekey, byte[] data) throws NoSuchAlgorithmException, Nosuchpaddingexception, InvalidKeyException, Illegalblocksizeexception, badpaddingexception {
- Cipher Cipher = cipher.getinstance ("rsa/ecb/pkcs1padding");
- Cipher.init (Cipher.decrypt_mode, Privatekey);
- byte[] Decrypteddata = cipher.dofinal (data);
- return new String (Decrypteddata);
- }
- private static byte[] EncryptedData (String base64text) {
- return Base64.getdecoder (). Decode (Base64text.getbytes (Charset.forname ("UTF-8"));
- }
- private static Privatekey Readprivatekey () throws IOException, NoSuchAlgorithmException, invalidkeyspecexception {
- byte[] Privatekeydata = files.readallbytes (
- Paths.get ("/users/twer/macspace/ios_workshop/security/securitylogin/tools/pkcs8_private_key.pem"));
- byte[] Decodedkeydata = Base64.getdecoder ()
- . Decode (new String (privatekeydata)
- . ReplaceAll ("-----\\w+ PRIVATE KEY-----", " ")
- . replace ("\ n", "" ")
- . GetBytes ());
- return Keyfactory.getinstance ("RSA"). Generateprivate (new Pkcs8encodedkeyspec (Decodedkeydata));
- }
- }
The console will output "Hello ~" after the line succeeds.
Summarize
This encrypted transmission will be used in the online banking app. Although the net bank will use the whole station HTTPS scheme, but in the secure login this block will use another certificate to encrypt the login information, so that the double-layer to ensure data security.
Based on RSA encryption and decryption algorithm, it can also be used in digital signature scenarios. I'll be free later. How to use the RSA algorithm to implement the digital signature of the file.
Resources
- Openssl Document
- Load Private Key in Java
- Cryptographic Services Guide
Encrypt and decrypt data using RSA in iOS