2016-08-01 108 views
1

我正在將一個PKI api移植到Swift 2.2並發現以下錯誤。 Objective-C中一切正常。SecKeyEncrypt返回錯誤-50和0 cipherSize

要加密的數據對象大小爲32個字節。這是我正在使用的代碼。

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) 

這會導致錯誤-50和0的密碼長度。

我做的公鑰和dataPointer的hexdump都以確保它們都OK,但不容找到與SecKeyEncrypt呼叫

任何幫助將不勝感激

回答

1

經過一番研究,我的問題找到了解決該問題

我用alloc和零終止陣列創建cipherBuffer,如下所示:

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

我嘗試了下面的方法,它工作正常。

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

鑑於這兩種方法報道的64個字節的塊使用進制打印0x00時,我做了快速測試和審查前面的代碼,發現除去與線「cipherBuffer [buflen] = 0」解決了這個問題。

它似乎與數組的零終止有關,或者我可能做了一些奇怪的事情。