sql >> Database teknologi >  >> RDS >> Mysql

Kryptere med PHP Mcrypt og dekryptere med MySQL aes_decrypt?

Jeg fandt god hjælp her

Bemærk, at dette virker for krypteret tekst på op til 65519 tegn i almindelig tekst. (måske lidt mere, hvis ingen UTF-8-kodning)

PHP-kode til at kryptere:

// MySQL uses 16 bytes key for 128 encryption/decryption
$key = "ABCDEF0123456789";

$plaintext = "This string was AES-128 / EBC / ZeroBytePadding encrypted.";
// Optionally UTF-8 encode
$plaintext_utf8 = utf8_encode($plaintext);
// Find out what's your padding
$pad_len = 16 - (strlen($plaintext_utf8) % 16);
// Padd your text
$plaintext_utf8 = str_pad($plaintext_utf8, (16 * (floor(strlen($plaintext_utf8) / 16) + 1)), chr($pad_len));

// Encryption
mt_srand();
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
mcrypt_generic_init($td, $key, false);
// Generates a warning about empty IV but it's Ok
$ciphertext = mcrypt_generic($td, $plaintext_utf8);
mcrypt_generic_deinit($td);
$ciphertext = mysql_real_escape_string($ciphertext);

// Store in MySQL
$mysqli = new mysqli("localhost", "test", "test", "test");
$mysqli->set_charset("utf8");
$mysqli->query("insert into test(content) value ('$ciphertext')");
$mysqli->close();

SQL-forespørgsel til at søge efter string was :

SELECT CAST(AES_DECRYPT(content,'ABCDEF0123456789') AS CHAR) AS content
FROM test
WHERE CAST(AES_DECRYPT(content,'ABCDEF0123456789') AS CHAR) like '%string was%';

Output er:

This string was AES-128 / EBC / ZeroBytePadding encrypted.

Bemærk:MySQL-tabel blev oprettet af:

create table test (
id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
content blob ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


  1. Sådan installeres SQL Server på SUSE 12

  2. CodeIgniter - hvordan man poster værdi fra formular som NULL i stedet for 0

  3. Bruger gruppe af kolonner som en unik nøgle i MySQL

  4. Opret et Excel-regneark fra en Oracle-database