btnguyen2k / swiftutils

Utility library in Swift
MIT License
72 stars 22 forks source link

SecKey reference is returning nil, when I try to retrieve the saved key from keychain. #12

Closed silicuskushal closed 4 years ago

silicuskushal commented 4 years ago

I am using your library to save the public key generated on the server in the iOS keychain and then use that saved key reference to encrypt information and send that encrypted data back to the server.

Now, when I save the public key in keychain using the function - addRSAPublicKey(_ pubkeyBase64: String, tagName: String) throws -> SecKey? , the result constant returns 0 which I guess is confirmation that my key is saved in the keychain. The problem arises when I try to retrieve back the saved key from the keychain then I get the value of SecKey as nil.

Details about the public key, Encryption Algorithm - RSA Generated on - Server Key Size - 4096

Please advice, how should I proceed?

btnguyen2k commented 4 years ago

Hi @silicuskushal,

There are 2 things you need to check: First is the tagName, it must match your application id. Second is you may need to run on simulator or real device (running on playground will not work).

The repo has a dummy XCode project to demonstrate it. You can have a look at its code to understand the first thing.

Best regards, Thanh Nguyen

silicuskushal commented 4 years ago

Thank you so much for the response. Actually, the public key was in the xml format, I had to convert that into a PEM format first before adding it in the keychain. But my concern is, I am able to encrypt the data using the PEM public key and send that data to the server but since the server side is having the private key in xml format, the encrypted data is not getting decrypted at their end. Can you please help me out as to how to approach? Can we encrypt using an xml format public key in swift ?

btnguyen2k commented 4 years ago

Hi @silicuskushal,

The particular format of the key (XML, JSON, etc) is not really an issue. As long as the key content is correct you can either pre-convert the key to PEM format and use, or convert the key to PEM on-the-fly each time you need to use it. In your case, it's the job of the server side to decrypt the encrypted message correctly. It has nothing to do with the format of the key.

Best regards, Thanh Nguyen