PHP使用libsodium + mysql加密存储解密

时间:2018-09-13 08:37:12

标签: php mysql encryption libsodium sodium

我正在一个项目中,开发一个Web应用程序来存储法律程序中的数据以及在下岗人员和客户之间的消息。一切都需要加密。最近,我正在研究加密/解密的新方法,并构建了这段代码来对其进行测试。有人可以告诉我我做得不好吗?

<?php

if (!sodium_crypto_aead_aes256gcm_is_available()) {
    echo ":(";
    die();
}

function create_key() {
    // generate a key
    $key = random_bytes(SODIUM_CRYPTO_AEAD_AES256GCM_KEYBYTES);
    // store the key in a folder, for development proposes it's in the root folder
    fopen('a1/'.sodium_bin2hex($key), "w") or die("Unable to open file!");
    return $key;
}

function create_nonce() {
    // generate a nonce
    $nonce = random_bytes(SODIUM_CRYPTO_AEAD_AES256GCM_NPUBBYTES);
    // store the nonce in a folder, for development proposes it's in the root folder
    fopen('a2/'.sodium_bin2hex($nonce), "w") or die("Unable to open file!");
    return $nonce;
}

function encrypt ($message_to_encrypt) {
    // encript the given message
    $ciphertext = sodium_crypto_aead_aes256gcm_encrypt($message_to_encrypt, "blabla", $nonce = create_nonce(), $key = create_key());
    return $ciphertext;
}


function decrypt ($message_to_decrypt) {
    // get the keys and ninces from folder
    $dir_path = 'a1/';
    if (is_dir($dir_path)) {
        $keys_array = scandir($dir_path);
        unset($keys_array[0]);
        unset($keys_array[1]);
    }
    $dir_path = 'a2/';
    if (is_dir($dir_path)) {
        $nonces_array = scandir($dir_path);
        unset($nonces_array[0]);
        unset($nonces_array[1]);
    }
    // development propose counter
    $i = 1;
    // for each key, try every nonce to get a match
    foreach ($keys_array as $key) {
        foreach ($nonces_array as $nonce) {
            $decrypted = sodium_crypto_aead_aes256gcm_decrypt($message_to_decrypt, "blabla", sodium_hex2bin($nonce), sodium_hex2bin($key));
            // if we found a match, return the decrypted string
            if (!$decrypted === false) {
                return $i . " - " .  $decrypted. "<br />";
                die();
            }
            $i++;
        }
    }
}

$message = "just a test message to encrypt";
echo "message to encrypt - " . $message;
echo "<p>";

$encrypted_mgs = encrypt($message);
echo "encrypted message - " . $encrypted_mgs;
echo "<p>";

$decrypted_mgs = decrypt($encrypted_mgs);
echo "decrypted message - " . $decrypted_mgs;
echo "<p>";

echo "end.";

0 个答案:

没有答案