I am trying to decrypt a file that was created using the OpenSSL command-line interface. This file was created with:
openssl aes-256-cbc -a -in file.txt -out file_encrypted.txt
And can be decrypted with:
openssl aes-256-cbc -d -a -in file_encrypted.txt
By using the -p
flag I can retrieve the actual value, salt and IV which will be required by the WebCrypto API:
> openssl aes-256-cbc -d -a -p -in file_encrypted.txt
salt=F57F1CC0CD384326
key=0E971326890959386F1CFB91F185CFE109203DCEBC81DCAD4EE642F34C538E5B
iv=A884549B66400EB198879F8A09148D4E
secret text
My current attempt looks like this:
function getKey (password) {
return crypto.subtle.digest({name: "SHA-256"}, convertStringToArrayBufferView(password)).then(function(result){
return crypto.subtle.importKey("raw", result, {name: "AES-CBC"}, false, ["encrypt", "decrypt"]);
});
}
function decrypt(key, data, iv) {
return crypto.subtle.decrypt({ name: "AES-CBC", iv: iv }, key, data).then(function(result){
var decrypted_data = new Uint8Array(result);
return convertArrayBufferViewtoString(decrypted_data);
}, fail);
}
var encrypted = Uint8Array.from('0E971326890959386F1CFB91F185CFE109203DCEBC81DCAD4EE642F34C538E5B'.match(/\w\w/g));
var IV = Uint8Array.from('A884549B66400EB198879F8A09148D4E'.match(/\w\w/g));
getKey(prompt('Enter decryption password:')).then(function (key) {
decrypt(key, encrypted, IV).then(result => {
console.log(`password: ${result}`)
});
}, fail);
(array-to-buffer methods ommited for brevity - taken from http://qnimate.com/passphrase-based-encryption-using-web-cryptography-api/)
This fails with an unspecified DOMException
though and I have no idea what to do next.
OpenSSL applies a salted key derivation algorithm to your password using some random bytes generated when encrypting and stored in the header of the encrypted file.
In this post is very well explained
To make your code works is needed:
Load the key generated by OpenSSL (or derive the key from password using the provided salt with the openssl algorithm. The derivation algorithm is undocumented in the openssl encryption page, but in this post is said that is propietary, so it is not available in webcrypto)
decode from HEX to ArrayBuffer using
hex2a
andconvertStringToArrayBufferView
var IV = convertStringToArrayBufferView (hex2a ('A884549B66400EB198879F8A09148D4E'));
Load the encrypted file: decode from base64 (you used
-a
option) and remove the first 16 bytes of the saltThis a simplified javascript example with data generated with the same openssl command
Javascript code
Utility functions