douqiao5440 2017-02-11 07:57
浏览 47
已采纳

加密结果在PHP和Node.js中有所不同

I'm encrypting the string "aaaaaaaaaaaaaaaa" (a 16 byte UTF8 string) using AES 128 CBC with a blank iv and key (16 0's) and getting different results

in PHP:

echo base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128,pack("H*", "00000000000000000000000000000000"),"aaaaaaaaaaaaaaaa",MCRYPT_MODE_CBC,pack("H*", "00000000000000000000000000000000")))

returns "kmwP6gWv1l9ZMdKanGs/nA=="

in Node.js:

let cipher = require('crypto').createCipheriv('aes-128-cbc',Buffer.alloc(16),Buffer.alloc(16))
console.log(cipher.update('aaaaaaaaaaaaaaaa','utf8','base64') + cipher.final('base64'))

returns "kmwP6gWv1l9ZMdKanGs/nHeUidae8Z4dK0HU7p2z+1c="

the first bit (bolded) is identical to PHP, but the PHP value has an extra 'A=' and then Node value has a whole extra 'HeUidae8Z4dK0HU7p2z+1c'

I'll admit that I'm pretty shaky on what's going on here - what am I missing here?

edit ... but not so shaky that I don't understand that what I'm doing here isn't particularly secure. Don't worry about whether this is the 'right' way to do encryption - please focus on the fact that the results ought to line up.

edit2 - I can, however, get close using hex rather than base64 -

PHP: 926c0fea05afd65f5931d29a9c6b3f9c

Node: 926c0fea05afd65f5931d29a9c6b3f9c779489d69ef19e1d2b41d4ee9db3fb57

the second chunk of Node hex is returned by the .final method, and I don't understand what it's for.

  • 写回答

1条回答 默认 最新

  • dsh7623 2017-02-11 09:25
    关注

    AES works on a block size of 16 bytes. You are encrypting the string "hello world", which is 11 bytes long in UTF8. Thus, padding is used to increase the length of your string to 16 bytes.

    Node, and as it should, uses PKCS5 Padding to pad your plain-text to 16 bytes and then encrypts it.

    mcrypt, as it shouldn't, uses zero bytes to pad your plain-text. mcrypt is deprecated and has been abandoned for a decade.

    Because your two padding schemes are different, the plain-text is actually different before we even get to the point where we apply AES.

    My advice: use the openssl_* functions in PHP instead. And don't use a static IV. Using a static IV makes your program vulnerable to some of the same vulnerabilities as ECB mode, which is not good!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面