使用密钥 PHP 加密和解密字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2806682/
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
Encrypt and Decrypt String With Key PHP
提问by Belgin Fish
I'm looking for some functions to encrypt and decrypt strings in php using a key specified.
我正在寻找一些函数来使用指定的密钥加密和解密 php 中的字符串。
Thanks!
谢谢!
采纳答案by labratmatt
Start with this: http://www.ibm.com/developerworks/opensource/library/os-php-encrypt/
从这个开始:http: //www.ibm.com/developerworks/opensource/library/os-php-encrypt/
After that, have a look at Pascal MARTIN's answer in How do I encrypt a string in PHP?
之后,看看 Pascal MARTIN 在如何在 PHP 中加密字符串中的回答?
回答by Mark
A basic openssl implementation I've used before:
我以前使用过的一个基本的 openssl 实现:
class MyEncryption
{
public $pubkey = '...public key here...';
public $privkey = '...private key here...';
public function encrypt($data)
{
if (openssl_public_encrypt($data, $encrypted, $this->pubkey))
$data = base64_encode($encrypted);
else
throw new Exception('Unable to encrypt data. Perhaps it is bigger than the key size?');
return $data;
}
public function decrypt($data)
{
if (openssl_private_decrypt(base64_decode($data), $decrypted, $this->privkey))
$data = $decrypted;
else
$data = '';
return $data;
}
}
You would need to generate the RSA key pair. See here for informationon how to do that. Storing the private key in the file itself is a bad idea. This is just an example. Ideally you would want the user to supply the private key at decryption time
您需要生成 RSA 密钥对。有关如何执行此操作的信息,请参见此处。将私钥存储在文件本身中是一个坏主意。这只是一个例子。理想情况下,您希望用户在解密时提供私钥
回答by ZZ Coder
I assume you meant symmetric key encryption. mcrypt does support several algorithms (Like AES, Tripel DES). There is one catch though, it doesn't support any padding algorithm so you wouldn't be able to get the original length back. You have 2 options to get around this issue,
我假设您的意思是对称密钥加密。mcrypt 确实支持多种算法(如 AES、Tripel DES)。但是有一个问题,它不支持任何填充算法,因此您将无法恢复原始长度。您有 2 个选项可以解决此问题,
Add a length field in front of your clear-text. Say use first 4 bytes as length.
Do PKCS#5 padding yourself. There are code examples on this page: http://www.php.net/manual/en/function.mcrypt-encrypt.php
在您的明文前面添加一个长度字段。说使用前 4 个字节作为长度。
自己做 PKCS#5 填充。本页有代码示例:http: //www.php.net/manual/en/function.mcrypt-encrypt.php

