开发者

sha1 hash from as3crypto differs from the one made with PHP

开发者 https://www.devze.com 2023-02-12 04:55 出处:网络
Make SHA1 hash from string \'12345\' with as3crypto in as3 the same way how it is done in there example:

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:Byt开发者_StackOverflow中文版eArray = 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


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.


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 );


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消