swift-RSA(二)-SecKeyEncrypt errSecParam(-50)

swift中,使用SecKeyEncrypt进行RSA加密时,会出现errSecParam(-50)?

如何解决呢?

按照苹果官方文档中的errSecParam解释如下:

One or more parameters passed to the function are not valid
1.SecKeyEncrypt参数
  • 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参数解读及注意事项
  • key

    RSA的公钥,使用公钥加密,私钥解密。公钥加载不对或错误,直接报错errSecParam

  • padding

    选择PKCS1,不选PKCS1MD2/PKCS1MD5/PKCS1SHA1/PKCS1SHA224/PKCS1SHA256/PKCS1SHA384/PKCS1SHA512,这些是加签/验签时使用。该参数选错了,直接报错errSecParam

  • plainText/plainTextLen

    注意加密数据的长度,小于等于SecKeyGetBlockSize(:)-11 ,只要超过了该长度,直接报错errSecParam

  • cipherText/cipherTextLen
    cipherText加密后数据缓存区大于与cipherTextLen要一致。
    只要不一致,直接报错errSecParam

3.问题:
  • 1.为什么加密数据长度要求小于等于SecKeyGetBlockSize(:)-11?

      RSA加解密为块加密算法( block cipher algorithm),在固定长度的数据块上进行操作。
      block length是跟key length 以及所使用的填充模式相关
      PKCS1模式时:数据块长度最大为SecKeyGetBlockSize(:)-11
      OAEP模式时,数据块长度最大为SecKeyGetBlockSize(:)-42
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,499评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,132评论 0 23
  • 认识自己,了解自己,接纳自己,才能让自己更好的成长。面对自己,不逃避不退缩。看着曾经犯下过错自己,接纳他。我们不一...
    昨夜北风阅读 202评论 0 0
  • C语言中定义int变量,默认值是多少 专业回答 区分变量的类型,有两种情况。 1 局部变量。 局部变量在没有显式初...
    孤远阅读 760评论 1 0
  • 看着身边熟睡的女儿,我觉得很对不起她,作为母亲,我不能给她完整的家。 两年前,老公出轨,我们离婚了。 当时,我们的...
    思绪芬芳阅读 280评论 0 5