如何加密和解密 PHP 字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16600708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you Encrypt and Decrypt a PHP String?
提问by u775856
What I mean is:
我的意思是:
Original String + Salt or Key --> Encrypted String
Encrypted String + Salt or Key --> Decrypted (Original String)
Maybe something like:
也许是这样的:
"hello world!" + "ABCD1234" --> Encrypt --> "2a2ffa8f13220befbe30819047e23b2c" (may be, for e.g)
"2a2ffa8f13220befbe30819047e23b2c" --> Decrypt with "ABCD1234" --> "hello world!"
- In PHP, how can you do this?
- 在 PHP 中,你怎么能做到这一点?
Attempted to use Crypt_Blowfish
, but it didn't work for me.
尝试使用Crypt_Blowfish
,但它对我不起作用。
采纳答案by u775856
Updated
更新
PHP 7 ready version. It uses openssl_encryptfunction from PHP OpenSSL Library.
PHP 7 就绪版本。它使用PHP OpenSSL 库中的openssl_encrypt函数。
class Openssl_EncryptDecrypt {
function encrypt ($pure_string, $encryption_key) {
$cipher = 'AES-256-CBC';
$options = OPENSSL_RAW_DATA;
$hash_algo = 'sha256';
$sha2len = 32;
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($pure_string, $cipher, $encryption_key, $options, $iv);
$hmac = hash_hmac($hash_algo, $ciphertext_raw, $encryption_key, true);
return $iv.$hmac.$ciphertext_raw;
}
function decrypt ($encrypted_string, $encryption_key) {
$cipher = 'AES-256-CBC';
$options = OPENSSL_RAW_DATA;
$hash_algo = 'sha256';
$sha2len = 32;
$ivlen = openssl_cipher_iv_length($cipher);
$iv = substr($encrypted_string, 0, $ivlen);
$hmac = substr($encrypted_string, $ivlen, $sha2len);
$ciphertext_raw = substr($encrypted_string, $ivlen+$sha2len);
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $encryption_key, $options, $iv);
$calcmac = hash_hmac($hash_algo, $ciphertext_raw, $encryption_key, true);
if(function_exists('hash_equals')) {
if (hash_equals($hmac, $calcmac)) return $original_plaintext;
} else {
if ($this->hash_equals_custom($hmac, $calcmac)) return $original_plaintext;
}
}
/**
* (Optional)
* hash_equals() function polyfilling.
* PHP 5.6+ timing attack safe comparison
*/
function hash_equals_custom($knownString, $userString) {
if (function_exists('mb_strlen')) {
$kLen = mb_strlen($knownString, '8bit');
$uLen = mb_strlen($userString, '8bit');
} else {
$kLen = strlen($knownString);
$uLen = strlen($userString);
}
if ($kLen !== $uLen) {
return false;
}
$result = 0;
for ($i = 0; $i < $kLen; $i++) {
$result |= (ord($knownString[$i]) ^ ord($userString[$i]));
}
return 0 === $result;
}
}
define('ENCRYPTION_KEY', '__^%&Q@$&*!@#$%^&*^__');
$string = "This is the original string!";
$OpensslEncryption = new Openssl_EncryptDecrypt;
$encrypted = $OpensslEncryption->encrypt($string, ENCRYPTION_KEY);
$decrypted = $OpensslEncryption->decrypt($encrypted, ENCRYPTION_KEY);
回答by Scott Arciszewski
Before you do anything further, seek to understand the difference between encryptionand authentication, and why you probably want authenticated encryptionrather than just encryption.
在进一步操作之前,请先了解加密和身份验证之间的区别,以及为什么您可能需要经过身份验证的加密而不仅仅是加密。
To implement authenticated encryption, you want to Encrypt then MAC. The order of encryption and authentication is very important!One of the existing answers to this question made this mistake; as do many cryptography libraries written in PHP.
要实现经过身份验证的加密,您需要先加密,然后再 MAC。加密和认证的顺序很重要!这个问题的现有答案之一犯了这个错误;许多用 PHP 编写的密码学库也是如此。
You should avoid implementing your own cryptography, and instead use a secure library written by and reviewed by cryptography experts.
您应该避免实施自己的密码学,而应使用由密码学专家编写和的安全库。
Update: PHP 7.2 now provides libsodium! For best security, update your systems to use PHP 7.2 or higher and only follow the libsodium advice in this answer.
更新:PHP 7.2 现在提供 libsodium!为了获得最佳安全性,请更新您的系统以使用 PHP 7.2 或更高版本,并且仅遵循此答案中的 libsodium 建议。
Use libsodium if you have PECL access(or sodium_compatif you want libsodium without PECL); otherwise...
Use defuse/php-encryption; don't roll your own cryptography!
如果您有 PECL 访问权限,请使用 libsodium(如果您想要没有 PECL 的libsodium,请使用sodium_compat);否则...
使用 defuse/php-encryption; 不要推出自己的密码学!
Both of the libraries linked above above make it easy and painless to implement authenticated encryption into your own libraries.
上面链接的两个库都可以轻松轻松地在您自己的库中实现经过身份验证的加密。
If you still want to write and deploy your own cryptography library, against the conventional wisdom of every cryptography expert on the Internet, these are the steps you would have to take.
如果您仍然想编写和部署自己的密码学库,与 Internet 上每个密码学专家的传统智慧相反,这些是您必须采取的步骤。
Encryption:
加密:
- Encrypt using AES in CTR mode. You may also use GCM (which removes the need for a separate MAC). Additionally, ChaCha20 and Salsa20 (provided by libsodium) are stream ciphers and do not need special modes.
- Unless you chose GCM above, you should authenticate the ciphertext with HMAC-SHA-256 (or, for the stream ciphers, Poly1305 -- most libsodium APIs do this for you). The MAC should cover the IV as well as the ciphertext!
- 在 CTR 模式下使用 AES 加密。您也可以使用 GCM(无需单独的 MAC)。此外,ChaCha20 和 Salsa20(由libsodium提供)是流密码,不需要特殊模式。
- 除非您选择了上面的 GCM,否则您应该使用 HMAC-SHA-256(或者,对于流密码,Poly1305——大多数 libsodium API 为您执行此操作)验证密文。MAC应该涵盖IV以及密文!
Decryption:
解密:
- Unless Poly1305 or GCM is used, recalculate the MAC of the ciphertext and compare it with the MAC that was sent using
hash_equals()
. If it fails, abort. - Decrypt the message.
- 除非使用 Poly1305 或 GCM,否则重新计算密文的 MAC,并将其与使用 发送的 MAC 进行比较
hash_equals()
。如果失败,则中止。 - 解密消息。
Other Design Considerations:
其他设计注意事项:
- Do not compress anything ever. Ciphertext is not compressible; compressing plaintext before encryption can lead to information leaks (e.g. CRIME and BREACH on TLS).
- Make sure you use
mb_strlen()
andmb_substr()
, using the'8bit'
character set mode to preventmbstring.func_overload
issues. - IVs should be generating using a CSPRNG; If you're using
mcrypt_create_iv()
, DO NOT USEMCRYPT_RAND
!- Also check out random_compat.
- Unless you're using an AEAD construct, ALWAYS encrypt then MAC!
bin2hex()
,base64_encode()
, etc. may leak information about your encryption keys via cache timing. Avoid them if possible.
- 不要压缩任何东西。密文不可压缩;在加密之前压缩明文会导致信息泄漏(例如 TLS 上的 CRIME 和 BREACH)。
- 确保使用
mb_strlen()
和mb_substr()
,使用'8bit'
字符集模式来防止出现mbstring.func_overload
问题。 - IV 应该使用CSPRNG生成;如果您正在使用
mcrypt_create_iv()
,请勿使用MCRYPT_RAND
!- 另请查看random_compat。
- 除非您使用的是 AEAD 构造,否则始终先加密 MAC!
bin2hex()
、base64_encode()
等可能会通过缓存计时泄露有关您的加密密钥的信息。如果可能,请避免使用它们。
Even if you follow the advice given here, a lot can go wrong with cryptography. Always have a cryptography expert review your implementation.If you are not fortunate enough to be personal friends with a cryptography student at your local university, you can always try the Cryptography Stack Exchangeforum for advice.
即使您遵循此处给出的建议,密码学也可能会出现很多问题。始终让密码学专家您的实施。如果您没有幸与当地大学的密码学学生成为私人朋友,您可以随时尝试密码堆栈交换论坛寻求建议。
If you need a professional analysis of your implementation, you can always hire a reputable team of security consultants to review your PHP cryptography code(disclosure: my employer).
如果您需要对您的实现进行专业分析,您可以随时聘请信誉良好的安全顾问团队来您的 PHP 加密代码(披露:我的雇主)。
Important: When to Not Use Encryption
重要提示:何时不使用加密
Don't encryptpasswords. You want to hashthem instead, using one of these password-hashing algorithms:
不要加密密码。你想散他们,而不是使用这些密码散列算法之一:
Never use a general-purpose hash function (MD5, SHA256) for password storage.
切勿使用通用哈希函数(MD5、SHA256)来存储密码。
Don't encrypt URL Parameters.It's the wrong tool for the job.
不要加密 URL 参数。这是工作的错误工具。
PHP String Encryption Example with Libsodium
使用 Libsodium 的 PHP 字符串加密示例
If you are on PHP < 7.2 or otherwise do not have libsodium installed, you can use sodium_compatto accomplish the same result (albeit slower).
如果您使用的是 PHP < 7.2 或者没有安装 libsodium,您可以使用sodium_compat来完成相同的结果(虽然速度较慢)。
<?php
declare(strict_types=1);
/**
* Encrypt a message
*
* @param string $message - message to encrypt
* @param string $key - encryption key
* @return string
* @throws RangeException
*/
function safeEncrypt(string $message, string $key): string
{
if (mb_strlen($key, '8bit') !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
throw new RangeException('Key is not the correct size (must be 32 bytes).');
}
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$cipher = base64_encode(
$nonce.
sodium_crypto_secretbox(
$message,
$nonce,
$key
)
);
sodium_memzero($message);
sodium_memzero($key);
return $cipher;
}
/**
* Decrypt a message
*
* @param string $encrypted - message encrypted with safeEncrypt()
* @param string $key - encryption key
* @return string
* @throws Exception
*/
function safeDecrypt(string $encrypted, string $key): string
{
$decoded = base64_decode($encrypted);
$nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
$ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');
$plain = sodium_crypto_secretbox_open(
$ciphertext,
$nonce,
$key
);
if (!is_string($plain)) {
throw new Exception('Invalid MAC');
}
sodium_memzero($ciphertext);
sodium_memzero($key);
return $plain;
}
Then to test it out:
然后测试一下:
<?php
// This refers to the previous code block.
require "safeCrypto.php";
// Do this once then store it somehow:
$key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);
$message = 'We are all living in a yellow submarine';
$ciphertext = safeEncrypt($message, $key);
$plaintext = safeDecrypt($ciphertext, $key);
var_dump($ciphertext);
var_dump($plaintext);
Halite - Libsodium Made Easier
Halite - Libsodium 变得更容易
One of the projects I've been working on is an encryption library called Halite, which aims to make libsodium easier and more intuitive.
一个我一直在工作的项目是称为加密库岩盐,使libsodium更简单,更直观,其目的。
<?php
use \ParagonIE\Halite\KeyFactory;
use \ParagonIE\Halite\Symmetric\Crypto as SymmetricCrypto;
// Generate a new random symmetric-key encryption key. You're going to want to store this:
$key = new KeyFactory::generateEncryptionKey();
// To save your encryption key:
KeyFactory::save($key, '/path/to/secret.key');
// To load it again:
$loadedkey = KeyFactory::loadEncryptionKey('/path/to/secret.key');
$message = 'We are all living in a yellow submarine';
$ciphertext = SymmetricCrypto::encrypt($message, $key);
$plaintext = SymmetricCrypto::decrypt($ciphertext, $key);
var_dump($ciphertext);
var_dump($plaintext);
All of the underlying cryptography is handled by libsodium.
所有底层密码学都由 libsodium 处理。
Example with defuse/php-encryption
使用 defuse/php-encryption 的示例
<?php
/**
* This requires https://github.com/defuse/php-encryption
* php composer.phar require defuse/php-encryption
*/
use Defuse\Crypto\Crypto;
use Defuse\Crypto\Key;
require "vendor/autoload.php";
// Do this once then store it somehow:
$key = Key::createNewRandomKey();
$message = 'We are all living in a yellow submarine';
$ciphertext = Crypto::encrypt($message, $key);
$plaintext = Crypto::decrypt($ciphertext, $key);
var_dump($ciphertext);
var_dump($plaintext);
Note: Crypto::encrypt()
returns hex-encoded output.
注意:Crypto::encrypt()
返回十六进制编码的输出。
Encryption Key Management
加密密钥管理
If you're tempted to use a "password", stop right now. You need a random 128-bit encryption key, not a human memorable password.
如果您想使用“密码”,请立即停止。您需要一个随机的 128 位加密密钥,而不是人类容易记住的密码。
You can store an encryption key for long-term use like so:
您可以存储加密密钥以供长期使用,如下所示:
$storeMe = bin2hex($key);
And, on demand, you can retrieve it like so:
而且,根据需要,您可以像这样检索它:
$key = hex2bin($storeMe);
I stronglyrecommend just storing a randomly generated key for long-term use instead of any sort of password as the key (or to derive the key).
我强烈建议只存储一个随机生成的密钥以供长期使用,而不是将任何类型的密码作为密钥(或派生密钥)。
If you're using Defuse's library:
如果您使用的是 Defuse 的库:
"But I reallywant to use a password."
“但我真的很想使用密码。”
That's a bad idea, but okay, here's how to do it safely.
这是一个坏主意,但好吧,这里是如何安全地做到这一点。
First, generate a random key and store it in a constant.
首先,生成一个随机密钥并将其存储在一个常量中。
/**
* Replace this with your own salt!
* Use bin2hex() then add \x before every 2 hex characters, like so:
*/
define('MY_PBKDF2_SALT', "\x2d\xb7\x68\x1a\x28\x15\xbe\x06\x33\xa0\x7e\x0e\x8f\x79\xd5\xdf");
Note that you're adding extra work and could just use this constant as the key and save yourself a lot of heartache!
请注意,您正在添加额外的工作,并且可以仅使用此常量作为键并为自己省去很多心痛!
Then use PBKDF2 (like so) to derive a suitable encryption key from your password rather than encrypting with your password directly.
然后使用 PBKDF2(像这样)从您的密码中派生出合适的加密密钥,而不是直接使用您的密码进行加密。
/**
* Get an AES key from a static password and a secret salt
*
* @param string $password Your weak password here
* @param int $keysize Number of bytes in encryption key
*/
function getKeyFromPassword($password, $keysize = 16)
{
return hash_pbkdf2(
'sha256',
$password,
MY_PBKDF2_SALT,
100000, // Number of iterations
$keysize,
true
);
}
Don't just use a 16-character password. Your encryption key will be comically broken.
不要只使用 16 个字符的密码。您的加密密钥将被可笑地破坏。
回答by Emil Borconi
I'm late to the party, but searching for the correct way to do it I came across this page it was one of the top Google search returns, so I will like to share my view on the problem, which I consider it to be up to date at the time of writing this post (beginning of 2017). From PHP 7.1.0 the mcrypt_decrypt
and mcrypt_encrypt
is going to be deprecated, so building future proof code should use openssl_encryptand openssl_decrypt
我迟到了,但正在寻找正确的方法来做这件事我遇到了这个页面,它是谷歌搜索返回最多的页面之一,所以我想分享我对这个问题的看法,我认为它是在撰写本文时是最新的(2017 年初)。从 PHP 7.1.0mcrypt_decrypt
和mcrypt_encrypt
将被弃用,因此构建未来证明代码应该使用openssl_encrypt和openssl_decrypt
You can do something like:
您可以执行以下操作:
$string_to_encrypt="Test";
$password="password";
$encrypted_string=openssl_encrypt($string_to_encrypt,"AES-128-ECB",$password);
$decrypted_string=openssl_decrypt($encrypted_string,"AES-128-ECB",$password);
Important: This uses ECB mode, which isn't secure. If you want a simple solution without taking a crash course in cryptography engineering, don't write it yourself, just use a library.
重要提示:这使用不安全的ECB 模式。如果您想要一个简单的解决方案,而无需参加密码工程速成课程,请不要自己编写,只需使用库即可。
You can use any other chipper methods as well, depending on your security need. To find out the available chipper methods please see the openssl_get_cipher_methodsfunction.
您也可以使用任何其他削片方法,具体取决于您的安全需要。要找出可用的切片器方法,请参阅openssl_get_cipher_methods函数。
回答by u775856
What not to do
什么不该做
WARNING:
This answer uses ECB. ECB is not an encryption mode, it's only a building block. Using ECB as demonstrated in this answer does not actually encrypt the string securely. Do not use ECB in your code. See Scott's answerfor a good solution.
警告:
此答案使用ECB。ECB 不是一种加密模式,它只是一个构建块。使用本答案中演示的 ECB 实际上并不能安全地加密字符串。不要在您的代码中使用 ECB。请参阅Scott 的答案以获得一个好的解决方案。
I got it on myself. Actually i found some answer on google and just modified something. The result is completely insecure however.
我自己弄的。其实我在谷歌上找到了一些答案,只是修改了一些东西。然而,结果是完全不安全的。
<?php
define("ENCRYPTION_KEY", "!@#$%^&*");
$string = "This is the original data string!";
echo $encrypted = encrypt($string, ENCRYPTION_KEY);
echo "<br />";
echo $decrypted = decrypt($encrypted, ENCRYPTION_KEY);
/**
* Returns an encrypted & utf8-encoded
*/
function encrypt($pure_string, $encryption_key) {
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$encrypted_string = mcrypt_encrypt(MCRYPT_BLOWFISH, $encryption_key, utf8_encode($pure_string), MCRYPT_MODE_ECB, $iv);
return $encrypted_string;
}
/**
* Returns decrypted original string
*/
function decrypt($encrypted_string, $encryption_key) {
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypted_string = mcrypt_decrypt(MCRYPT_BLOWFISH, $encryption_key, $encrypted_string, MCRYPT_MODE_ECB, $iv);
return $decrypted_string;
}
?>
回答by Somnath Muluk
For Laravel framework
对于 Laravel 框架
If you are using Laravel framework then it's more easy to encrypt and decrypt with internal functions.
如果您使用的是 Laravel 框架,那么使用内部函数进行加密和解密会更容易。
$string = 'Some text to be encrypted';
$encrypted = \Illuminate\Support\Facades\Crypt::encrypt($string);
$decrypted_string = \Illuminate\Support\Facades\Crypt::decrypt($encrypted);
var_dump($string);
var_dump($encrypted);
var_dump($decrypted_string);
Note: Be sure to set a 16, 24, or 32 character random string in the key option of the config/app.php file. Otherwise, encrypted values will not be secure.
注意:请务必在 config/app.php 文件的 key 选项中设置一个 16、24 或 32 个字符的随机字符串。否则,加密的值将不安全。
回答by Ascon
If you don't want to use library (which you should) then use something like this (PHP 7):
如果你不想使用库(你应该使用),那么使用这样的东西(PHP 7):
function sign($message, $key) {
return hash_hmac('sha256', $message, $key) . $message;
}
function verify($bundle, $key) {
return hash_equals(
hash_hmac('sha256', mb_substr($bundle, 64, null, '8bit'), $key),
mb_substr($bundle, 0, 64, '8bit')
);
}
function getKey($password, $keysize = 16) {
return hash_pbkdf2('sha256',$password,'some_token',100000,$keysize,true);
}
function encrypt($message, $password) {
$iv = random_bytes(16);
$key = getKey($password);
$result = sign(openssl_encrypt($message,'aes-256-ctr',$key,OPENSSL_RAW_DATA,$iv), $key);
return bin2hex($iv).bin2hex($result);
}
function decrypt($hash, $password) {
$iv = hex2bin(substr($hash, 0, 32));
$data = hex2bin(substr($hash, 32));
$key = getKey($password);
if (!verify($data, $key)) {
return null;
}
return openssl_decrypt(mb_substr($data, 64, null, '8bit'),'aes-256-ctr',$key,OPENSSL_RAW_DATA,$iv);
}
$string_to_encrypt='John Smith';
$password='password';
$encrypted_string=encrypt($string_to_encrypt, $password);
$decrypted_string=decrypt($encrypted_string, $password);
回答by BrianH
Historical Note:This was written at the time of PHP4. This is what we call "legacy code" now.
历史注释:这是在 PHP4 时代编写的。这就是我们现在所说的“遗留代码”。
I have left this answer for historical purposes - but some of the methods are now deprecated, DES encryption method is not a recommended practice, etc.
我出于历史目的留下了这个答案 - 但是现在不推荐使用某些方法,不推荐使用 DES 加密方法等。
I have not updated this code for two reasons: 1) I no longer work with encryption methods by hand in PHP, and 2) this code still serves the purpose it was intended for: to demonstrate the minimum, simplistic concept of how encryption can work in PHP.
我没有更新这段代码有两个原因:1)我不再在 PHP 中手动使用加密方法,2)这段代码仍然达到它的目的:演示加密如何工作的最小、简单的概念在 PHP 中。
If you find a similarly simplistic, "PHP encryption for dummies" kind of source that can get people started in 10-20 lines of code or less, let me know in comments.
如果您发现类似简单的“傻瓜式 PHP 加密”类型的源代码,可以让人们以 10-20 行或更少的代码开始,请在评论中告诉我。
Beyond that, please enjoy this Classic Episode of early-era PHP4 minimalistic encryption answer.
除此之外,请欣赏这个早期 PHP4 简约加密答案的经典集。
Ideally you have - or can get - access to the mcrypt PHP library, as its certainly popular and very useful a variety of tasks. Here's a run down of the different kinds of encryption and some example code: Encryption Techniques in PHP
理想情况下,您可以访问或可以访问 mcrypt PHP 库,因为它在各种任务中非常流行且非常有用。这是对不同类型加密和一些示例代码的总结:PHP 中的加密技术
//Listing 3: Encrypting Data Using the mcrypt_ecb Function
<?php
echo("<h3> Symmetric Encryption </h3>");
$key_value = "KEYVALUE";
$plain_text = "PLAINTEXT";
$encrypted_text = mcrypt_ecb(MCRYPT_DES, $key_value, $plain_text, MCRYPT_ENCRYPT);
echo ("<p><b> Text after encryption : </b>");
echo ( $encrypted_text );
$decrypted_text = mcrypt_ecb(MCRYPT_DES, $key_value, $encrypted_text, MCRYPT_DECRYPT);
echo ("<p><b> Text after decryption : </b>");
echo ( $decrypted_text );
?>
A few warnings:
一些警告:
1) Never use reversible, or "symmetric" encryption when a one-way hash will do.
1) 当单向散列可以使用时,切勿使用可逆或“对称”加密。
2) If the data is truly sensitive, like credit card or social security numbers, stop; you need more than any simple chunk of code will provide, but rather you need a crypto library designed for this purpose and a significant amount of time to research the methods necessary. Further, the software crypto is probably <10% of security of sensitive data. It's like rewiring a nuclear power station - accept that the task is dangerous and difficult and beyond your knowledge if that's the case. The financial penalties can be immense, so better to use a service and ship responsibility to them.
2) 如果数据真的很敏感,比如信用卡或社会安全号码,停止;您需要的不仅仅是任何简单的代码块所能提供的,而是您需要为此目的而设计的加密库和大量时间来研究必要的方法。此外,软件加密可能不到敏感数据安全性的 10%。这就像为核电站重新布线 - 接受这项任务是危险和困难的,如果是这样的话,你可能不知道。经济处罚可能是巨大的,因此最好使用服务并将责任交给他们。
3) Any sort of easily implementable encryption, as listed here, can reasonably protect mildly important information that you want to keep from prying eyes or limit exposure in the case of accidental/intentional leak. But seeing as how the key is stored in plain text on the web server, if they can get the data they can get the decryption key.
3) 此处列出的任何类型的易于实施的加密都可以合理地保护您想要防止窥探或在意外/故意泄漏的情况下限制暴露的轻微重要信息。但是看看密钥如何以纯文本形式存储在 Web 服务器上,如果他们可以获得数据,他们就可以获得解密密钥。
Be that as it may, have fun :)
尽管如此,玩得开心:)
回答by Javed
Below code work in php for all string with special character
下面的代码在 php 中适用于所有带有特殊字符的字符串
// Encrypt text --
$token = "9611222007552";
$cipher_method = 'aes-128-ctr';
$enc_key = openssl_digest(php_uname(), 'SHA256', TRUE);
$enc_iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher_method));
$crypted_token = openssl_encrypt($token, $cipher_method, $enc_key, 0, $enc_iv) . "::" . bin2hex($enc_iv);
echo $crypted_token;
//unset($token, $cipher_method, $enc_key, $enc_iv);
// Decrypt text --
list($crypted_token, $enc_iv) = explode("::", $crypted_token);
$cipher_method = 'aes-128-ctr';
$enc_key = openssl_digest(php_uname(), 'SHA256', TRUE);
$token = openssl_decrypt($crypted_token, $cipher_method, $enc_key, 0, hex2bin($enc_iv));
echo $token;
//unset($crypted_token, $cipher_method, $enc_key, $enc_iv);