1

I am facing an issue which from my side lacks a lot of description in Apples documentation.

I need to sign NSData with RSA private key which is provided from backoffice. Private key is received in form of string.

How to achieve this? I do not want to create my own key pairs, I just want to use that single PRIVATE key to sign NSData.

I found several solutions using OPENSSL, but none of them works and I am not able to find any suitable solution for my problem with native CommonCrypto library.

In fact, this is a piece of Android code I need to replicate:

public static PrivateKey getPrivateKey() throws Exception {
String key = ContentHolder.getInstance(context).getClientPrivateKey();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(android.util.Base64.decode(key, android.util.Base64.NO_WRAP));
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);

- this one returns Private key which is generated from string stored in app's database

public String sign(byte[] array) throws SignatureException {
        try {
            Signature sign = Signature.getInstance("SHA1withRSA");
            sign.initSign(privateKey);
            sign.update(array);
            return android.util.Base64.encodeToString(sign.sign(), android.util.Base64.NO_WRAP);
        } catch (Exception ex) {
            throw new SignatureException(ex);
        }
    }

- this returns signed byte array in form of base64 string

How to achieve this in iOS? I spent many hours searching web and trying several approaches, none of them was successful.

I would be very thankful for any code snippets, since hints like "CommonCrypto should do this" do not work for me.

Thank you very much

1 Answers1

0

The main problem is that Apple officially doesn't support signing using a string-key (https://devforums.apple.com/message/641836#641836). They insist on using .p12 and importing it using SecPKCS12Import.

Check this answer: https://stackoverflow.com/a/27945240/4324866

Community
  • 1
  • 1
Roman Slyepko
  • 1,393
  • 2
  • 8
  • 15
  • Hi, is it ok if i include openSSL using cocoa pods? If yes, why my #include giving me error? Please, Help =) – Vladislav Kan Feb 18 '15 at 09:21
  • 1
    @VladislavKan in order to use C++ libraries and/or any other C++ code you must change the file type of your sourcefile from "Objectice-C" to "Objective-C++" by selecting it in "Identity and Type" tab OR change the sourcefile extension from .m to .mm – Roman Slyepko Mar 03 '15 at 10:10
  • I have already solved the problem using a different approach, but thanks anyway for the useful information. Cheers =) – Vladislav Kan Mar 04 '15 at 03:40
  • 1
    @VladislavKan and what approach did you use? I'm facing the same problem – Jordi Puigdellívol Oct 24 '16 at 13:55