I can make an HMAC using the following:
var encrypt = crypto.createHmac("SHA256", secret).update(string).digest('base64');
I am trying to decrypt an encoded HMAC with the secret:
var decrypt = crypto.createDecipher("SHA256", secret).update(string).final("ascii");
The following was unsuccessful. How can I decrypt a HMAC with the key?
I get the following error:
node-crypto : Unknown cipher SHA256
crypto.js:155
return (new Decipher).init(cipher, password);
^
Error: DecipherInit error
The HmacSHA256() function takes either a WordArray object or a string. When you pass a string in, as you do, it will assume that the data is UTF-8 encoded and try to decode it as UTF-8. You need to parse the data yourself into a WordArray: var hash = CryptoJS.
What is HMAC? The results MAC code is a message hash mixed with a secret key. It has the cryptographic properties of hashes: irreversible, collision resistant, etc.
First, enter the plain-text and the cryptographic key to generate the code. Then, you can use select the hash function you want to apply for hashing. The default is SHA-256. Then you can submit your request by clicking on the compute hash button to generate the HMAC authentication code for you.
HMAC does not encrypt the message. Instead, the message (encrypted or not) must be sent alongside the HMAC hash. Parties with the secret key will hash the message again themselves, and if it is authentic, the received and computed hashes will match.
HMAC is a MAC/keyed hash, not a cipher. It's not designed to be decrypted. If you want to encrypt something, use a cipher, like AES, preferably in an authenticated mode like AES-GCM.
Even knowing the key, the only way to "decrypt" is guessing the whole input and then comparing the output.
Again to reiterate hashes aren't designed to be decrypted. However once you have a hash you can check any string is equal to that hash by putting it through the same encryption with the same secret.
var crypto = require('crypto')
var secret = 'alpha'
var string = 'bacon'
var hash = crypto.createHmac('SHA256', secret).update(string).digest('base64');
// => 'IbNSH3Lc5ffMHo/wnQuiOD4C0mx5FqDmVMQaAMKFgaQ='
if (hash === crypto.createHmac('SHA256', secret).update(string).digest('base64')) {
console.log('match') // logs => 'match'
} else {
console.log('no match')
}
Seems obvious, but very powerful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With