How to decrypt an ArrayBuffer?

笑着哭i 提交于 2019-11-30 02:25:55
i_turo

The conversion of ArrayBuffer -> WordArray has been discussed in CryptoJS's issue 46. For that reason a TypedWordArraywhere you can also pass an ArrayBuffer has been added.


To use that additionally include the following script:

<script src="http://crypto-js.googlecode.com/svn/tags/3.1/build/components/lib-typedarrays.js"></script>

Then you can simply do:

var wordArray = CryptoJS.lib.WordArray.create(arrayBuffer);

/* perform decryption of `wordArray` */

To reconvert the resulting decryptedWordArray to an ArrayBuffer, the simplest approach would probably be, to first convert it to a Base64-String (as discussed here) and then decode that String to the desired ArrayBuffer (see here). The whole procedure would look something like this:

dcWordArray = ... // your decrypted WordArray
dcBase64String = dcWordArray.toString(CryptoJS.enc.Base64); // to Base64-String
dcArrayBuffer = base64DecToArr(dcBase64String).buffer; // to ArrayBuffer

Edit:

For a more efficient conversion (no intermediate Base64String necessary) check out Aletheios answer to that question (the function wordToByteArray(wordArray) and then do .buffer).

you can use the web crypto API to directly decrypt arrayBuffer. No need to convert binary data to a string, which is so inefficient, and it could cause memory and CPU rises.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!