Swift读取RSA Key报错RSA private key creation from data failed

macOS Swift程序因为需要,使用了RSA非对称加密。读取公钥的时候一切正常,但读取私钥的时候会报错

Error Domain=NSOSStatusErrorDomain Code=-50 "RSA private key creation from data failed" (paramErr: error in user parameter list) UserInfo={numberOfErrorsDeep=0, NSDescription=RSA private key creation from data failed}

相关代码片段如下

    func loadPrivateKey(from string: String) -> SecKey? {
        guard let data = Data(base64Encoded: string) else {
            Debuger.log(caller: self, "Private key data malformed")
            return nil
        }
        
        let attributes: [String: Any] = [
            kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
            kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,
        ]
        
        var error: Unmanaged<CFError>?
        guard let privateKey = SecKeyCreateWithData(data as CFData, attributes as CFDictionary, &error) else {
            Debuger.log(caller: self, "Private key create failed: \(error!.takeRetainedValue())")
            return nil
        }
        
        return privateKey
    }

检查了半天,百思不得其解。对应的key在PHP中运行一切正常

查看具体的key pem,格式如下

-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----

最后尝试把key转换为旧版本的RSA private key

openssl rsa -in private_key.pem -out rsa-private_key.pem  -traditional

转换后,key pem格式如下

-----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----

测试代码,运行一切正常了

[encrypt string: PxL4Mi2dCDF1Bibatg2GrvdW+6aD0tFcBjPClKw/dOvOvrxbrowZoUlI+uVAGSCq5924fAUIU8AtZNemJ6CI5YfbKTC98bQQXUFRLrc0fqIXq/qbqytChPuDTCOrOAbzSFZ8bNmr8IhxsIFNEISfBwLlDkamsvV6oADLZSO7c2BsBnwN1XT/feZ5SVCQY9XjPBqGoiSq/8Wv+yoKIW8sc85FixC4b6gWGuW0w3cu7jJci4F/Pqcq3/12rUst9fAo+aizOZLs9L/ynJhdszcxCU8lxN+4N4DDSlKjcXeeYFd81WOUDVhOmzDT1OG2RXQougHR8viwEaOhCdrfsrH0/A==.BpJWr47NShkkRKZG1Yd+8mJfgGEwl73Ij+ICsqM8fPw=]

[decrypt string: test]