[英]How to use crypto-js to save the binary data, of an encryption-output, to a file?
我正在嘗試協助移動開發人員加密圖像並將其上傳到 Azure blob 存儲。 移動應用程序使用 expo 和 crypto js。 我對移動開發或 expo 不是很熟悉,但看起來 expo 可以讓您訪問圖像的 base64 編碼版本。
我的目標是使用 crypto js 加密該圖像數據,並將其上傳到 Azure blob 存儲。
expo 或 Azure 的具體細節對我的問題來說並不是那么重要,但我認為它們值得一提。 我認為重要的是我正在使用 crypto js 來 AES 加密該圖像數據。
我從 base64 圖像數據字符串開始,所以我使用 crypto js 來解析它,如下所示......
const words = CryptoES.enc.Base64.parse(data);
這給了我一個代表圖像數據的WordArray
,我想(來自移動 API 給我的 base64 字符串)。
接下來我可以像這樣加密圖像數據......
const encrypted = CryptoES.AES.encrypt(words, AES_KEY, { iv: AES_IV });
現在我有了加密數據,我想將它寫到一個二進制十六進制格式或其他格式的文件中。 我不想要文件中的 base64 文本,也不想要文件中的十六進制字符串 - 我希望它包含逐字節的文字加密數據。
我不確定如何獲取這些數據。
我猜它只是“toString”,但當我這樣做時它說 invalid utf8
。 這是一個正在處理的 JPG 文件。
我怎樣才能得到實際的字節數據並將其寫入帶有加密 js 的文件?
CryptoJS.AES.encrypt()
返回一個CipherParams
object,其中封裝了密文作為WordArray
。 一種可能性是使用自定義方法將此WordArray
轉換為Uint8Array
。 在以下代碼中,此轉換由convertWordArrayToUint8Array()
完成:
function convertWordArrayToUint8Array(wordArray) {
var arrayOfWords = wordArray.hasOwnProperty("words") ? wordArray.words : [];
var length = wordArray.hasOwnProperty("sigBytes") ? wordArray.sigBytes : arrayOfWords.length * 4;
var uInt8Array = new Uint8Array(length), index=0, word, i;
for (i=0; i<length; i++) {
word = arrayOfWords[i];
uInt8Array[index++] = word >> 24;
uInt8Array[index++] = (word >> 16) & 0xff;
uInt8Array[index++] = (word >> 8) & 0xff;
uInt8Array[index++] = word & 0xff;
}
return uInt8Array;
}
var AES_KEY = CryptoJS.enc.Utf8.parse('0123456789012345');
var AES_IV = CryptoJS.enc.Utf8.parse('5432109876543210');
var plaintext = 'The quick brown fox jumps over the lazy dog';
var ciphertextCP = CryptoJS.AES.encrypt(plaintext, AES_KEY, { iv: AES_IV }); // CipherParams object
var ciphertextWA = ciphertextCP.ciphertext; // WordArray
var ciphertextArr = convertWordArrayToUint8Array(ciphertextWA); // Uint8Array
這個Uint8Array
現在可以存儲在一個文件中,例如:
var fileName = "encdata.bin";
saveByteArray([ciphertextArr], fileName);
從這里使用saveByteArray()
。
另一種方法是使用Latin1 編碼器將WordArray
轉換為二進制字符串:
var ciphertextBinStr = ciphertextWA.toString(CryptoJS.enc.Latin1);
然后可以輕松地將其轉換為Uint8Array
,例如:
function str2Uint8Array(str) {
const arr = new Uint8Array(new ArrayBuffer(str.length));
for (let i = 0, strLen = str.length; i < strLen; i++)
arr[i] = str.charCodeAt(i);
return arr;
}
var ciphertextArr = str2Uint8Array(ciphertextBinStr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.