历史注释:这是在PHP4时代编写的。这就是我们现在所说的“遗留代码”。
出于历史原因,我留下了这个答案——但有些方法现在已弃用,DES加密方法不是推荐的实践,等等。
我没有更新这段代码有两个原因:1)我不再在PHP中手工使用加密方法,2)这段代码仍然达到了预期的目的:演示如何在PHP中进行加密的最简单的概念。
如果你发现类似简单的“PHP加密傻瓜”的源代码,可以让人们在10-20行代码或更少的代码中开始,请在评论中告诉我。
除此之外,请欣赏这个早期PHP4极简加密答案的经典集。
理想情况下,您已经或能够访问mcrypt 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 );
?>
一些警告:
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.
3)任何一种容易实现的加密,如这里所列,都可以合理地保护你想要避免被窥探或限制意外/故意泄露的情况下暴露的轻度重要信息。但鉴于密钥是如何以纯文本形式存储在web服务器上的,如果他们能获得数据,他们就能获得解密密钥。
尽管如此,玩得开心吧。