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!

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

报告相同问题?

悬赏问题

  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢