Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to parse KeyObject for purpose of signing JWT with an EC private key. #85

Closed
swapnilgt opened this issue Jul 1, 2020 · 6 comments · Fixed by #86
Closed

Unable to parse KeyObject for purpose of signing JWT with an EC private key. #85

swapnilgt opened this issue Jul 1, 2020 · 6 comments · Fixed by #86
Labels
bug Something isn't working

Comments

@swapnilgt
Copy link

swapnilgt commented Jul 1, 2020

I have been trying to read my EC private key from a file and use it to generate a signed JWT token. First I am putting my private key (a sample privateKey mentioned here) in the file my_privatekey.txt:

-----BEGIN PRIVATE KEY-----
MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCCXpUVoM4DfOtMyRVtC
eGSpVL+1tMBirnUGJHY6Y7mSHg==
-----END PRIVATE KEY-----

Following is the code to read and create a signed JWT:

const { JWT, JWS, JWK } = require('jose');
const fs = require('fs')
var crypto =require('crypto')

let keyFile = fs.readFileSync('my_privatekey.txt')
console.log("keyRaw: " + keyFile.toString());

// Using the nodejs crypto library ...
let keyObjCrypto = crypto.createPrivateKey(
  keyFile.toString(),
  'der',
  'pkcs8'
);

console.log("keyObjCrypto: " + JSON.stringify(keyObjCrypto));
console.log("asymmetricKeyType: " + keyObjCrypto.asymmetricKeyType);
console.log("type: " + keyObjCrypto.type);

// Jose code
let keyObj = JWK.asKey(keyObjCrypto, {'use': 'sig'});

let token = JWT.sign(
    {
        'claim': '<claimValue>,
    },
    keyObj,
    {
        expiresIn: '24 hours',
        header: {
            typ: 'JWT',
        },
        issuer: 'issuer,
        algorithm: 'ES256'

    })
  console.log(token);

I am getting the following error in the step JWK.asKey(keyObjCrypto, {'use': 'sig'}):

/Users/swapnil.g/node_modules/jose/lib/help/key_utils.js:92
      const { privateKey: d, publicKey: { data: publicKey } } = ECPrivateKey.decode(privateKey)
                                                ^

TypeError: Cannot read property 'data' of undefined
    at Object.private (/Users/swapnil.g/node_modules/jose/lib/help/key_utils.js:92:49)
    at module.exports.keyObjectToJWK (/Users/swapnil.g/node_modules/jose/lib/help/key_utils.js:159:56)
    at ECKey.get [as crv] (/Users/swapnil.g/node_modules/jose/lib/jwk/key/base.js:231:23)
    at new ECKey (/Users/swapnil.g/node_modules/jose/lib/jwk/key/ec.js:30:29)
    at Object.asKey (/Users/swapnil.g/node_modules/jose/lib/jwk/import.js:120:16)
    at Object.<anonymous> (/Users/swapnil.g/Desktop/walrus_signing.js:28:18)

Not sure, what else I am missing.

Also, I tried verifying the key type using openssl command on terminal. Running openssl ec -in my_privatekey.txt -noout -text outputs:

read EC key
Private-Key: (256 bit)
priv:
    00:97:a5:45:68:33:80:df:3a:d3:32:45:5b:42:78:
    64:a9:54:bf:b5:b4:c0:62:ae:75:06:24:76:3a:63:
    b9:92:1e
pub:
    04:68:d2:11:3f:69:fd:d8:80:5c:e2:c4:c4:07:0d:
    19:20:ad:f9:fc:6c:c2:7b:95:67:59:68:94:3c:5c:
    fc:0a:c1:05:1a:ec:ad:99:94:df:25:a8:6d:e6:46:
    11:62:ff:73:e8:71:b5:c5:3b:96:03:c2:72:3b:c6:
    50:00:f8:92:d0
ASN1 OID: prime256v1
NIST CURVE: P-256

on the terminal.

Can someone please help here?

@swapnilgt swapnilgt added the question Further information is requested label Jul 1, 2020
@swapnilgt swapnilgt changed the title Unable to parse KeyObject for purpose of signing JWT with an EC keypair. Unable to parse KeyObject for purpose of signing JWT with an EC private key. Jul 1, 2020
@panva
Copy link
Owner

panva commented Jul 1, 2020

I think my code doesn’t account for EC private keys that don’t include the public key in them.

I’ll see what I can do, in the meantime, can you post the command that generated this key?

@panva panva added triage waiting for feedback The OP is asked for feedback or a proposal labels Jul 1, 2020
@panva
Copy link
Owner

panva commented Jul 1, 2020

This is your key's structure. The library expects it to be this, i.e. having the publicKey member.

I have a fix for this for Node runtimes >= 12.0.0. I can't fix this for ^10.13.0 because i lack the functionality to compute the public key out of a private one and the extra code needed does seem like an overkill when all a person needs is to use lts/12 runtime.

@swapnilgt
Copy link
Author

swapnilgt commented Jul 1, 2020

I was trying out some openssl commands to generate a private key that does not have a public key embedded. Tried this:

openssl ecparam -name prime256v1 -genkey -noout -out key.pem

I am searching for a way to extra only the private key part from here.

PS: The library works fine with the key embedded with the public key

I generally generate the KeyPair using the Java security library:

public static KeyPair generateEcKeyPair() {
        String name = "prime256v1";
        try {
            KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
            ECGenParameterSpec spec = new ECGenParameterSpec(name);
            generator.initialize(spec, new SecureRandom());
            return generator.generateKeyPair();
        } catch (Exception exp) {
           // Your code
        }
    }

Once you get the key pair, you can access the private key separately and extract the base64 encoded format using Java's util functions.

@panva

@panva
Copy link
Owner

panva commented Jul 1, 2020

PS: The library works fine with the key embedded with the public key

I know.

panva added a commit that referenced this issue Jul 1, 2020
Only possible to handle when KeyObject API is available in the runtime.

closes #85
@panva panva added bug Something isn't working and removed question Further information is requested triage waiting for feedback The OP is asked for feedback or a proposal labels Jul 1, 2020
@panva panva closed this as completed in #86 Jul 1, 2020
panva added a commit that referenced this issue Jul 1, 2020
Only possible to handle when KeyObject API is available in the runtime.

closes #85
@swapnilgt
Copy link
Author

Thanks a lot @panva fo your quick support. :)

@panva
Copy link
Owner

panva commented Jul 2, 2020

Please consider supporting the library if it provides value to you or your company and this support was of help to you. Supporting the library means, amongst other things, that such support will be available in the future.

@github-actions github-actions bot locked and limited conversation to collaborators Sep 30, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants