user6789238
user6789238

Reputation:

Search for encrypted text in database starts with or include string

I just thinking about if it can be possible to search for encrypted fields in database what is starts with or include some characters or string.

Example:

Encrypted text in db: "7724bd4ae7cba2c8d182980c7889258b07be344a9c8892de3c303ae03677771c"

Decrypted text: "Jackey"

Search for all encrypted fields in db what is starts with or include: "Jac"

Using sodium to encrypt / decrypt values with a fixed nonce (using in the example)

<?php

define("VALUE_ENCRYPTION_KEY", hex2bin("01abff4e1bbb9104e8e053bcc0492ad114ee7cbdc8597e4e5296e86c44a66bf0"));
define("VALUE_ENCRYPTION_NONCE", hex2bin('c1126da4358e7e4173f2ccc621dd1801a5949ae9f1896e43'));
define("VALUE_ENCRYPTION_BLOCK_SIZE", 16);

function EncryptValue($value)
{
    if (!empty($value)) {
        $padded_value = sodium_pad($value, VALUE_ENCRYPTION_BLOCK_SIZE);
        $encrypted_value = sodium_crypto_secretbox($padded_value, VALUE_ENCRYPTION_NONCE, VALUE_ENCRYPTION_KEY);

        return bin2hex($encrypted_value);
    } else {
        return null;
    }
}

function DecryptValue($value)
{
    if (!empty($value)) {
        $decrypted_padded_value = sodium_crypto_secretbox_open(hex2bin($value), VALUE_ENCRYPTION_NONCE, VALUE_ENCRYPTION_KEY);
        $decrypted_value = sodium_unpad($decrypted_padded_value, VALUE_ENCRYPTION_BLOCK_SIZE);
        return $decrypted_value;
    } else {
        return null;
    }
}

Upvotes: 0

Views: 754

Answers (1)

Nico Haase
Nico Haase

Reputation: 12103

If you fetched all values, decrypted them, and filtered them afterwards: no problem, go for it.

If you want to outload all this to the database: forget it. One of the most important principles of proper encryption is to avoid especially that setting: if I now some part of the plaintext, encrypt it and check for other parts in the database that contain it / start with it. Just try to encrypt a string char by char to see how the encrypted string changes not only in tiny bits, but completely.

But you could try the following: if you always want to search for a prefix of a given, constant length (as in: always the first three, four chars of a string), encode that seperately or hash it, and store it in a seperate column. That would make it possible to use this column for filtering

Upvotes: 3

Related Questions