2

sha 256 Encrypt code (from document)

function hmacEncrypt(r) {
    let str = r.uri.split("/", 2)
    return require('crypto').createHash('sha256', 'key')
                          .update(str)
                          .digest('base64url');
}

I want to use njs to decode aes256, base64 encoded string. However, the official njs document only shows the encrypt method. Is there a way to decode or encode aes256? Can I help you?

Rightly
  • 31
  • 2
  • SHA256 is not an encryption, is a one-way hash. It's impossible to find the original input from the output. – Alejandro Aug 03 '21 at 01:15
  • Thanks! I found out while I was googling. Is there any way to decode aes256? – Rightly Aug 03 '21 at 01:55
  • 1
    The code in your question is still showing a SHA256-hash function and not AES-encryption. The decryption [in pseudo code] goes like this: Base64 decoding and the decrypt instead on encrypt. – Michael Fehr Aug 03 '21 at 05:44

1 Answers1

2

For the aes256, you can do something like:

const crypto = require("crypto");

const initVector = new Uint8Array([
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
]);

function encryptString(string, securityKey) {
    const cipher = crypto.createCipheriv(
        'aes-256-cbc',
        securityKey,
        initVector
    );
    cipher.update(string, 'utf-8', 'hex');
    return cipher.final('hex');
}

function decryptString(string, securityKey) {
    const decipher = crypto.createDecipheriv(
        'aes-256-cbc',
        securityKey,
        initVector
    );
    decipher.update(string, 'hex', 'utf-8');
    return decipher.final('utf-8');
}

The initVector is to provide the initial state of the algorithm, you can change it to whatever you want but it should be an array of exactly 16 bytes, then just simply use those functions:

const securityKey = new Uint8Array([
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
    17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
    31, 32
]);

const text = 'example string';
const encrypted = encryptString(text, securityKey);
const decrypted = decryptString(encrypted, securityKey);

console.log(encrypted);
console.log(decrypted);

The securityKey key is the password that will be used to encrypt and decrypt the string, it should be an array of exactly 32 bytes, change it to whatever you want!

Jonathan Quispe
  • 586
  • 3
  • 10