CryptoKit sign payload and header with private key

I am trying to create a jwt token signed with Elliptic Curve Digital Signature Algorithm (ECDSA) with the P-256 curve and the SHA-256 hash algorithm. The payload and the header are created properly, but I am having problems signing it. The P256.Signing.PrivateKey(rawRepresentation: keyData) always returns nil. Can anyone please help?

    let privateKey = """
 -----BEGIN ENCRYPTED PRIVATE KEY-----
code
-----END ENCRYPTED PRIVATE KEY-----
"""
    let keyData = Data(base64Encoded: privateKey.toBase64())!
    let header = jwtHeader()

    let payload = jwtPayload()

    let signingInput = "\(header).\(payload)"

    let privateKey = try! P256.Signing.PrivateKey(rawRepresentation: keyData)

    let sig = try! privateKey.signature(for: Data(signingInput.utf8)).rawRepresentation

    return "\(signingInput).\(sig.base64URLEncodedString)"


extension String {
    func toBase64() -> String {
        return Data(self.utf8).base64EncodedString()
    }
}
Answered by DTS Engineer in 727023022

Your private key has the ENCRYPTED PRIVATE KEY label, suggesting that it’s in a format that you can’t import directly. See my On Cryptographic Key Formats post for details about the formats that CryptoKit can import.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

when I had the same problem I was referred to louvolpini @ gmail dot com,he helped me take care of it,

Accepted Answer

Your private key has the ENCRYPTED PRIVATE KEY label, suggesting that it’s in a format that you can’t import directly. See my On Cryptographic Key Formats post for details about the formats that CryptoKit can import.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Thanks a lot, it helped.

CryptoKit sign payload and header with private key
 
 
Q