我怎样才能解密一个HMAC?

我可以使用以下方法制作HMAC:

var encrypt = crypto.createHmac("SHA256", secret).update(string).digest('base64'); 

我正试图用这个秘密解密一个编码的HMAC:

 var decrypt = crypto.createDecipher("SHA256", secret).update(string).final("ascii"); 

以下是不成功的。 我如何用密钥解密HMAC?

我得到以下错误:

 node-crypto : Unknown cipher SHA256 crypto.js:155 return (new Decipher).init(cipher, password); ^ Error: DecipherInit error 

HMAC是MAC /密钥哈希,而不是密码。 这不是为了解密而devise的。 如果要encryption某些内容,请使用AES等密码,最好使用AES-GCM等身份validation模式。

“解密”的唯一方法是猜测整个input,然后比较输出。

再次重申哈希不是被devise为被解密的。 但是,一旦你有一个散列,你可以检查任何string是相同的散列通过相同的encryption通过相同的秘密。

 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') } 

看起来很明显,但非常强大。

正如CodesInChaos所指出的那样 ,带有SHA256的HMAC只能用来散列一个值,这个值只能是单向的。 如果你想能够encryption/解密,你将不得不使用密码,如aesdes

示例如何encryption/解密:

 const crypto = require("crypto"); // key and iv var key = crypto.createHash("sha256").update("OMGCAT!", "ascii").digest(); var iv = "1234567890123456"; // this is the string we want to encrypt/decrypt var secret = "ermagherd"; console.log("Initial: %s", secret); // create a aes256 cipher based on our password var cipher = crypto.createCipheriv("aes-256-cbc", key, iv); // update the cipher with our secret string cipher.update(secret, "ascii"); // save the encryption as base64-encoded var encrypted = cipher.final("base64"); console.log("Encrypted: %s", encrypted); // create a aes267 decipher based on our password var decipher = crypto.createDecipheriv("aes-256-cbc", key, iv); // update the decipher with our encrypted string decipher.update(encrypted, "base64"); console.log("Decrypted: %s", decipher.final("ascii")); 

注意:您必须将密码/解密保存到自己的variables中,并且确保在.final之后不会链接.update

如果您想知道系统上可用的密码,请使用以下命令:

 openssl list-cipher-algorithm 

清理Minimalist视图的代码并清除杂乱:注意:IIFE可以在节点repl中运行“原样”

 !function(){ const crypto = require("crypto"); // key var key = crypto.createHash("sha256").digest(); // this is the string we want to encrypt/decrypt var secret = "ermagherd"; console.log("Initial: %s", secret); // create a aes256 cipher based on our password var cipher = crypto.createCipher("aes-256-cbc", key); // update the cipher with our secret string cipher.update(secret); // save the encryption var encrypted = cipher.final(); console.log("Encrypted: %s", encrypted); // create a aes267 decipher based on our password var decipher = crypto.createDecipher("aes-256-cbc", key); // update the decipher with our encrypted string decipher.update(encrypted); console.log("Decrypted: %s", decipher.final()); //default is utf8 encoding final("utf8") not needed for default }() /* REPL Output Initial: ermagherd Encrypted: T)  l  Ʀ  , ' Decrypted: ermagherd true */