Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

objective c - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...