-2
Well I have an application that needs a password encryption, I’m using crypto
of node js
to do the encryption, but I can do the encryption but I can’t decrypt it so I can authenticate the user. You can do it that way to make the encryption.
const crypto = require('crypto');
module.exports = function encryptedPwd(pwd){
const iv = crypto.randomBytes(16).toString('hex').slice(0, 16);
const key = crypto.createHash('sha256').update(String(pwd)).digest('base64').substr(0, 32);//pwd.toString().substr(0, 32);
const cipher = crypto.createCipheriv('aes-256-ctr', key, iv);
let encrypted = cipher.update(String(pwd), 'utf8', 'hex') + cipher.final('hex');
return encrypted;
}
But the password has to be 32 characters long (I didn’t want it to be that way) and I can’t decrypt it either. To decrypt the following excerpt
const testes1 = value => {
const iv = crypto.randomBytes(16).toString('hex').slice(0, 16);
const key = value.substr(0, 32);
const cipher = crypto.createDecipheriv('aes-256-ctr', key, iv);
let encrypted = cipher.update(String(value), 'hex', 'utf8') + cipher.final('hex');
return encrypted;
}
But the following error occurs
internal/assert.js:14
throw new ERR_INTERNAL_ASSERTION(message);
^
Error [ERR_INTERNAL_ASSERTION]: Cannot change encoding
This is caused by either a bug in Node.js or incorrect usage of Node.js internals.
Please open an issue with this stack trace at https://github.com/nodejs/node/issues
at assert (internal/assert.js:14:11)
at getDecoder (internal/crypto/cipher.js:82:3)
at Decipheriv.final (internal/crypto/cipher.js:175:21)
at testes1 (E:\projetos\quadraTenis\backend\src\server.js:10:74)
at Object.<anonymous> (E:\projetos\quadraTenis\backend\src\server.js:13:13)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) {
code: 'ERR_INTERNAL_ASSERTION'
}
Talking about encryption in general... You do not decrypt, you encrypt the password the user sent with the same data (usually a fixed private key and a random salt that is also saved with the password) and compare the result with the saved password. It doesn’t look like that’s what you’re doing, but I don’t know the library so I can’t say
– Costamilam
Encrypting something is not the safest way to "save" a password. It is even disregarded as an option to authenticate a password. Don’t confuse cryptography with a hash (safe for that purpose). To learn more, read How to hash passwords securely?
– Luiz Felipe