Skip to content

Instantly share code, notes, and snippets.

@jaymecd
Last active December 28, 2015 23:19
Show Gist options
  • Save jaymecd/7578322 to your computer and use it in GitHub Desktop.
Save jaymecd/7578322 to your computer and use it in GitHub Desktop.
2-way php encryption (mcrypt)
#!/usr/bin/env php
<?php
class Coder
{
const CRYPT_CIPHER = MCRYPT_RIJNDAEL_128;
const CRYPT_MODE = MCRYPT_MODE_ECB;
protected static function get_crypt_iv()
{
$sz = mcrypt_get_iv_size(static::CRYPT_CIPHER, static::CRYPT_MODE);
$iv = mcrypt_create_iv($sz, MCRYPT_RAND);
return $iv;
}
protected static function get_crypt_key($key)
{
$key = hash('md5', $key);
return $key;
}
public static function encr($in, $key)
{
$iv = static::get_crypt_iv();
$key = static::get_crypt_key($key);
$out = mcrypt_encrypt(static::CRYPT_CIPHER, $key, $in, static::CRYPT_MODE, $iv);
$out = base64_encode($out);
return $out;
}
public static function decr($in, $key)
{
$iv = static::get_crypt_iv();
$key = static::get_crypt_key($key);
$in = base64_decode($in);
$out = mcrypt_decrypt(static::CRYPT_CIPHER, $key, $in, static::CRYPT_MODE, $iv);
$out = rtrim($out, "\0");
return $out;
}
}
$k = isset($argv[2]) ? $argv[2] : 'secret';
$p = isset($argv[1]) ? $argv[1] : 'passwd';
$ep = Coder::encr($p, $k);
$dp = Coder::decr($ep, $k);
var_dump($k, $p, $ep, $dp, $p === $dp);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment