I have one problem, with crypto package from npm.
I wan't to to send encrypted string to server to decrypt with express router params.
But there is a big problem, if i enter invalid string, server gives me this error:
TypeError: Bad input string
at Decipher.update (crypto.js:144:26)
at decrypt (APPDIRECTORY\encryption.js:17:22)
at app.get (APPDIRECTORY\encryption.js:35:17)
at Layer.handle [as handle_request] (APPDIRECTORY\node_modules\express\lib\router\layer.js:95:5)
at next (APPDIRECTORY\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (APPDIRECTORY\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (APPDIRECTORY\node_modules\express\lib\router\layer.js:95:5)
at APPDIRECTORY\node_modules\express\lib\router\index.js:281:22
at param (APPDIRECTORY\node_modules\express\lib\router\index.js:354:14)
at param (APPDIRECTORY\node_modules\express\lib\router\index.js:365:14)
I just wan't to know, how to disable this error, and enter my own error!
Thanks!
EDIT:
const express = require('express')
const app = express();
var crypto = require('crypto'),
algorithm = 'aes-256-ctr',
password = 'd6F3Efeq';
function encrypt(text){
var cipher = crypto.createCipher(algorithm,password)
var crypted = cipher.update(text,'utf8','hex')
crypted += cipher.final('hex');
return crypted;
}
function decrypt(text){
var decipher = crypto.createDecipher(algorithm,password)
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return dec;
}
app.get('/decrypt/:string', (request, response) => {
let string = request.params.string;
response.send(decrypt(string));
})
app.listen(3030, (request, response) => {
console.log("Server started succesfully!")
})
If string is not aes-256-ctr format, i got errors. So is there someway to validate string if string is aes-256-ctr format?
You just need try-catch:
function decrypt(text){
try {
var decipher = crypto.createDecipher(algorithm,password)
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return { result: dec };
} catch(err) {
return { error: 'INVALID_ENCRYPTED_TEXT' };
}
}
app.get('/decrypt/:string', (request, response) => {
let string = request.params.string;
const dec = decrypt(string);
if (dec.error) {
response.status(400).end();
} else {
response.send(dec.result);
}
});