In 2013 I published an article titled “Creating Reversible Passwords with PHP”, and lately I've been getting feedback about it. The reason is that the Mcrypt library used in that article's approach is no longer available in newer versions of PHP.
I developed the class below both as an alternative and so that it doesn't require any extra dependency.
Feel free to use it as you like:
Class
<?php
/*
* A "Reversible" password encryption routine by Sinan Eldem
* www.sinaneldem.com.tr
* V. 2.9
* 18.07.2018 11:15
*/
class MyHash {
public function encode($string, $key) {
$result = '';
for ($i = 0; $i < strlen($string); $i++) {
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key)) - 1, 1);
$char = chr(ord($char) + ord($keychar));
$result .= $char;
}
return base64_encode($result);
}
public function decode($string, $key) {
$result = '';
$string = base64_decode($string);
for ($i = 0; $i < strlen($string); $i++) {
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key)) - 1, 1);
$char = chr(ord($char) - ord($keychar));
$result .= $char;
}
return $result;
}
}
$key = '123abc!#,678def';
$string = 'Merhaba Dünya!';
$encoded = (new MyHash)->encode($string, $key);
$decoded = (new MyHash)->decode($encoded, $key);
echo $encoded; // s5akm8LExEFn7/KlscWG
echo '<br>';
echo $decoded; // Merhaba Dünya!
Happy coding.