PHP和MySQL进行加密

PHP和MySQL进行加密

本文介绍了使用mcrypt,PHP和MySQL进行加密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用mcrypt在我的数据库上存储密码.首先,它起作用,但是仅在某些时间起作用.

I am trying to use mcrypt to store a password on my database. First of all, it WORKS, but only some of the time.

这是我的加密代码:

    //Encryption/Decryption key
    $key = $username.$username.$username.$username.$username;
    //Encryption Algorithm
    $cipher_alg = MCRYPT_RIJNDAEL_256;

    $iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher_alg, MCRYPT_MODE_ECB), MCRYPT_RAND);
    $password = mcrypt_encrypt($cipher_alg, $key, $pass1, MCRYPT_MODE_CBC, $iv);

然后将$ username,$ iv和$ password上载到MySQL数据库.

This then uploads the $username, the $iv and the $password to the MySQL database.

这是我的解密代码:

    //Encryption/Decryption key
    $key = $username.$username.$username.$username.$username;

    //Encryption Algorithm
    $cipher_alg = MCRYPT_RIJNDAEL_256;

    $dbpass = mcrypt_decrypt($cipher_alg, $key, $encpass, MCRYPT_MODE_CBC, $random);
    $dbpass = trim($dbpass); // Trim the fat

从数据库中检索$ username,$ iv和$ encpass(加密密码),并使用用户名重新创建密钥.

The $username, $iv, and $encpass(encrypted password) are retrieved from the database and the key is recreated using the username.

这有效,但仅在某些情况下有效.我不知道为什么.我唯一的假设是数据库不能接受加密产生的某些字符,例如引号.

This WORKS but only sometimes. I can't figure out why. My only assumption is that the database can't accept some of characters the encryption produces such as quotations.

任何帮助将不胜感激!

推荐答案

您可以尝试以下代码进行双向加密.您可以根据需要添加带有密码的盐.

You can try below code for 2 way encryption. You may add salt with password as per your requirement.

$key = 'ecryptionkey';
$string = 'password';

$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");

var_dump($encrypted);
var_dump($decrypted);

我从URL下面获得了此代码,并在我的应用程序中使用它.

I got this code from below URL and I'm using it in my application.

https://stackoverflow.com/a/9262137/1724762

这篇关于使用mcrypt,PHP和MySQL进行加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 15:27