I have copied this from the PHP forum as I have now realised that this is definitely a problem related to the way that the javascript is encoding the new lines in the text.....:


I am having trouble implementing a SHA-512 hashing system via ajax.

I have a textarea box, and every time the box is edited, the javascript function (using jQuery) is called. The function looks like this:

Code:
function checkHash() { 
    				var Dtext = $("#checkcode").val();
    				var hash = $("#hash").val();
    				$.post("/ajax/hash", {hash: hash, text: Dtext}, function(ret) { $("#hashCheck").html(ret) });
    		}
As you can see, this function calls /ajax/hash, passing two arguments: hash -> the hash to compare with and text -> the text to hash and to compare to the other hash....

The php code in the /ajax/hash file looks like this (I am using zend framework)

PHP Code:
<?php $text $_POST['text'];
            
$hashOriginal $_POST['hash'];
            
$hash hash('sha512'trim($text));
            
            if(
$hashOriginal == $hash) {
                
$ret '<img src="/images/ajax/tick.png" title="Match"/>';
            } else {
                
$ret '<img src="/images/ajax/cross.png" title="No Match"/>';
                
                
            }
            
$this->view->data $ret;?>
The idea being that if the two hashes match, an image showing a tick is returned, and if they dont then a cross is shown.

This all works hunky dory when there is only a single like of text in the textarea, but as soon as there are multiple lines, it doesnt work...

For example, lets take the following block of text:
a
b

That is the letter 'a' followed by a new line followed by the letter b.

According to http://hash.online-convert.com/sha512-generator and also to my 'non-ajax' has gennerator, the hash for the above text is: 28812982bf1a0b46a2900c05b800808c3268b41e90b06fba3ad4711aa12e30be4e040e35f918ceb5ecd4cc6b8bf9d5955d47d2904ae59753f319455805bb346d

However, my ajax function spits out: 377f7c6560b237d3b88f734faf092fe88f4b2067e048277223748881569ce7b2237c3e3a3fbeef319eea1ccab853b42ff2a7b8791308342ae383579f4420cba0

A completely different hash....

Now, because this only happens when a new line is involved in the textarea, I am guessing it has something to do with the newline character.....

I have tried multiple combinations of applying escape(....) in my javascript code and adding urldecode(....) in my php code but to no avail....


I have tested calling the ajax function form a form, and it gives the correct answer... so this is clearly an issue with the way the newline is encoded in the javascript.... any ideas?