You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中Wrapped Key加密失效问题求助

问题描述

我执行了以下操作:

  • 生成512位的Wrapped Key并保存至钥匙串
  • 生成另一组512位的Private Key
  • 将Private Key转换为319字节的数据
  • 从钥匙串中取出Wrapped Key
  • 从Wrapped Key中获取公钥
  • 尝试用该公钥加密Private Key的数据
  • 目前尝试的所有算法均报错
相关代码
guard let privateKeyData = KeyManager.keyToData(key: privateKey)
     else {
            debugPrint("private Key Data not found")
            return
        }
        
        var error : Unmanaged<CFError>?
        let pubKey = SecKeyCopyPublicKey(wrappedKey)
        
        ///2. Encrypt Private key by Wrapped Key
        guard let encryptedPrivateKey = SecKeyCreateEncryptedData(pubKey!, .eciesEncryptionStandardX963SHA1AESGCM, data as CFData, &error) as Data? else {
            debugPrint("encryption error private key")
            debugPrint(error!.takeUnretainedValue())
            return
        }
错误信息

UserInfo={numberOfErrorsDeep=0, NSDescription=algid:encrypt:ECIES:ECDH:KDFX963:SHA1:AESGCM: 算法不被该密钥支持 <SecKeyRef algorithm id: 1, key type: RSAPublicKey, version: 4, 512 bits (block size: 64),

问题原因

错误信息明确显示,你使用的是RSA公钥,却尝试用ECIES(椭圆曲线加密算法)进行加密——这两种算法体系完全不兼容。ECIES仅适用于椭圆曲线(EC)类型的密钥,而你的Wrapped Key属于RSA类型,自然无法支持该加密算法。

另外需要注意:512位的RSA密钥安全性极低,当前主流标准要求至少2048位,建议后续使用更高位数的密钥。

解决方案

根据你的密钥类型选择对应加密算法:

  1. 继续使用RSA密钥:替换加密算法为RSA兼容类型,推荐使用更安全的.rsaEncryptionOAEPSHA256,也可选择旧标准.rsaEncryptionPKCS1。修改后代码示例:
    guard let encryptedPrivateKey = SecKeyCreateEncryptedData(pubKey!, .rsaEncryptionOAEPSHA256, privateKeyData as CFData, &error) as Data? else {
        debugPrint("encryption error private key")
        debugPrint(error!.takeUnretainedValue())
        return
    }
    
  2. 坚持使用ECIES算法:重新生成椭圆曲线类型的Wrapped Key(比如选择P-256、P-384等曲线),再用对应的ECIES算法完成加密操作。

内容的提问来源于stack exchange,提问作者nirav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 19:40:05