问题描述
我正在使用Mcrypt加密一些字符串.
I am using Mcrypt to encrypt some strings.
此后,我将它们存储在数据库中,但是在我的数据库中看起来像"?? f ?? R ?????? h $",因为许多特殊字符被'?'代替.
After that I store them in my database, but in my database it looks like "??f??R?????h$", because many special chars are replaced by a '?'.
我必须使用特殊的字符集还是有另一种简单的方法吗?
Do I have to use a special charset or is there another simple way?
关于,Cr41s3
Regards,Cr41s3
推荐答案
我认为您可能正在将加密字符串的字节直接保存到mysql数据库中.
I think you might be saving the encrypted string's bytes directly into mysql database.
您可以执行以下操作来解决您的问题:
You could do something like this to solve your problem:
-
加密:原始文本> MCrypt加密> Base64编码>在MySQL中存储为纯文本
Encryption: Orignal Text > MCrypt Encrypt > Base64 Encode > Store as Plain Text in MySQL
解密:从MySQL> Base64解码> MCrypt解密->原始文本加载加密的base64编码文本
Decryption: Load encrypted base64 encoded text from MySQL > Base64 Decode > MCrypt Decrypt -> Orignal Text
这就是我要做的.创建一个类进行加密/解密:
This is how I would do it. Create a class to do encryption/decryption:
<?php
class cipher
{
private $securekey;
private $iv_size;
function __construct($textkey)
{
$this->iv_size = mcrypt_get_iv_size(
MCRYPT_RIJNDAEL_128,
MCRYPT_MODE_CBC
);
$this->securekey = hash(
'sha256',
$textkey,
TRUE
);
}
function encrypt($input)
{
$iv = mcrypt_create_iv($this->iv_size);
return base64_encode(
$iv . mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
$this->securekey,
$input,
MCRYPT_MODE_CBC,
$iv
)
);
}
function decrypt($input)
{
$input = base64_decode($input);
$iv = substr(
$input,
0,
$this->iv_size
);
$cipher = substr(
$input,
$this->iv_size
);
return trim(
mcrypt_decrypt(
MCRYPT_RIJNDAEL_128,
$this->securekey,
$cipher,
MCRYPT_MODE_CBC,
$iv
)
);
}
}
?>
然后像这样使用它:
// Usage
$cipher = new cipher('my-secret-key');
$orignal_text = 'my secret message';
$encrypted_text = $cipher->encrypt($orignal_text); // store this in db
$decrypted_text = $cipher->decrypt($encrypted_text); // load $encrypted_text from db
// Debug
echo "<pre>";
echo "Orignal Text : $orignal_text\r\n";
echo "Encrypted Text: $encrypted_text\r\n";
echo "Decrypted Text: $decrypted_text";
echo "</pre>";
这分别输出以下内容:
Orignal Text : my secret message
Encrypted Text: Z21ifr5dHEdE9nO8vaDWb9QkjooqCK4UI6D/Ui+fkpmXWwmxloy8hM+7oimtw1wE
Decrypted Text: my secret message
这篇关于PHP使用mcrypt并将加密后的内容存储在MySQL中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!