简体   繁体   English

这个 SHA-256 Javascript 代码有什么问题?

[英]What's wrong in this SHA-256 Javascript code?

var secure;
var authentic;
secure = prompt("Enter password","");
alert(secure);

var c1 = CryptoJS.SHA256(secure);
alert(c1);


authentic = prompt("Enter password","");
alert(authentic);
var c2=CryptoJS.SHA256(authentic);
alert(c2);

if(c1==c2)
{
    alert("hi");
}
else
{
    alert("bye");
}

I use the script " http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha256.js "我使用脚本“ http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha256.js

EXPLANATION: What, I'm trying to do is to compare hashed passwords.If both the passwords entered (secure and authentic) that have been hashed (c1 and c2 respectively) are equal, It must display 'hi' to me.解释:什么,我想要做的是比较散列密码。如果输入的两个密码(安全和真实)已经散列(分别为 c1 和 c2),它必须向我显示 'hi'。 But I find that it displays 'bye' to me always.但我发现它总是向我显示“再见”。

PROBLEM: When I compare c1 and c2, the result I get always is 'bye', though the values of c1 and c2 are the same when I display them using the alert box.问题:当我比较 c1 和 c2 时,我得到的结果总是“再见”,尽管当我使用警告框显示 c1 和 c2 时,它们的值是相同的。

I'm kinda new to hashing.我对散列有点陌生。 A li'l help would be much appreciated!非常感谢您的帮助!

From the docs :文档

The hash you get back isn't a string yet.您返回的哈希值还不是字符串。 It's a WordArray object.它是一个 WordArray 对象。 When you use a WordArray object in a string context, it's automatically converted to a hex string.在字符串上下文中使用 WordArray 对象时,它会自动转换为十六进制字符串。

When you compare objects in JavaScript you are testing to see if they are the same object, not if they are identical objects.当您在 JavaScript 中比较对象时,您正在测试它们是否是同一个对象,而不是它们是否是相同的对象。

Since you have created two WordArrays, you are comparing two different (but probably identical) objects.由于您创建了两个 WordArray,因此您正在比较两个不同(但可能相同)的对象。

You need to convert them to strings.您需要将它们转换为字符串。

if ( (''+c1) == (''+c2) ) 

or或者

if ( c1.toString() == c2.toString() )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM