Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encryption with RSA public key on iOS

I write an iOS app to communicate with an existing server. The server generates RSA key pair(public key and private key), and sends public key to the client.

The client(the iOS app) have to encrypt with ONLY the public key, and sends the encrypted data to server.

So, I need a Objective-C function to do RSA encryption.

Input:

  • Plain text: hello world!
  • The public key:

    -----BEGIN PUBLIC KEY-----
    MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEChqe80lJLTTkJD3X3Lyd7Fj+
    zuOhDZkjuLNPog3YR20e5JcrdqI9IFzNbACY/GQVhbnbvBqYgyql8DfPCGXpn0+X
    NSxELIUw9Vh32QuhGNr3/TBpechrVeVpFPLwyaYNEk1CawgHCeQqf5uaqiaoBDOT
    qeox88Lc1ld7MsfggQIDAQAB
    -----END PUBLIC KEY-----
    

Process:

+ (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey;

Output:

uwGuSdCgDxAAN3M5THMrNcec3Fm/Kn+uUk7ty1s70oH0FNTAWz/7FMnEjWZYOtHe37G3D4DjqiWijyUCbRFaz43oVDUfkenj70NWm3tPZcpH8nsWYevc9a1M9GbnNF2jRlami8LLUTZiogypSVUuhcJvBZBOfea9cOonX6BG+vw=

Question:

How to implement this function?

+ (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey;

I have had digg for a long time, on SO and google and Apple's document. I found out Apple need a .der file to do encryption, not only the public key.

like image 358
ideawu Avatar asked Feb 03 '15 04:02

ideawu


1 Answers

I will answer my qustion:

1. create SecKeyRef with public key string

I am helped by this post: http://blog.flirble.org/2011/01/05/rsa-public-key-openssl-ios/#its-all-in-the-format

It led to my code: https://github.com/ideawu/Objective-C-RSA/blob/master/RSA.m#L34

2. use the SecKeyRef to encrypt input data

Use Apple's SecKeyEncrypt(https://developer.apple.com/library/ios/documentation/Security/Reference/certifkeytrustservices/index.html)

3. the full code on github

https://github.com/ideawu/Objective-C-RSA

like image 172
ideawu Avatar answered Oct 06 '22 20:10

ideawu