swift中,使用SecKeyEncrypt
進行RSA加密時牌芋,會出現(xiàn)errSecParam(-50)
?
如何解決呢榛丢?
按照蘋果官方文檔中的errSecParam
解釋如下:
One or more parameters passed to the function are not valid
1.SecKeyEncrypt
參數(shù)
-
key
Public key with which to encrypt the data.
-
padding
The type of padding to use. Possible values are listed in SecPadding. Typically, PKCS1 is used, which adds PKCS1 padding before encryption. If you specify none, the data is encrypted as-is.
plainText
The data to encrypt.-
plainTextLen
Length in bytes of the data in the plainText buffer. This must be less than or equal to the value returned by the SecKeyGetBlockSize(:) function. When PKCS1 padding is performed, the maximum length of data that can be encrypted is 11 bytes less than the value returned by the SecKeyGetBlockSize(:) function (secKeyGetBlockSize() - 11).
cipherText
On return, the encrypted text.-
cipherTextLen
On entry, the size of the buffer provided in the cipherText parameter. On return, the amount of data actually placed in the buffer.
2.SecKeyEncrypt參數(shù)解讀及注意事項
-
key
RSA的公鑰栅盲,使用公鑰加密舔庶,私鑰解密猪狈。公鑰加載不對或錯誤箱沦,直接報錯
errSecParam
-
padding
選擇PKCS1,不選PKCS1MD2/PKCS1MD5/PKCS1SHA1/PKCS1SHA224/PKCS1SHA256/PKCS1SHA384/PKCS1SHA512雇庙,這些是加簽/驗簽時使用谓形。該參數(shù)選錯了灶伊,直接報錯
errSecParam
-
plainText/plainTextLen
注意加密數(shù)據(jù)的長度,小于等于SecKeyGetBlockSize(:)-11 寒跳,只要超過了該長度聘萨,直接報錯
errSecParam
cipherText/cipherTextLen
cipherText加密后數(shù)據(jù)緩存區(qū)大于與cipherTextLen要一致。
只要不一致童太,直接報錯errSecParam
3.問題:
-
1.為什么加密數(shù)據(jù)長度要求小于等于SecKeyGetBlockSize(:)-11米辐?
RSA加解密為塊加密算法( block cipher algorithm),在固定長度的數(shù)據(jù)塊上進行操作书释。 block length是跟key length 以及所使用的填充模式相關 PKCS1模式時:數(shù)據(jù)塊長度最大為SecKeyGetBlockSize(:)-11 OAEP模式時翘贮,數(shù)據(jù)塊長度最大為SecKeyGetBlockSize(:)-42