Create and Use Secret Keys

The following sample creates a simple Suitelet that requests user credentials, creates a secret key, and encodes a sample string.

Note:

This script sample uses the define function, which is required for an entry point script (a script you attach to a script record and deploy). You must use the require function if you want to copy the script into the SuiteScript Debugger and test it. For more information, see SuiteScript 2.x Global Objects.

Note:

The default maximum length for a secret key field is 32 characters. If needed, use the Field.maxLength property to change this value.

          /**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 */
define(['N/ui/serverWidget', 'N/runtime', 'N/crypto', 'N/encode'], (serverWidget, runtime, crypto, encode) => {
    function onRequest(option) {
        if (option.request.method === 'GET') {
            let form = serverWidget.createForm({
                title: 'My Credential Form'
            });
            let skField = form.addSecretKeyField({
                id: 'mycredential',
                label: 'Credential',
                restrictToScriptIds: [runtime.getCurrentScript().id],
                restrictToCurrentUser: false
            })
            skField.maxLength = 200;

            form.addSubmitButton();

            option.response.writePage(form);
        } else {
            let form = serverWidget.createForm({
                title: 'My Credential Form'
            });

            const inputString = "YWJjZGVmZwo=";
            let myGuid = option.request.parameters.mycredential;

            // Create the key
            let sKey = crypto.createSecretKey({
                guid: myGuid,
                encoding: encode.Encoding.UTF_8
            });

            try {
                let hmacSha512 = crypto.createHmac({
                    algorithm: 'SHA512',
                    key: sKey
                });
                hmacSha512.update({
                    input: inputString,
                    inputEncoding: encode.Encoding.BASE_64
                });
                let digestSha512 = hmacSha512.digest({
                    outputEncoding: encode.Encoding.HEX
                });
            } catch (e) {
                log.error({
                    title: 'Failed to hash input',
                    details: e
                });
            }

            form.addField({
                id: 'result',
                label: 'Your digested hash value',
                type: 'textarea'
            }).defaultValue = digestSha512;

            option.response.writePage(form);
        }
    }
    return {
        onRequest: onRequest
    };
}); 

        

Related Topics

SuiteScript 2.x Suitelet Script Type
SuiteScript 2.x Suitelet Script Type Code Samples
Custom Forms
N/ui/serverWidget Module
N/runtime Module
N/encode Module
N/crypto Module

General Notices