webcron/src/Service/Secret.php

32 lines
1.0 KiB
PHP
Raw Normal View History

2021-04-13 14:44:58 +02:00
<?php
2022-04-27 14:24:48 +02:00
namespace App\Service;
2021-04-13 14:44:58 +02:00
class Secret
{
static function encrypt($plaintext) {
2022-04-27 14:24:48 +02:00
$password = $_ENV['APP_SECRET'];
2021-04-13 14:44:58 +02:00
$method = $_ENV['ENCRYPTION_METHOD'];
$key = hash($_ENV['HASHING_METHOD'], $password, true);
$iv = openssl_random_pseudo_bytes(16);
$ciphertext = openssl_encrypt($plaintext, $method, $key, OPENSSL_RAW_DATA, $iv);
$hash = hash_hmac($_ENV['HASHING_METHOD'], $ciphertext . $iv, $key, true);
2021-04-13 14:44:58 +02:00
return $iv . $hash . $ciphertext;
}
static function decrypt($ivHashCiphertext) {
2022-04-27 14:24:48 +02:00
$password = $_ENV['APP_SECRET'];
2021-04-13 14:44:58 +02:00
$method = $_ENV['ENCRYPTION_METHOD'];
$iv = substr($ivHashCiphertext, 0, 16);
$hash = substr($ivHashCiphertext, 16, 32);
$ciphertext = substr($ivHashCiphertext, 48);
$key = hash($_ENV['HASHING_METHOD'], $password, true);
if (!hash_equals(hash_hmac($_ENV['HASHING_METHOD'], $ciphertext . $iv, $key, true), $hash)) return null;
return openssl_decrypt($ciphertext, $method, $key, OPENSSL_RAW_DATA, $iv);
}
}