hohl / MIHCrypto

OpenSSL wrapper for Objective-C [cryptography]
MIT License
340 stars 68 forks source link

Question: How to get RSA public key as string #35

Closed ElyasNaranjeeSani closed 8 years ago

ElyasNaranjeeSani commented 8 years ago

Hi,

I generate the keys as below:

MIHRSAKeyFactory factory=[[MIHRSAKeyFactory alloc]init]; MIHKeyPair keys = [factory generateKeyPair];

Now, I need to get string value of public key for sending it to our web services. How can I get it?

Appreciate any help,

hohl commented 8 years ago

RSA keys are just a tuple of large numbers, so you need to specify what format you would like to get. However I guess you mean the most common BASE64-based OpenSSL format. If you want that, all you need to do is:

[[publicKey dataValue] toString]

If required (for example for storage in PEM files), you need to wrap that string by -----BEGIN RSA PUBLIC KEY----- and -----END RSA PUBLIC KEY----- which is quite common for some applications.

ElyasNaranjeeSani commented 8 years ago

Thanks for your quick reply. Yes I meant BASE64-based. Actually the code you provided does not compile.

I've also tried below: NSString *string = [[NSString alloc] initWithData:[keys.public dataValue] encoding:NSUTF8StringEncoding];

But the string is always nil.

hohl commented 8 years ago

Yes, that's what I meant. Can you please checked that keys.public != nil?

([publicKey dataValue] should work fine, theres a test case [MIHRSAKeyTests testDataValue] doing exactly that and at least it seems to pass)

ElyasNaranjeeSani commented 8 years ago

Sure I've checked the keys.public and it was not nil.

Oh, Seems the below solution worked for me!

MIHRSAKeyFactory *keyFactory = [[MIHRSAKeyFactory alloc] init];
MIHKeyPair *keyPair = [keyFactory generateKeyPair];
MIHRSAPublicKey *publicKey = keyPair.public;
NSData *publicKeyData = [publicKey dataValue];
NSString *publicKeyString = [publicKeyData MIH_base64EncodedString];
hohl commented 8 years ago

Try:

 [[keys.public dataValue] base64EncodedString]

Just had a look at the source of dataValue and it looks like it returns the data as binary (not as base64 string).

I'm sorry, it was quite a while ago when I wrote that lines of code.

ElyasNaranjeeSani commented 8 years ago

We posted together :) Thank you so much @hohl .

Really appreciate your help.

hohl commented 8 years ago

No problem, hope you'll find MIHCrypto useful for your project.