简体   繁体   English

如何将HMAC添加到CryptoJS AES加密?

[英]How to add HMAC to CryptoJS AES encryption?

CryptoJS's convenience function CryptoJS.AES.encrypt("some plaintext", "password") doesn't seem to do any authentication. CryptoJS的便捷功能CryptoJS.AES.encrypt("some plaintext", "password")似乎没有进行任何身份验证。

I see CryptoJS provides an HMAC class , but I'm confused about how to use this to encrypt-then-authenticate. 我看到CryptoJS提供了HMAC类 ,但是我对如何使用它进行加密然后认证感到困惑。

I searched around for tutorials and other questions but couldn't find any. 我到处搜索教程和其他问题,但找不到任何问题。

How would I add authentication using the above CryptoJS HMAC class to authenticate the ciphertext produced by CryptoJS.AES.encrypt ? 我将如何使用上述CryptoJS HMAC类来验证所产生的密文添加验证CryptoJS.AES.encrypt

The idea with the HMAC provided by cryptoJS is to have you, the developer, pass it both the encrypted data and a key in order for it to spit out the MAC on the other end. cryptoJS提供的HMAC的想法是让开发人员将加密的数据和密钥都传递给它,以便使其在另一端吐出MAC。

Below is an example of how you could use it to produce a MAC for your encrypted data. 以下是如何使用它为加密数据生成MAC的示例。 The idea here is that the key object is the shared secret used between you and trusted parties to verify the integrity of the encrypted data. 这里的想法是, 密钥对象是您和受信方之间用来验证加密数据完整性的共享密钥。

    //Encrypt Data
    var encryptObject = CryptoJS.AES.encrypt(content, key, { iv: yourIV });

    //Calculate HMAC
    var HMAC = CryptoJS.HmacSHA256(encryptObject.toString(), key);

A few things to keep in mind. 需要记住的几件事。

  • Always calculate the HMAC on the encrypted object before decryption. 解密之前,请始终在加密对象上计算HMAC。 This prevents any manipulation of the encrypted data to cause harm after decryption. 这样可以防止对加密数据进行任何操作而在解密后造成损害。

  • Make sure the data encoding/format is the same when validating the HMAC. 验证HMAC时,请确保数据编码/格式相同。 For example, above I used the toString() of my encrypted object, I did this becuase cryptoJS automatically serializes that object to only be the ciphertext. 例如,在上面我使用了加密对象的toString()之前,我这样做是因为cryptoJS自动将该对象序列化为仅密文。 Upon decryption, I calculate the HMAC on the binary string of the encrypted blob I am presented with to make sure the HMAC calculates correctly. 解密后,我根据提供的加密Blob的二进制字符串计算HMAC,以确保HMAC计算正确。

With that I think you should be set to validate some data! 这样,我认为您应该设置为验证一些数据!

Also for a working example, you could check out http://meowcrypt.com/ which is my in browser file encryption service for google drive that uses cryptoJS. 另外,对于一个有效的示例,您可以查看http://meowcrypt.com/ ,这是我在使用cryptoJS的Google驱动器中的浏览器文件加密服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM