pgcrypto & php

Hello,


I am storing certain data encrypted by pgcrypto in my database.

Here are the commands I use to test the functionality:

CREATE TABLE crypto (
id SERIAL PRIMARY KEY,
title VARCHAR(50),
crypted_content BYTEA
);


INSERT INTO crypto VALUES (1,'test1',encrypt('daniel', 'fooz', 'aes'));
INSERT INTO crypto VALUES (2,'test2',encrypt('struck', 'fooz', 'aes'));
INSERT INTO crypto VALUES (3,'test3',encrypt('konz', 'fooz', 'aes'));

SELECT * FROM crypto;

SELECT *,decrypt(crypted_content, 'fooz', 'aes') FROM crypto;

SELECT *,decrypt(crypted_content, 'fooz', 'aes') FROM crypto WHERE decrypt(=
crypted_content, 'fooz', 'aes')=3D'struck';


There are certain occasions where I would like to be able to decrypt/ encry=
pt the data in PHP itself. Is this possible with the "Mcrypt Encryption Fun=
ctions" of PHP?

I have already tried it, by as I am no expert in cryptography, I have diffi=
culties finding the right syntax.
This is the code I used to try it out:

$test=3Dnew db_sql_user;
$test->query("select crypted_content from crypto WHERE id=3D1;");
$crypt=3D$test->result();

echo "
";
echo "crypted content from postgresql: " .$crypt;
$array =3D unpack("c2chars/nint", $crypt);
echo $array;
echo "
";
echo mcrypt_decrypt ( MCRYPT_RIJNDAEL_128 , "fooz", $crypt, cbc);
echo "
";
echo mcrypt_cbc (MCRYPT_RIJNDAEL_128, "fooz", $crypt , MCRYPT_DECRYPT);


This is the output:

crypted content from postgresql: g=B0=F1\220399=F9=FB=B9qyg=AE=DB~Array
5*X]Nl\x{2022}u
5*X]Nl\x{2022}u


Best regards,
Daniel Struck


--
Retrovirology Laboratory Luxembourg
Centre Hospitalier de Luxembourg
4, rue E. Barbl=E9
L-1210 Luxembourg

phone: +352-44116105
fax: +352-44116113
web: http://www.retrovirology.lu
e-mail: struck.d [at] retrovirology.lu

---------------------------(end of broadcast)---------------------------
TIP 7: don't forget to increase your free space map settings
Daniel Struck [ Mo, 12 Januar 2004 11:34 ] [ ID #141580 ]

Re: pgcrypto & php

Finally, it works :-)

$crypt=3D$test->result();
echo "
";
echo "crypted content from postgresql: " .$crypt;
echo "
";
$crypt=3Dpg_unescape_bytea($crypt);
echo $crypt;
echo "
";
echo mcrypt_decrypt ( MCRYPT_RIJNDAEL_128 , "fooz", $crypt, cbc);
echo "
";
echo mcrypt_cbc (MCRYPT_RIJNDAEL_128, "fooz", $crypt , MCRYPT_DECRYPT);

OUTPUT:

crypted content from postgresql: g=B0=F1\220399=F9=FB=B9qyg=AE=DB~
g=B0=F1399=F9=FB=B9qyg=AE=DB~
daniel
daniel


You have to use the function "pg_unescape_bytea();" from PHP when you extra=
ct bytea data from postgresql. How stupid of me, should have known that the=
bytea data would be escaped ;-)

Daniel

---------------------------(end of broadcast)---------------------------
TIP 1: subscribe and unsubscribe commands go to majordomo [at] postgresql.org
Daniel Struck [ Mo, 12 Januar 2004 15:35 ] [ ID #141581 ]
Datenbanken » gmane.comp.db.postgresql.php » pgcrypto & php

Vorheriges Thema: pg_connect socket creation error (0x0000273F)
Nächstes Thema: php pear DB, UTF8 settngs question