add des padding options

This commit is contained in:
thezero 2019-04-22 21:20:22 +02:00
parent 8d0fcf37c5
commit 16098ac9c9
2 changed files with 44 additions and 4 deletions

View file

@ -44,6 +44,11 @@ class DESDecrypt extends Operation {
"type": "option",
"value": ["CBC", "CFB", "OFB", "CTR", "ECB"]
},
{
"name": "Padding",
"type": "option",
"value": ["PKCS#7", "Null byte", "None"]
},
{
"name": "Input",
"type": "option",
@ -65,7 +70,7 @@ class DESDecrypt extends Operation {
run(input, args) {
const key = Utils.convertToByteString(args[0].string, args[0].option),
iv = Utils.convertToByteArray(args[1].string, args[1].option),
[,, mode, inputType, outputType] = args;
[,, mode, padding, inputType, outputType] = args;
if (key.length !== 8) {
throw new OperationError(`Invalid key length: ${key.length} bytes
@ -79,7 +84,29 @@ Triple DES uses a key length of 24 bytes (192 bits).`);
const decipher = forge.cipher.createDecipher("DES-" + mode, key);
decipher.start({iv: iv});
decipher.update(forge.util.createBuffer(input));
const result = decipher.finish();
var result = null;
if (padding === "PKCS#7") {
result = decipher.finish();
} else if (padding === "Null byte") {
result = decipher.finish(function(blockSize, buffer, decrypt) {
if (decrypt) {
var len = buffer.length(), count = 0;
for(var i = len - 1; i > 0; --i) {
if (buffer.at(i) == "00") {
count += 1;
} else {
break;
}
}
return buffer.truncate(count);
}
});
} else {
result = decipher.finish(function(blockSize, buffer, decrypt) {
return true;
});
}
if (result) {
return outputType === "Hex" ? decipher.output.toHex() : decipher.output.getBytes();

View file

@ -44,6 +44,11 @@ class DESEncrypt extends Operation {
"type": "option",
"value": ["CBC", "CFB", "OFB", "CTR", "ECB"]
},
{
"name": "Padding",
"type": "option",
"value": ["PKCS#7", "Null byte"]
},
{
"name": "Input",
"type": "option",
@ -65,7 +70,7 @@ class DESEncrypt extends Operation {
run(input, args) {
const key = Utils.convertToByteString(args[0].string, args[0].option),
iv = Utils.convertToByteArray(args[1].string, args[1].option),
[,, mode, inputType, outputType] = args;
[,, mode, padding, inputType, outputType] = args;
if (key.length !== 8) {
throw new OperationError(`Invalid key length: ${key.length} bytes
@ -79,7 +84,15 @@ Triple DES uses a key length of 24 bytes (192 bits).`);
const cipher = forge.cipher.createCipher("DES-" + mode, key);
cipher.start({iv: iv});
cipher.update(forge.util.createBuffer(input));
cipher.finish();
if (padding === "PKCS#7") {
cipher.finish();
} else if (padding === "Null byte") {
cipher.finish(function(blockSize, buffer, decrypt) {
if (!decrypt) {
return buffer.fillWithByte(0, blockSize);
}
});
}
return outputType === "Hex" ? cipher.output.toHex() : cipher.output.getBytes();
}