用于将 JWK 格式的密钥转换为更流行的格式(如 PEM)的库。目前仅支持 RSA,并输出 PEM PKCS#8 格式。
swift build -Xlinker -L/usr/local/opt/openssl/lib -Xcc -I/usr/local/opt/openssl/include
swift package generate-xcodeproj
前往 targets -> build settings -> 搜索 user paths,添加到 Header Search Paths /usr/local/opt/openssl/include,添加到 Library Search Paths /usr/local/opt/openssl/lib
✨ 构建魔法 ✨
可以使用 JWK 字符串或 JWK RSA 组件作为初始化器的输入。
let key = try RSAKey(jwk: token)
其中
init(jwk: String) throws
或者
let key = try RSAKey(n: mod, e: expE, d: expD)
其中
init(n: String, e: String, d: String? = nil,
p: String? = nil, q: String? = nil,
dp: String? = nil, dq: String? = nil,
qi: String? = nil) throws
- parameter n: Base64 URL encoded string representing the `modulus` of the RSA Key.
- parameter e: Base64 URL encoded string representing the `public exponent` of the RSA Key.
- parameter d: Base64 URL encoded string representing the `private exponent` of the RSA Key.
- parameter p: Base64 URL encoded string representing the `secret prime factor` of the RSA Key.
- parameter q: Base64 URL encoded string representing the `secret prime factor` of the RSA Key.
- parameter dp: Base64 URL encoded string representing the `first factor CRT exponent` of the RSA Key. `d mod (p-1)`
- parameter dq: Base64 URL encoded string representing the `second factor CRT exponent` of the RSA Key. `d mod (q-1)`
- parameter qi: Base64 URL encoded string representing the `first CRT coefficient` of the RSA Key. `q^-1 mod p`
初始化后,可以使用 PKCS#8 编码提取公钥和私钥为 PEM 格式。
let key = try RSAKey(jwk: token)
let publicPem = try key.getPublicKey(certEncoding.pemPkcs8)
let privatePem = try key.getPublicKey(certEncoding.pemPkcs8)
public key
(公钥):此库应生成 OpenSSL 生成的公钥。
private key
(私钥):RSA 私钥只需要 q
,但通常情况下,如果提供了上述其余值,RSA 操作会更快。OpenSSL 生成的 RSA 私钥文件包含这些值。因此,如果不是所有私有参数都提供了,则生成的私钥可能与原始 OpenSSL 生成的不完全匹配。
JSON Web Key (JWK) 定义在 https://tools.ietf.org/html/rfc7517
JWK 示例
{
"kty": "RSA", // key type
"alg": "RS256", // algorithm for the key
"use": "sig", // how the key is meant to be used. For this example, sig represents signature.
"x5c": [ // x.509 certificate chain
"MIIC+DCCAe..="
],
// n = modulus and e = exponent for a standard PEM. Both are base64url encoded
"n": "AJ+E8O4KJ...ltU=",
"e": "AQAB",
"kid": "NjVB...TM2Qg", // unique identifier for the key
"x5t": "NjVB...TM2Qg" // thumbprint of x.509 cert (SHA-1 thumbprint)
}