<?php

function getPassphrase() {
    $passphrase = trim(shell_exec("/usr/bin/hostname")).trim(shell_exec("/usr/bin/cat /sys/class/net/*/address"));
    return $passphrase;
}

function ensureKey() {
    if (file_exists("/var/www/usergen/secret/private.key") && file_exists("/var/www/usergen/secret/public.key")) {
        return;
    }
    $passphrase = getPassphrase();
    $config = array(
        "digest_alg" => "sha256",
        "private_key_bits" => 4096,
        "private_key_type" => OPENSSL_KEYTYPE_RSA,
        "encrypt_key" => true,
        "encrypt_key_cipher" => OPENSSL_CIPHER_AES_256_CBC
    );
    $res = openssl_pkey_new($config);
    openssl_pkey_export($res, $privkey, $passphrase);
    $oldMask = umask(0007);
    file_put_contents("/var/www/usergen/secret/private.key", $privkey);
    $pubkey = openssl_pkey_get_details($res);
    umask($oldMask);
    file_put_contents("/var/www/usergen/secret/public.key", $pubkey["key"]);
}

function getPublic() {
    ensureKey();
    $public = file_get_contents("/var/www/usergen/secret/public.key");
    return $public;
}

function getFingerprint() {
    ensureKey();
    $fingerprint = shell_exec("/usr/bin/openssl pkey -pubin -in /var/www/usergen/secret/public.key -outform DER | /usr/bin/openssl dgst -sha256 -c | /usr/bin/sed -e 's/^.* //' | /usr/bin/sed -e 's/://g'");
    return $fingerprint;
}

function encrypt($input){
    // Encrypt with public key
    ensureKey();
    $public = getPublic();
    $public = openssl_get_publickey($public);
    openssl_public_encrypt($input, $encrypted, $public);
    return base64_encode($encrypted);
}

function decrypt($input){
    // Decrypt with private key
    ensureKey();
    openssl_private_decrypt(
        base64_decode($input),
        $decrypted,
        openssl_get_privatekey(
            file_get_contents("/var/www/usergen/secret/private.key"),
            getPassphrase()
        )
    );
    return $decrypted;
}

?>
