当我尝试在swift 4中实现JWT时,我遇到了问题。 我使用jwt.io的JWT库。 我正在尝试使用PKCS8 pem文件类型和RSA256算法证书加密有效负载。 但始终出现错误消息"操作无法完成。 (OSStatus错误-50 - 从数据创建RSA私钥失败)"
有人可以帮助我吗?
代码:
let payload: [AnyHashable:Any] = ["payload":"hiden_information"]
let algorithmName = "RS256"
let path = Bundle.main.path(forResource: "priv", ofType: "pem")
let privateKeySecretData = try? Data(contentsOf: URL(fileURLWithPath: path!))
let privateKey = String(data: privateKeySecretData!, encoding: .utf8)!
let signDataHolder: JWTAlgorithmRSFamilyDataHolder = JWTAlgorithmRSFamilyDataHolder()
_ = signDataHolder.keyExtractorType(JWTCryptoKeyExtractor.privateKeyWithPEMBase64().type)
_ = signDataHolder.algorithmName(algorithmName)
_ = signDataHolder.secret(privateKey)
let signBuilder : JWTEncodingBuilder = JWTEncodingBuilder.encodePayload(payload)
_ = signBuilder.addHolder(signDataHolder)
let signResult = signBuilder.result
if ((signResult?.successResult) != nil) {
print(signResult!.successResult.encoded)
} else {
print(signResult?.errorResult.error.localizedDescription ?? "Unknown")
}
答案 0 :(得分:1)
JWT版本3.0.0.-beta7未支持PKCS8。 我使用PKCS1和RSA256,它有效!
func encryptPayload(payload:[AnyHashable:Any])->String?
{
var resultStr: String?
var publicKeyCrypto: JWTCryptoKeyProtocol? = nil
do {
publicKeyCrypto = try JWTCryptoKeyPublic(pemEncoded: AppConstant.Scurity.publicKey, parameters: nil)
}
catch {
NSLog("error: \(error)")
}
guard let theCrypto = publicKeyCrypto else {
return nil
}
do {
let privateKeyCrypto = try JWTCryptoKeyPrivate(pemEncoded: privateKey, parameters: nil)
guard let holder = JWTAlgorithmRSFamilyDataHolder().signKey(privateKeyCrypto)?.secretData(AppConstant.Scurity.privateKey.data(using: .utf8))?.algorithmName(JWTAlgorithmNameRS256) else {return nil}
let headers : [AnyHashable:Any] = ["alg": "RS256","typ": "JWT"]
guard let encoding = JWTEncodingBuilder.encodePayload(payload).headers(headers)?.addHolder(holder) else {return nil}
let result = encoding.result
print(result?.successResult?.encoded ?? "Encoding failed")
print(result?.errorResult?.error ?? "No encoding error")
let verifyDataHolder = JWTAlgorithmRSFamilyDataHolder().signKey(theCrypto)?.secretData(publicKey.data(using: .utf8)!)?.algorithmName(JWTAlgorithmNameRS256)
let verifyResult = JWTDecodingBuilder.decodeMessage(result?.successResult?.encoded).addHolder(verifyDataHolder)?.result
if verifyResult?.successResult != nil, let result = verifyResult?.successResult.encoded {
print("Verification successful, result: \(result)")
} else {
print("Verification error: \(verifyResult!.errorResult.error)")
}
resultStr = result?.successResult.encoded
} catch {
print(error)
}
return resultStr
}