Mahesh Haldar
Mahesh Haldar

Reputation: 591

Cannot sign data using private key, getting algorithm not supported by the key in swift

I have generated the private key in swift using the following code:

 let publicKeyAttr: [NSObject: NSObject] = [
                kSecAttrIsPermanent:true as NSObject,
                kSecAttrApplicationTag:"com.xeoscript.app.RsaFromScrach.public2".data(using: String.Encoding.utf8)! as NSObject] // added this value
        let privateKeyAttr: [NSObject: NSObject] = [
                kSecAttrIsPermanent:true as NSObject,
                kSecAttrApplicationTag:"com.xeoscript.app.RsaFromScrach.private2".data(using: String.Encoding.utf8)! as NSObject] // added this

        var keyPairAttr = [NSObject: NSObject]()
        keyPairAttr[kSecAttrKeyType] = kSecAttrKeyTypeRSA
        keyPairAttr[kSecAttrKeySizeInBits] = 2048 as NSObject
        keyPairAttr[kSecPublicKeyAttrs] = publicKeyAttr as NSObject
        keyPairAttr[kSecPrivateKeyAttrs] = privateKeyAttr as NSObject

        statusCode = SecKeyGeneratePair(keyPairAttr as CFDictionary, &publicKey, &privateKey)

And then I am using the private key to sign a piece of data, using the SecKeyAlgorithm.rsaEncryptionPKCS1 algorithm.

The code to sign is as follows:

 public func sign(privateKey myPrivateKey: SecKey, value: String, base64EncodingOptions: Data.Base64EncodingOptions = []) throws -> String?
    {
        enum LoginErrors: Error {
            case badUsername
            case badPassword
        }
        guard #available(iOS 10.0, watchOS 3.0, tvOS 10.0, *) else {
               return "Not available"
           }
        let data = value.data(using: .utf8)!

        var error: Unmanaged<CFError>?
        guard let signedData = SecKeyCreateSignature(myPrivateKey,
                                                     SecKeyAlgorithm.rsaEncryptionPKCS1,
                                                     data as CFData,
                                                     &error) as Data? else
        {
            return nil
        }
        return "(signedData.base64EncodedString())"
    }

I am getting this exception:

[0] (null)  "NSDescription" : "algid:encrypt:RSA:PKCS1: algorithm not supported by the key <SecKeyRef algorithm id: 1, key type: RSAPrivateKey, version: 4, block size: 2048 bits, addr: 0x280a0e5a0>"  

Upvotes: 1

Views: 1519

Answers (1)

Woodstock
Woodstock

Reputation: 22926

SecKeyAlgorithm.rsaEncryptionPKCS1 is incorrect, this is attempting to use the RSA private key for hybrid encryption.

Instead pass something appropriate such as rsaSignatureDigestPKCS1v15SHA256, rsaSignatureDigestPSSSHA256 or one of the other options shown here.

Note, rsaSignatureDigestPKCS1v15SHA256 is deterministic.

Additionally, I would suggest using elliptic curve signature, RSA in 2020, however tempting, is the wrong choice.

There are so many gorgeous libs that support ECC now I wouldn't be using SecKit.

Upvotes: 1

Related Questions