sha1 hash from as3crypto differs from the one made with PHP

荒凉一梦 提交于 2019-12-21 05:56:12

问题


Make SHA1 hash from string '12345' with as3crypto in as3 the same way how it is done in there example:

var sha1:SHA1 = new SHA1;
var src:ByteArray = Hex.toArray("12345");
var digest:ByteArray = sha1.hash(src);
trace('SHA:' + Hex.fromArray(digest));

result : ec60c0fd70d82a7785f6c9a02dbe16f2e40b1344

Make SHA1 from the same string in PHP:

print "SHA:".sha1("12345");

result : 8cb2237d0679ca88db6464eac60da96345513964

If I try other tools to obtain hash I get the second result, so it looks like the result from PHP is correct.

Question: How can I get the same hash with as3crypto?

BTW: when testing I found that another way with as3crypto gives me another (wrong?) result:

var src:ByteArray = new ByteArray();
src.writeUTF("12345");
var digest:ByteArray = sha1.hash(src);
trace('SHA:' + Hex.fromArray(digest));

result : b98cfbc53daec4029895585ab198f7403d0d0506


回答1:


The hexadecimal (you're converting it with Hex.toArray) value of 12345 is not the same as the string "12345".

You are converting a decimal number to a hexadecimal byte array and hashing it, and then comparing it to a hash of a string generated in PHP. These will never match.

If you absolutely need to compare two hex number together then a change to your PHP like this should probably work.

print "SHA:" . sha1(dechex(12345));

See the dechex PHP documentation for more.




回答2:


The correct way to match a php sha1 using as3crypto lib is to do the following:

var src:ByteArray = Hex.toArray(Hex.fromString(srcString));
var sha1:SHA1 = new SHA1();
var hashedString:String = Hex.fromArray(sha1.hash( src ));

The first additional Hex.fromString avoids your decimal conversion as others have mentioned.

Note: The as3corelib version is much simpler: as3corelib SHA1

var hashedString:String = SHA1.hash( srcString );



回答3:


The PHP output is definitely correct. I tested it against MySQL's sha1 function:

mysql> select sha1('12345');
+------------------------------------------+
| sha1('12345')                            |
+------------------------------------------+
| 8cb2237d0679ca88db6464eac60da96345513964 |
+------------------------------------------+

The likely culprit is this - you're using Hex.toArray() on the input data in this line:

var src:ByteArray = Hex.toArray("12345");

When you need the original string to be in the byte array. I don't know AS3, though, so can't answer why your second attempt also failed.




回答4:


var sha1:SHA1 = new SHA1(); 
var src:ByteArray = new ByteArray(); 
src.writeUTFBytes("12345"); 
trace( Hex.fromArray( sha1.hash( src ) ) );

using writeUTFBytes, this method write the string into bytesarray object without BOM.



来源:https://stackoverflow.com/questions/5031566/sha1-hash-from-as3crypto-differs-from-the-one-made-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!