在 Swift iOS 中生成 X.509 证书(和公钥/私钥)

发布于 2025-01-11 23:06:28 字数 882 浏览 0 评论 0原文

我想生成公钥/私钥以及证书。我想将此证书发送到服务器以供将来验证。我可以使用 SecKeyCreateRandomKey 和 SecKeyCopyPublicKey 生成公钥和私钥。我还使用 SecKeyCopyExternalRepresentation 创建了密钥的外部表示形式,该表示形式采用 DER 格式。我不知道如何从中创建自签名 X.509 证书。

Android 上类似的东西:keyStore.getCertificate()

let tag = "com.example.keys.test".data(using: .utf8)!
let attributes: [String: Any] =
            [kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
             kSecAttrKeySizeInBits as String:      2048,
             kSecPrivateKeyAttrs as String:
                [kSecAttrIsPermanent as String:    true,
                 kSecAttrApplicationTag as String: tag]
        ]
var error: Unmanaged<CFError>?
let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error)
let publicKey = SecKeyCopyPublicKey(privateKey!)
let publicKeyData = SecKeyCopyExternalRepresentation(publicKey!, &error)! as Data

I want to generate a public/private key along with a certificate. I want to send this certificate to the server for future validation. I am able to generate the public and private key using SecKeyCreateRandomKey and SecKeyCopyPublicKey. I have also created an external representation of the key using SecKeyCopyExternalRepresentation, which is in DER format. I am stuck on how to create a self signed X.509 certificate from this.

Something similar to this on Android: keyStore.getCertificate()

let tag = "com.example.keys.test".data(using: .utf8)!
let attributes: [String: Any] =
            [kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
             kSecAttrKeySizeInBits as String:      2048,
             kSecPrivateKeyAttrs as String:
                [kSecAttrIsPermanent as String:    true,
                 kSecAttrApplicationTag as String: tag]
        ]
var error: Unmanaged<CFError>?
let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error)
let publicKey = SecKeyCopyPublicKey(privateKey!)
let publicKeyData = SecKeyCopyExternalRepresentation(publicKey!, &error)! as Data

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文