How to encrypt any text by key, that is, without having a key, the text cannot be decrypted. Please explain on the fingers, how to do it?
4 answers
On the fingers like this, just use the mcrypt extension:
Encrypt.
http://php.net/manual/ru/function.mcrypt-encrypt.php
string mcrypt_encrypt ( string $cipher , string $key , string $data , string $mode [, string $iv ] ) Decipher.
http://php.net/manual/ru/function.mcrypt-decrypt.php
string mcrypt_decrypt ( string $cipher , string $key , string $data , string $mode [, string $iv ] ) The most accessible and obvious option is XOR encryption. If you have a specific key (string) and xor`it each character of the source string on the [string.index% key.length] key, then you will need to have a key to perform the inverse operation (decryption).
- The question indicates the requirement that without the key the text should be impossible to decrypt. Encryption using XOR without a key will revert to any student, if you know at least something about the source text. - Athari
- In general, almost all encryption is built on xor. In the case of a short key, it can be calculated by stat.analysis. - etki
- Friends, no one stutters about the security of XOR-encryption. But as an example quite fit. - AseN
You can consider this solution:
function __encode($text, $key) { $td = mcrypt_module_open ("tripledes", '', 'cfb', ''); $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($td), MCRYPT_RAND); if (mcrypt_generic_init ($td, $key, $iv) != -1) { $enc_text=base64_encode(mcrypt_generic ($td,$iv.$text)); mcrypt_generic_deinit ($td); mcrypt_module_close ($td); return $enc_text; } } function strToHex($string) { $hex=''; for ($i=0; $i < strlen($string); $i++) { $hex .= dechex(ord($string[$i])); } return $hex; } function __decode($text, $key) { $td = mcrypt_module_open ("tripledes", '', 'cfb', ''); $iv_size = mcrypt_enc_get_iv_size ($td); $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($td), MCRYPT_RAND); if (mcrypt_generic_init ($td, $key, $iv) != -1) { $decode_text = substr(mdecrypt_generic ($td, base64_decode($text)),$iv_size); mcrypt_generic_deinit ($td); mcrypt_module_close ($td); return $decode_text; } } public function hexToStr($hex) { $string=''; for ($i=0; $i < strlen($hex)-1; $i+=2) { $string .= chr(hexdec($hex[$i].$hex[$i+1])); } return $string; } Encrypt
$code = strToHex(__encode($str, 'your key')); Decipher
$str = __decode(hexToStr($code), 'your key'); - Deprecated: Function mcrypt_module_open () is deprecated - fdrv
It's so easy to use naked mcrypt correctly (i.e., to have strong encryption) is not an easy task. Each algorithm has its own correct parameters.
Therefore, here is a link to the example code in which AES-128 encryption is implemented https://stackoverflow.com/questions/1788150/how-to-encrypt-string-in-php/19445173#19445173
In the bank, such encryption, of course, cannot be used, but even for an Internet shop it will do.