我想将 ECPublicKey 转换为 PEM 格式,如下所示
”-----开始公开 KEY-----MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEo0WcFrFClvBE8iZ1Gdlj+mTgZoJWMNE3kDKTfRny2iaguwuSYxo+jCnXqzkR+kyFK9CR3D+pypD1sGb1BnfWAA==-----END 公钥-----”
var error:Unmanaged<CFError>?
guard let cfdata = SecKeyCopyExternalRepresentation(publicKey, &error)
else { return }
let data:Data = cfdata as Data
let b64String = data.base64EncodedString()
感谢这里的任何帮助
首先转换为 ASN.1 格式: (请参阅ASN.1解码器中的解码示例)
let publicKeyData: CFData = ...
let ecHeader: [UInt8] = [
/* sequence */ 0x30, 0x59,
/* |-> sequence */ 0x30, 0x13,
/* |---> ecPublicKey */ 0x06, 0x07, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01, // (ANSI X9.62 public key type)
/* |---> prime256v1 */ 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, // (ANSI X9.62 named elliptic curve)
/* |-> bit headers */ 0x07, 0x03, 0x42, 0x00
]
var asn1 = Data()
asn1.append(Data(ecHeader))
asn1.append(publicKeyData as Data)
然后进行 Base64 编码并添加 PEM 页眉和页脚:
let encoded = asn1.base64EncodedString(options: .lineLength64Characters)
let pemString = "-----BEGIN PUBLIC KEY-----\r\n\(encoded)\r\n-----END PUBLIC KEY-----\r\n"
SecKeyCopyExternalRepresentation 的 Apple 开发人员文档
对于椭圆曲线公钥,格式遵循 ANSI X9.63 标准,使用字节字符串 04 || X|| Y.
– https://developer.apple.com/documentation/security/1643698-seckeycopyexternalrepresentation
您可以使用 CryptoKit 的 P256.Signing.PublicKey 类来打印各种表示形式,包括 PEM,
https://developer.apple.com/documentation/cryptokit/p256/signing/publickey/init(x963representation:)
https://developer.apple.com/documentation/cryptokit/p256/signing/publickey/pemrepresentation
请参阅下面的示例:
import CryptoKit
// .... your code from above, start
var error:Unmanaged<CFError>?
guard let cfdata = SecKeyCopyExternalRepresentation(publicKey, &error) else { return }
let data:Data = cfdata as Data
// .... your code from above, end
let p256PublicKey = try P256.Signing.PublicKey(x963Representation: data)
print(p256PublicKey.pemRepresentation)
打印格式,这里是另一个示例键
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEI8JXzxdgciiFjbyUfUu8+au9S9mK
U4NVJztkCgiTwwqGvSkawDPtYAZk7xAomyrnurU0VAbsQW45TcDfl3suvw==
-----END PUBLIC KEY-----