Search code examples
apinetsuitesuitescriptsuitescript2.0

How can I use a key.pem file in Netsuite to sign a HTTP request with Suitescript?


I am trying to sign a https request and for that I need to encrypt a digest. From the api I generated both a certificate.pem and a privateKey.pem. I uploaded them both in Netsuite in the Certficate and Key part of the company set up.

My question is mainly how do I now get the privateKey from the file to use with the crypto module?

Here is what I have so far. "payload" is the data I want to encrypt for my digest and is just a string.

var sKey = keyControl.loadKey('custkey2');
var hmacObj = crypto.createHmac({
                    algorithm: crypto.HashAlg.SHA256,
                    key: sKey
                });
var updatedHmac = hmacObj.update({
                    input: payload,
                    inputEncoding:encode.Encoding.UTF_8
                });
var reencoded = encode.convert({
                    string: updatedHmac,
                    inputEncoding: encode.Encoding.UTF_8,
                    outputEncoding: encode.Encoding.BASE_64
                });

But when ever I run that in my Suitelet I get an error coming from the "create Hmac". any help would be more than appreciated thank you.


Solution

  • SS2.0 module N/https/clientCertificate holds the answer. Instead of using https.post() use clientCertificate.post() which can send SSL requests with a digital certificate.

    Example that works for me:

    /* 1st create certificate in NetSuite UI (Setup > Pereferences > Certificates) */
    const certId = 'custcertificate_xy';
    /* 2nd use certificates id inside request call */
    const response = clientCertificate.post({
       url: url,
       body: body,
       certId: certId,
       headers: headers
    });
    

    Please note that for some reason NetSuite wanted me to have certificate (*.pem) file in following format:

    -----BEGIN PRIVATE KEY-----
          {{private key}}
    -----END PRIVATE KEY-----
    -----BEGIN CERTIFICATE-----
          {{certificate}}
    -----END CERTIFICATE-----