Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
667 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...