jonasroussel / dart_jsonwebtoken

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

JWT sign fails for ES256 depending on the generated private key (1% error rate) #38

Closed nblum37 closed 1 year ago

nblum37 commented 1 year ago

Hi,

depending on the private key (no matter how the private key was converted to the framework's private key format), the framework through the following issue:

Bildschirm­foto 2023-01-25 um 13 55 35

You can use the following code to generate the issues:

test('Own example simple working', () {
      int signingFails = 0;
      int verifyFails = 0;

      for (int i = 0; i < 1000; i++) {
        utils.AsymmetricKeyPair<utils.PublicKey, utils.PrivateKey> keyPair = utils.CryptoUtils.generateEcKeyPair();
        utils.ECPublicKey publicKeyNew = keyPair.publicKey as utils.ECPublicKey;
        utils.ECPrivateKey privateKeyNew = keyPair.privateKey as utils.ECPrivateKey;

        // Create a json web token
        var jwt = JWT(
          {'test': 'test'},
        );

        // Get private Key
        ECPrivateKey privateKey = ECPrivateKey.raw(privateKeyNew);

        // Sign
        String token;
        try {
          token = jwt.sign(
            privateKey,
            algorithm: JWTAlgorithm.ES256,
          );
        } catch (e) {
          signingFails++;  <<-- Set breakpoint here
          continue;
        }

        // Get public key
        ECPublicKey publicKey = ECPublicKey(utils.CryptoUtils.encodeEcPublicKeyToPem(publicKeyNew));

        // Verify
        try {
          JWT.verify(token, publicKey);
        } catch (e) {
          verifyFails++;
          continue;
        }
      }

      print('Signing Fails: $signingFails');
      print('Verify Fails: $verifyFails');
      expect(signingFails, 0);
      expect(verifyFails, 0);
    });
jonasroussel commented 1 year ago

I found the problem, that comes from a missing of 0 bits padding in ECDSA signatures {r, s} ! Fixed in this version : https://pub.dev/packages/dart_jsonwebtoken/versions/2.7.1

nblum37 commented 1 year ago

Nice, thank you!