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

Swift中EC PEM私钥生成SecKey失败,错误码-50求助

问题:EC PEM私钥创建SecKey失败(错误码-50)

我尝试从已验证有效的EC PEM私钥字符串创建SecKey,但始终遇到错误。以下是我的Swift测试代码:

import XCTest
import Foundation
import Security

final class reader_iOSTests: XCTestCase {
    
    func createKey() -> SecKey? {
        let pemKey = """
        EC-Parameters: (256 bit)
        -----BEGIN EC PRIVATE KEY-----
        MHcCAQEEIJnIOLJS0kWnbMuPnGhgj1a5kOrmts0zUJ3s0yS1ZfOwoAoGCCqGSM49
        AwEHoUQDQgAE2Jv2ux+edHPzseGnYzwwF+kAAIZNC7/ZhDSHvsGHoqSSJN4SwfQn
        ItXimSk+9AUCVzA3JPg7BoorjJxHNMRyzA==
        -----END EC PRIVATE KEY-----
        """
        
        // Extract the base64 encoded string
        let base64String = pemKey
            .split(separator: "\n")
            .filter { line in
                !line.contains("BEGIN EC PRIVATE KEY") && !line.contains("END EC PRIVATE KEY") && !line.contains("EC-Parameters")
            }
            .joined()
        
        guard let data = Data(base64Encoded: base64String) else {
            print("Error: Data is not valid base64")
            return nil
        }
        
        print("Base64 Data: \(data.base64EncodedString())") // Debug print
        
        // Define attributes for the private key
        let attributes: [String: Any] = [
            kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
            kSecAttrKeyClass as String: kSecAttrKeyClassPrivate
        ]
        
        print("Attributes: \(attributes)") // Debug print
        
        // Create the SecKey
        var error: Unmanaged<CFError>?
        guard let key = SecKeyCreateWithData(data as CFData, attributes as CFDictionary, &error) else {
            if let error = error?.takeRetainedValue() {
                print("Error creating SecKey: \(error)")
            }
            return nil
        }
        
        return key
    }
    
    func testPrivateKey() {
        let privateKey = createKey()
        XCTAssertNotNil(privateKey, "Failed to decode private key")
    }
}

执行后输出如下:

Attributes: ["type": 73, "kcls": 1]
2024-05-17 10:56:17.206730+0100 reader-iOS[2459:1010122] [seckey] SecKeyCreate init(ECPrivateKey) failed: -50
Error creating SecKey: Error Domain=NSOSStatusErrorDomain Code=-50 "EC private key creation from data failed" UserInfo={numberOfErrorsDeep=0, NSDescription=EC private key creation from data failed}
/Users/tomrowbotham/Documents/Documents - Tom’s MacBook Pro/ios/reader-iOS/reader-iOSTests/reader_iOSTests.swift:54: error: -[reader_iOSTests.reader_iOSTests testPrivateKey] : XCTAssertNotNil failed - Failed to decode private key

我已有可正常运行的等效实现,且已确认密钥有效,期望成功创建SecKey以执行加密操作,请问问题出在哪里?


解决方案

问题出在密钥数据的格式匹配上:你解码后的私钥数据是PKCS#8格式,但SecKeyCreateWithData默认未明确指定格式时,无法正确识别该格式的EC私钥,同时缺少密钥长度的明确声明。

修改密钥属性字典,补充以下两个关键配置:

  1. 明确指定密钥格式为PKCS#8
  2. 声明密钥长度为256位(对应你的EC-Parameters)

修改后的属性代码:

let attributes: [String: Any] = [
    kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
    kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,
    kSecAttrKeySizeInBits as String: 256,
    kSecAttrKeyFormat as String: kSecAttrKeyFormatPKCS8
]

你的base64解码逻辑是正确的,过滤掉无关行后得到的是合法的PKCS#8格式私钥数据,补充上述属性后,SecKeyCreateWithData就能正确解析并创建SecKey了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 03:20:09