Reputation: 25
I want to encrypt a message by php but at client side, I want javascript to decrypt it. I had tried Blowfish(using mcrypt ), but I discovered that php echoing non-alpha-numberic character and Javascript display alpha-numeric. I am using ajax so that the page will not reload.
I had tested codes from http://aam.ugpl.de/?q=node/1060 and http://www.php-einfach.de/blowfish_en.php#ausgabe.
Any help is appreciated.
Edit: I use Diffie-Hellman to calculate secret key with random generated number a and b. Below is the resulted from php code
class Encryption
{
const CYPHER = 'blowfish';
const MODE = 'cbc';
const KEY = '26854571066639171754759502724211797107457520821';
public function encrypt($plaintext)
{
$td = mcrypt_module_open(self::CYPHER, '', self::MODE, '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, self::KEY, $iv);
$crypttext = mcrypt_generic($td, $plaintext);
mcrypt_generic_deinit($td);
return $iv.$crypttext;
}
public function decrypt($crypttext)
{
$plaintext = '';
$td = mcrypt_module_open(self::CYPHER, '', self::MODE, '');
$ivsize = mcrypt_enc_get_iv_size($td);
$iv = substr($crypttext, 0, $ivsize);
$crypttext = substr($crypttext, $ivsize);
if ($iv)
{
mcrypt_generic_init($td, self::KEY, $iv);
$plaintext = mdecrypt_generic($td, $crypttext);
}
return $plaintext;
}
}
$encrypted_string = Encryption::encrypt('this is a test');
$decrypted_string = Encryption::decrypt($encrypted_string);
echo "encrypted: $encrypted_string<br>";
echo "decrypted: $decrypted_string<br>";
encrypted: µ˜?r_¿ÖŸŒúw‰1‹Žn!úaH
decrypted: this is a test
Upvotes: 1
Views: 6475
Reputation: 4314
This javascript AES crypto library from a few stanford students is the best I've seen:
http://crypto.stanford.edu/sjcl/
But note their caveat:
We believe that SJCL provides the best security which is practically available in Javascript. (Unfortunately, this is not as great as in desktop applications because it is not feasible to completely protect against code injection, malicious servers and side-channel attacks.)
In PHP, use base64_encode()
after encrypting and base64_decode()
before decrypting. This way it will be rendered with characters safe for transmission. In the browser, use atob()
and btoa()
.
Upvotes: 3