Search code examples
swiftencryptionpublic-key-encryptionpki

SecKeyEncrypt returns error -50 and 0 cipherSize


I am porting a PKI api to Swift 2.2 and found the following error. Everything works fine in Objective-C.

The data object to be encrypted is 32 bytes in size. This is the code I am using.

let buflen = 64
var cipherBuffer = UnsafeMutablePointer<UInt8>.alloc(buflen)
cipherBuffer[buflen] = 0 // zero terminate

var cipherLength: Int = 0

var statusCode: OSStatus?

let dataPointer = UnsafePointer<UInt8>(data.bytes)

statusCode = SecKeyEncrypt(publicKey, SecPadding.PKCS1, dataPointer, data.length, cipherBuffer, &cipherLength)

This results in an error -50 and 0 cipher length.

I am doing an hexdump of the public key and the dataPointer to ensure they are OK, but can´t find the problem with the SecKeyEncrypt call

Any help will be appreciated


Solution

  • After some research I found a solution to the problem

    I was creating the cipherBuffer using alloc and zero terminating the array, as follows:

    let buflen = 64
    var cipherBuffer = UnsafeMutablePointer<UInt8>.alloc(buflen)
    cipherBuffer[buflen] = 0 // zero terminate
    

    I tried the following approach and it works fine.

    let blockSize = SecKeyGetBlockSize(publicKey) //64
    var cipherBuffer = [UInt8](count: Int(blockSize), repeatedValue: 0)
    

    Given that both approaches reported a block of 64 bytes with 0x00 using hexDump, I did a quick test and reviewed the previous code and found that removing the line with "cipherBuffer[buflen] = 0" fixes the problem.

    It seems that it has to do with the zero termination of the array, or I may have done something weird.