因项目需要,需要node.JS与php做接口调用,发现node.JS对中文使用md5加密与php对中文md5加密的结果不同。
PHP
<code><span><span><?php </span><span>$str</span> = <span>'程序员'</span>; <span>echo</span><span>$str</span>.<span>' md5:'</span>.md5(<span>$str</span>); <span>?></span></span></span></code>
输出:
程序员 md5:72d9adf4944f23e5efde37f6364c126f
node.JS
<code><span>var</span> crypto = <span>require</span>(<span>'crypto'</span>); <span>var</span> md5 = <span><span>function</span><span>(str)</span>{</span><span>var</span> crypto_md5 = crypto.createHash(<span>'md5'</span>); <span>return</span> crypto_md5.digest(<span>'hex'</span>); } <span>var</span> str = <span>'程序员'</span>; <span>var</span> result = str + <span>' md5:'</span> + md5(str); console.log(result);</code>
输出:
程序员 md5:d41d8cd98f00b204e9800998ecf8427e
经查阅资料发现是编码问题,只要在node.JS中加入编码即可解决问题。
解决方法如下:
<code><span>var</span> crypto = <span>require</span>(<span>'crypto'</span>); <span>var</span> md5 = <span><span>function</span><span>(str)</span>{</span><span>var</span> crypto_md5 = crypto.createHash(<span>'md5'</span>); crypto_md5.update(str, <span>'utf8'</span>); <span>// 加入编码</span><span>return</span> crypto_md5.digest(<span>'hex'</span>); } <span>var</span> str = <span>'程序员'</span>; <span>var</span> result = str + <span>' md5:'</span> + md5(str); console.log(result);</code>
输出:
程序员 md5:72d9adf4944f23e5efde37f6364c126f
以上就介绍了nodeJS md5加密中文与php结果不一致的解决方法,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。