63 lines
1.9 KiB
PHP
63 lines
1.9 KiB
PHP
<?php
|
||
// FILE: 02_supportFuncs.php
|
||
// Description: Support and utility functions
|
||
|
||
|
||
function getPasswordList(string $passwordFile, string $key): array {
|
||
if (!file_exists($passwordFile)) return [];
|
||
$raw = file_get_contents($passwordFile);
|
||
|
||
// Plain text mode
|
||
if ($key === "") return json_decode($raw, true) ?: [];
|
||
|
||
// Encrypted mode
|
||
$json = decryptData($raw, $key);
|
||
return $json === false ? [] : (json_decode($json, true) ?: []);
|
||
}
|
||
|
||
function savePasswordList(string $passwordFile, array $data, string $key): void {
|
||
$json = json_encode($data, JSON_PRETTY_PRINT);
|
||
$out = $key === "" ? $json : encryptData($json, $key);
|
||
file_put_contents($passwordFile, $out);
|
||
}
|
||
|
||
/* Encryption helpers – unchanged except key now fixed */
|
||
function encryptData(string $plain, string $key): string {
|
||
$m = "aes-256-cbc";
|
||
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($m));
|
||
$enc= openssl_encrypt($plain, $m, $key, 0, $iv);
|
||
return base64_encode($iv . $enc);
|
||
}
|
||
|
||
function decryptData(string $cipherB64, string $key): string|false {
|
||
$m = "aes-256-cbc";
|
||
$bin= base64_decode($cipherB64, true);
|
||
if ($bin === false) return false;
|
||
$ivLen = openssl_cipher_iv_length($m);
|
||
$iv = substr($bin, 0, $ivLen);
|
||
$enc = substr($bin, $ivLen);
|
||
return openssl_decrypt($enc, $m, $key, 0, $iv);
|
||
}
|
||
|
||
function generatePassword(int $len = 14): string {
|
||
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+';
|
||
return substr(str_shuffle(str_repeat($chars, (int)ceil($len / strlen($chars)))), 0, $len);
|
||
}
|
||
|
||
|
||
/**
|
||
* Return the current 6-digit TOTP for a given base32 secret.
|
||
* On error (empty or invalid secret) returns ''.
|
||
*/
|
||
function currentOtpCode(string $secret): string
|
||
{
|
||
if ($secret === '') return '';
|
||
try {
|
||
$totp = OTPHP\TOTP::create($secret);
|
||
return $totp->now(); // 6-digit string
|
||
} catch (\Throwable $e) {
|
||
return '';
|
||
}
|
||
}
|
||
?>
|