# Getting premature end of file error when creating key

**URL:** <https://devforum.okta.com/t/getting-premature-end-of-file-error-when-creating-key/17577>\
**Category:** Questions\
**Tags:** nodejs\
**Created:** [October 27, 2021, 8:51am UTC](https://devforum.okta.com/t/getting-premature-end-of-file-error-when-creating-key/17577 "2021-10-27T08:51:20Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![abroadhurst](https://avatars.discourse-cdn.com/v4/letter/a/65b543/32.png) [@abroadhurst](https://devforum.okta.com/u/abroadhurst)\
**Post date:** [October 27, 2021, 8:51am UTC](https://devforum.okta.com/t/getting-premature-end-of-file-error-when-creating-key/17577/1 "2021-10-27T08:51:21Z")

</div>

I’m attempting to connect to a service app in Okta using the sdk. To connect to the service app, I’m creating a JWT for authentication however I’m having a lot of trouble when using it for authentication.

If I use the PEM as the private key for the client then I receive this error:

`Error: Parse error: child value length (58) is greater than remaining parent length (-54 = 8 - 62)`

If I use a signed JWT then it comes up with this error:

`Error: premature end-of-file (index: 2 length: NaN)`

This is the first time I am working with a JWT that I have created myself so I am quite lost to why it is not successful.

Please find the code below:

```auto
'use strict';
var debug = require('debug')('my express app');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
const okta = require('@okta/okta-sdk-nodejs');
const jwt = require('jsonwebtoken');
const crypto = require("crypto");
const base64 = require("base64url");

var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

var client = undefined;

crypto.generateKeyPair('rsa', {
    modulusLength: 2048,
    publicKeyEncoding: {
        type: 'spki',
        format: 'pem'
    },
    privateKeyEncoding: {
        type: 'pkcs8',
        format: 'pem',
        cipher: 'aes-256-cbc',
        passphrase: 'top secret'
    }
}, (err, publicKey, privateKey) => {
    const signatureFunction = crypto.createSign('RSA-SHA256');

    const headerObj = {
        alg: 'RSA256',
        typ: 'JWT',
        size: 2048
    };

    const payloadObj = {
        "aud": "https://{{org}}/oauth2/v1/token",
        "iss": "{{clientId}",
        "sub": "{{clientId}}",
        "exp": Date.now() + 3600,
        "iat": Date.now()
    };
    
    const headerObjString = JSON.stringify(headerObj);
    const payloadObjString = JSON.stringify(payloadObj);

    const base64UrlHeader = base64(headerObjString);
    const base64UrlPayload = base64(payloadObjString);

    signatureFunction.write(base64UrlHeader + '.' + base64UrlPayload);
    signatureFunction.end();

    // The private key without line breaks
    const PRIV_KEY = privateKey;

    // Will sign our data and return Base64 signature (not the same as Base64Url!)
    const signatureBase64 = signatureFunction.sign({ key: PRIV_KEY, passphrase: 'top secret' }, 'base64');

    const signatureBase64Url = base64.fromBase64(signatureBase64);

    client = new okta.Client({
        orgUrl: 'https://{{org}}.oktapreview.com/',
        authorizationMode: 'PrivateKey',
        clientId: '{{clientId}}',
        scopes: ['okta.users.manage'],
        privateKey: signatureBase64Url 
        //privateKey: privateKey //authentication using PEM
    });
});

app.get('/', function (req, res) {
    try {
        console.log("listUsers:")
        const orgUsers = client.listUsers();
        orgUsers.each(user => {
            console.log(user);
        }).then(() => console.log('All users have been listed')).catch((e) => console.log(e));
    } catch (e) {
        console.log("list error:" + e);
    }
    res.render('index', { title: 'Express' });
});

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

app.set('port', process.env.PORT || 3000);

var server = app.listen(app.get('port'), function () {
    debug('Express server listening on port ' + server.address().port);
});

```

Sources:

SDK-[GitHub - okta/okta-sdk-nodejs: Node.js API Client for the Okta Platform API](https://github.com/okta/okta-sdk-nodejs)

Okta Services API app-[Overview | Okta Developer](https://developer.okta.com/docs/guides/implement-oauth-for-okta-serviceapp/overview/#use-the-client-credentials-grant-flow)

---

<div class="post-metadata">

**Author:** ![Cale](https://sea1.discourse-cdn.com/oktadev/user_avatar/devforum.okta.com/cale/32/2496_2.png) [@Cale](https://devforum.okta.com/u/Cale)\
**Post date:** [October 27, 2021, 1:41pm UTC](https://devforum.okta.com/t/getting-premature-end-of-file-error-when-creating-key/17577/2 "2021-10-27T13:41:32Z")

</div>

Hi there. I’m unfortunately not very familiar with Node’s crypto library - but would love to see you parse down the issue to see if there is a problem in your key generation or how you created the service app.

Are you familiar with Python at all? I created a private key JWT flow in 3 commands, repo can be found here:

> **[GitHub - Tennyx/private-key-jwt-python: Repo to generate JWTs for use in...](https://github.com/Tennyx/private-key-jwt-python)**
>
> Repo to generate JWTs for use in Private Key JWT OAuth flows. - GitHub - Tennyx/private-key-jwt-python: Repo to generate JWTs for use in Private Key JWT OAuth flows.

I wouldn’t mind seeing you try commands 1 and 2:

`python generate_keys.py`  
`python create_okta_service_app.py`

Then hardcode the private key into your Node JWT signing. If it still fails then maybe it’s an issue with the signature. If it works - then something is off in your key generation or Okta service app creation.

---

<div class="post-metadata">

**Author:** ![abroadhurst](https://avatars.discourse-cdn.com/v4/letter/a/65b543/32.png) [@abroadhurst](https://devforum.okta.com/u/abroadhurst)\
**Post date:** [October 27, 2021, 2:37pm UTC](https://devforum.okta.com/t/getting-premature-end-of-file-error-when-creating-key/17577/3 "2021-10-27T14:37:44Z")

</div>

it may be an actual [issue](https://github.com/okta/okta-sdk-nodejs/issues/286) with the SDK as I attempted to use an generated JWT with it and it brought up a strange error.

I would rather not hardcode the key if possible as it may cause security issue etc but i’ll keep it in mind if I continue to struggle with it once the issue is resolved.

---

<div class="post-metadata">

**Author:** ![system](https://global.discourse-cdn.com/oktadev/original/1X/589c4c5f80de422d01f47cee7185a7fb8227835c.png) [@system](https://devforum.okta.com/u/system)\
**Post date:** [November 9, 2021, 9:08am UTC](https://devforum.okta.com/t/getting-premature-end-of-file-error-when-creating-key/17577/4 "2021-11-09T09:08:33Z")

</div>

Closed on November 9, 2021, 9:08am UTC

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.
