Encrypt and decrypt data using RSA in iOS

Source: Internet
Author: User
Tags decrypt openssl library openssl rsa openssl x509 asymmetric encryption

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
  1. #!/usr/bin/env Bash
  2. echo "generating RSA key pair ..."
  3. echo "1024x768 RSA Key:private_key.pem"
  4. OpenSSL genrsa-out Private_key.pem 1024x768
  5. echo "Create certification require FILE:RSACERTREQ.CSR"
  6. OpenSSL Req-new-key private_key.pem-out RSACERTREQ.CSR
  7. echo "Create certification using X509:RSACERT.CRT"
  8. OpenSSL x509-req-days 3650-in rsacertreq.csr-signkey private_key.pem-out rsacert.crt
  9. Echo "Create public_key.der for IOS"
  10. OpenSSL x509-outform der-in rsacert.crt-out Public_key.der
  11. Echo "Create private_key.p12 for IOS. Please remember your password. The password is used in IOS. "
  12. OpenSSL pkcs12-export-out Private_key.p12-inkey private_key.pem-in rsacert.crt
  13. Echo "Create Rsa_public_key.pem for Java"
  14. OpenSSL rsa-in private_key.pem-out rsa_public_key.pem-pubout
  15. Echo "Create Pkcs8_private_key.pem for Java"
  16. OpenSSL pkcs8-topk8-in private_key.pem-out Pkcs8_private_key.pem-nocrypt
  17. Echo "finished."

    • 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:


The code relies on the BASE64 encoding library, and if you use Cocoapods, you can say the following dependencies added to Podfile:

Ruby Code
    1. Pod ' base64nl ', ' ~> 1.2 '

Encrypt data

CPP Code
  1. Rsaencryptor *rsa = [[Rsaencryptor alloc] init];
  2. NSLog (@"encryptor using RSA");
  3. NSString *publickeypath = [[NSBundle mainbundle] pathforresource:@"Public_key" oftype:@"der"];
  4. NSLog (@"public key:%@", Publickeypath);
  5. [RSA Loadpublickeyfromfile:publickeypath];
  6. NSString *securitytext = @"Hello ~";
  7. NSString *encryptedstring = [RSA Rsaencryptstring:securitytext];
  8. 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
    1. NSLog (@"decryptor using RSA");
    2. [RSA Loadprivatekeyfromfile:[[nsbundle Mainbundle] pathforresource:@"Private_key" oftype:@"P12"] password:@  "123456"];
    3. NSString *decryptedstring = [RSA rsadecryptstring:encryptedstring];
    4. 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:

    1. Load PKCS8 private key:
      1. Read private key file
      2. Remove the "-----begin private Key-----" and "-----begin private Key-----" from the private key tail
      3. Remove a line break from private key
      4. BASE64 decoding of processed data
      5. Generates a private key using the decoded data.
    2. Decrypt data:
      1. BASE64 Decoding of data
      2. Use RSA decrypt data.

Here I decode "Hello ~" encrypted data from iOS in Java:

Java code
  1. Import javax.crypto.BadPaddingException;
  2. Import Javax.crypto.Cipher;
  3. Import javax.crypto.IllegalBlockSizeException;
  4. Import javax.crypto.NoSuchPaddingException;
  5. Import java.io.IOException;
  6. Import Java.nio.charset.Charset;
  7. Import Java.nio.file.Files;
  8. Import java.nio.file.Paths;
  9. Import java.security.InvalidKeyException;
  10. Import Java.security.KeyFactory;
  11. Import java.security.NoSuchAlgorithmException;
  12. Import Java.security.PrivateKey;
  13. Import java.security.spec.InvalidKeySpecException;
  14. Import Java.security.spec.PKCS8EncodedKeySpec;
  15. Import java.util.Base64;
  16. Import static Java.lang.String.format;
  17. Public class Encryptor {
  18. public static void Main (string[] args) throws IOException, NoSuchAlgorithmException, Invalidkeyspecexception, Nosuchpaddingexception, InvalidKeyException, Badpaddingexception, illegalblocksizeexception {
  19. Privatekey Privatekey = Readprivatekey ();
  20. String message = "afppafptbmbomzd55cjcfrvawuw7+hzkaq16od+6fp0lwz/yc+rshb/ 8cf5bpbluao2eunchnzekxzpipqtcccitkvk6hcfkzs0sn9wohlqfyt+i4f/czitwbvajaldz7mkyoiuvm+raxmwrs+  7mlkgyxkd5cfpxestxpmsa5nk= ";
  21. SYSTEM.OUT.PRINTLN (Format ("-Decrypt RSA encrypted base64 message:%s", message));
  22. //Hello ~, encrypted and encoded with BASE64:
  23. byte[] data = encrypteddata (message);
  24. String Text = Decrypt (privatekey, data);
  25. System.out.println (text);
  26. }
  27. private static String decrypt (Privatekey Privatekey, byte[] data) throws NoSuchAlgorithmException, Nosuchpaddingexception, InvalidKeyException, Illegalblocksizeexception, badpaddingexception {
  28. Cipher Cipher = cipher.getinstance ("rsa/ecb/pkcs1padding");
  29. Cipher.init (Cipher.decrypt_mode, Privatekey);
  30. byte[] Decrypteddata = cipher.dofinal (data);
  31. return new String (Decrypteddata);
  32. }
  33. private static byte[] EncryptedData (String base64text) {
  34. return Base64.getdecoder (). Decode (Base64text.getbytes (Charset.forname ("UTF-8"));
  35. }
  36. private static Privatekey Readprivatekey () throws IOException, NoSuchAlgorithmException, invalidkeyspecexception {
  37. byte[] Privatekeydata = files.readallbytes (
  38. Paths.get ("/users/twer/macspace/ios_workshop/security/securitylogin/tools/pkcs8_private_key.pem"));
  39. byte[] Decodedkeydata = Base64.getdecoder ()
  40. . Decode (new String (privatekeydata)
  41. . ReplaceAll ("-----\\w+ PRIVATE KEY-----", " ")
  42. . replace ("\ n", "" ")
  43. . GetBytes ());
  44. return Keyfactory.getinstance ("RSA"). Generateprivate (new Pkcs8encodedkeyspec (Decodedkeydata));
  45. }
  46. }

The console will output "Hello ~" after the line succeeds.


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.

      • Openssl Document
      • Load Private Key in Java
      • Cryptographic Services Guide

Encrypt and decrypt data using RSA in iOS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.