Skip to content
Home Sinan Eldem
Software

Creating Reversible Passwords with PHP

Sinan Eldem

• 4 min read

Creating Reversible Passwords with PHP

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.

Sinan Eldem

Custom software and AI solutions with Laravel

Related posts

Software
6 min read

Laravel Eloquent Relationships Quick Reference Guide

This quick reference is a practical guide that explains the most common relationship types with simple examples. Covering hasOne, hasMany, belongsTo, belongsToMany and polymorphic relationships along with eager loading and performance tips, it gives developers a fast and accurate reference.

Read more