add functions for hashing and encoding

This commit is contained in:
Pekka Laiho 2020-12-21 08:49:05 +07:00
parent b4d8715525
commit 7049d54427
4 changed files with 88 additions and 0 deletions

33
src/Lib/Crypto.php Normal file
View File

@ -0,0 +1,33 @@
<?php
/**
* MadLisp language
* @link http://madlisp.com/
* @copyright Copyright (c) 2020 Pekka Laiho
*/
namespace MadLisp\Lib;
use MadLisp\CoreFunc;
use MadLisp\Env;
class Crypto implements ILib
{
public function register(Env $env): void
{
$env->set('md5', new CoreFunc('md5', 'Calculate the MD5 hash of a string.', 1, 1,
fn (string $a) => md5($a)
));
$env->set('sha1', new CoreFunc('sha1', 'Calculate the SHA1 hash of a string.', 1, 1,
fn (string $a) => sha1($a)
));
$env->set('pw-hash', new CoreFunc('pw-hash', 'Calculate hash from a password.', 1, 1,
fn (string $a) => password_hash($a, PASSWORD_DEFAULT)
));
$env->set('pw-verify', new CoreFunc('pw-verify', 'Verify that given password matches a hash.', 2, 2,
fn (string $pw, string $hash) => password_verify($pw, $hash)
));
}
}

49
src/Lib/Encoding.php Normal file
View File

@ -0,0 +1,49 @@
<?php
/**
* MadLisp language
* @link http://madlisp.com/
* @copyright Copyright (c) 2020 Pekka Laiho
*/
namespace MadLisp\Lib;
use MadLisp\CoreFunc;
use MadLisp\Env;
class Encoding implements ILib
{
public function register(Env $env): void
{
$env->set('bin2hex', new CoreFunc('bin2hex', 'Convert binary data to hexadecimal representation.', 1, 1,
fn (string $a) => bin2hex($a)
));
$env->set('hex2bin', new CoreFunc('hex2bin', 'Decode a hexadecimally encoded binary string.', 1, 1,
fn (string $a) => hex2bin($a)
));
$env->set('to-base64', new CoreFunc('to-base64', 'Encode binary data to Base64 representation.', 1, 1,
fn (string $a) => base64_encode($a)
));
$env->set('from-base64', new CoreFunc('from-base64', 'Decode a Base64 encoded binary string.', 1, 1,
fn (string $a) => base64_decode($a)
));
$env->set('url-encode', new CoreFunc('url-encode', 'Encode special characters in URL.', 1, 1,
fn (string $a) => urlencode($a)
));
$env->set('url-decode', new CoreFunc('url-decode', 'Decode special characters in URL.', 1, 1,
fn (string $a) => urldecode($a)
));
$env->set('utf8-encode', new CoreFunc('utf8-encode', 'Encode ISO-8859-1 string to UTF-8.', 1, 1,
fn (string $a) => utf8_encode($a)
));
$env->set('utf8-decode', new CoreFunc('utf8-decode', 'Decode UTF-8 string to ISO-8859-1.', 1, 1,
fn (string $a) => utf8_decode($a)
));
}
}

View File

@ -142,5 +142,9 @@ class Math implements ILib
return $a;
}
));
$env->set('rand-bytes', new CoreFunc('rand-bytes', 'Generate the number of random bytes as specified by the argument.', 1, 1,
fn (int $length) => random_bytes($length)
));
}
}

View File

@ -25,6 +25,8 @@ class LispFactory
// Register core libraries
(new Lib\Collections())->register($env);
(new Lib\Compare())->register($env);
(new Lib\Crypto())->register($env);
(new Lib\Encoding())->register($env);
if (extension_loaded('json')) {
(new Lib\Json())->register($env);
}