jonasroussel / dart_jsonwebtoken

A dart implementation of the famous javascript library 'jsonwebtoken'
MIT License
87 stars 29 forks source link

.ECPrivateKey(s) can not load Apple private key from 2.7.0 #40

Closed bsz0206 closed 1 year ago

bsz0206 commented 1 year ago

.ECPrivateKey(s) can not load Apple private key:

dart_jsonwebtoken.ECPrivateKey(certificateStr)

Invalid argument(s): The given string does not have the correct begin/end markers expected in a PEM file. -- #0 CryptoUtils.getBytesFromPEMString crypto_utils.dart:519 I/flutter (25799): #1...

this is working in 2.6.4 and stopped working from 2.7.0

The issue is that the cypto.util line 516, lines.lenght==1 when the certificate is given in 1 line

jonasroussel commented 1 year ago

Hello, Can you give me an example of an Apple private key or at least the structure with the content of the key hidden

bsz0206 commented 1 year ago

This is an example p8 file download from Apple Certificate site directly. Some characters are replaced to make it invalid however the bug can be reproduced by it.

AppleAppStore_API_Key.p8.txt

jonasroussel commented 1 year ago

I tested the library using the certificate that you provided me with, and it works well. I attempted to replicate the issue by providing the certificate in a single line, and the error did indeed occur.

So I read the RFC 7468 (https://www.rfc-editor.org/rfc/rfc7468#section-2) and it's indicate how a PEM certificate must be structured and it must have at least 2 lines.

I don't know why it was working before, but to work your certificate must be in the format you gave me in the example, with line break.

Furthermore, I tested the jsonwebtoken JavaScript library using the certificate provided in a single line, and it also failed.

So, I could try to do a "fix" for that case, it would be an unnecessary feature for a edge case like this.

First: Try to find a solution in your own code, by not removing line breaks. Second: If you really can't, add this code:

dart_jsonwebtoken.ECPrivateKey(certificateStr
  .replaceAllMapped(RegExp('-----BEGIN PRIVATE KEY-----'), (match) => '${match.group(0)}\n')
  .replaceAllMapped(RegExp('-----END PRIVATE KEY-----'), (match) => '\n${match.group(0)}')
);