部分加密和解密似乎不起作用

问题描述 投票:0回答:1

考虑代码:

const CryptoJS = require("crypto-js");

var key = CryptoJS.enc.Hex.parse("000102030405060708090a0b0c0d0e0f");
var iv = CryptoJS.enc.Hex.parse("101112131415161718191a1b1c1d1e1f");

// encrypt
var aesEncryptor = CryptoJS.algo.AES.createEncryptor(key, { iv: iv });

var ciphertextPart1 = aesEncryptor.process("Message Part 1");
var ciphertextPart2 = aesEncryptor.process("Message Part 2");
var ciphertextPart3 = aesEncryptor.process("Message Part 3");
var ciphertextPart4 = aesEncryptor.finalize();

// decrypt
var aesDecryptor = CryptoJS.algo.AES.createDecryptor(key, { iv: iv });

var plaintextPart1 = aesDecryptor.process(ciphertextPart1);
var plaintextPart2 = aesDecryptor.process(ciphertextPart2);
var plaintextPart3 = aesDecryptor.process(ciphertextPart3);
var plaintextPart4 = aesDecryptor.process(ciphertextPart4);
var plaintextPart5 = aesDecryptor.finalize();

console.log(plaintextPart5.toString());

来源:https://cryptojs.gitbook.io/docs/#ciphers

也许我错了,但是我希望消息被解密

输出实际上是:

61676520506172742033

我不知道输出的含义以及它的来源。

如果我打印出另一部分,则出现相同的问题:

console.log(plaintextPart4.toString());

输出:

7373616765205061727420324d657373
javascript encryption cryptojs
1个回答
0
投票

[.process方法返回通过处理作为.process的参数而给定的纯文本以及早期加密活动中剩下的任何纯文本而生成的任何新的密文块。

在这种情况下,密码算法是AES。特别是AES-128,因为用于创建加密器的密钥长为128位。 AES-128使用128位(16字节)块的明文,并为每个明文块发出128位(16字节)的密文。这种基于块的处理会产生您不了解的结果。

程序发生的事情是:

var ciphertextPart1 = aesEncryptor.process("Message Part 1");

给加密器14个字节的输入。这还不足以使其生成密文块,因此.process返回空的密文结果,并将其存储在ciphertextPart1中。加密器在内部存储未处理的14个字节。

var ciphertextPart2 = aesEncryptor.process("Message Part 2");

这会给加密器另外14个字节。它将那些追加到上一次调用剩余的14个字节中,因此现在总共有28个未处理的字节。它会处理尽可能多的字节。即,它将处理这些字节的前16个字节(“ Message Part1Me”),并返回存储在cipherText2中的这16个字节的密文块。加密器现在包含12个未处理的字节。

var ciphertextPart3 = aesEncryptor.process("Message Part 3");

这会给加密器另外14个字节。现在,它具有26个未处理的字节。它处理这些字节的前16个字节(“ ssage Part2Mess”),并返回存储在cipherText3中的这16个字节的密文块。加密器现在包含10个未处理的字节。

var ciphertextPart4 = aesEncryptor.finalize();

这将强制加密器处理任何未处理的字节。它只能在16字节的块上工作,因此会在剩余的10个未处理的明文字节(“ age Part 3”)中增加6个填充字节,对该块进行加密并返回该块的密文。您将该密文块存储为ciphertextPart4

现在您解密了密文块。

var plaintextPart1 = aesDecryptor.process(ciphertextPart1);

[cipherTextPart1是一个空块,因此plaintextPart1将为空,显然解密器将不保留任何未处理的密文。

var plaintextPart2 = aesDecryptor.process(ciphertextPart2);

cipherTextPart2包含明文的前16个字节的加密版本,因此plaintextPart2将包含“消息部分1Me”。密文输入正好是16个字节长,因此解密器不包含未处理的密文。

var plaintextPart3 = aesDecryptor.process(ciphertextPart3);

cipherTextPart3包含明文后16个字节的加密版本,因此plaintextPart3将包含“ ssage Part 2Mess”。解密器再次不保存任何未处理的密文。

var plaintextPart4 = aesDecryptor.process(ciphertextPart4);

cipherTextPart4包含明文最后10个字节的加密版本,因此plaintextPart3将包含“ age Part 3”。解密器中不会保留任何未处理的密文。

var plaintextPart5 = aesDecryptor.finalize();

解密器中没有剩余的未处理密文,因此finalize没有工作要做,plaintextPart5将为空。

© www.soinside.com 2019 - 2024. All rights reserved.