v1.0.1
AtheraStudio Database
- <?php
- declare(strict_types=1);
-
- namespace Athera;
-
- defined('ATHERA') || exit;
-
- final class Atbde
- {
- public const MAGIC = 'ATBDE';
- public const VERSION = 1;
- public const BLOCK = 1048576;
- public const ITERATIONS = 600000;
- public const MIN_ITERATIONS = 100000;
- public const MAX_ITERATIONS = 10000000;
- public const SQL_MYSQL = 1;
- public const SQL_SQLITE = 2;
- public const SQLITE_DB = 3;
- public const SQL_PGSQL = 4;
-
- private $sink;
- private string $buf = '';
- private int $index = 0;
- private string $header;
- private string $enc;
- private string $prefix;
- private bool $done = false;
-
- public function __construct(string $password, int $type, callable $sink, int $iterations = self::ITERATIONS)
- {
- self::checkPassword($password);
- $salt = random_bytes(16);
- $this->prefix = random_bytes(8);
- $this->header = self::MAGIC . chr(self::VERSION) . "\x01\x01\x01" . chr($type) . "\0\0"
- . pack('N', $iterations) . $salt . $this->prefix . pack('N', self::BLOCK) . str_repeat("\0", 20);
- [$this->enc, $mac] = self::derive($password, $salt, $iterations);
- $this->sink = $sink;
- ($this->sink)($this->header . hash_hmac('sha256', $this->header, $mac, true));
- }
-
- public static function checkPassword(string $password): void
- {
- if (mb_strlen($password) < 12) throw new UserError('A-TBDE password must have at least 12 characters', 400, 'atbde_short');
- }
-
- private static function derive(string $password, string $salt, int $iterations): array
- {
- if (class_exists('Normalizer')) $password = (string)\Normalizer::normalize($password, \Normalizer::FORM_C);
- $k = hash_pbkdf2('sha256', $password, $salt, $iterations, 64, true);
- return [substr($k, 0, 32), substr($k, 32, 32)];
- }
-
- public function write(string $data): void
- {
- if ($this->done) throw new \LogicException('A-TBDE stream closed');
- $this->buf .= $data;
- while (strlen($this->buf) > self::BLOCK) {
- $this->emit(substr($this->buf, 0, self::BLOCK), false);
- $this->buf = substr($this->buf, self::BLOCK);
- }
- }
-
- public function finish(): void
- {
- if ($this->done) return;
- $this->emit($this->buf, true);
- $this->buf = '';
- $this->done = true;
- }
-
- private function emit(string $raw, bool $final): void
- {
- $packed = gzdeflate($raw, 6);
- $aad = $this->header . pack('N', $this->index) . ($final ? "\x01" : "\x00");
- $tag = '';
- $c = openssl_encrypt($packed, 'aes-256-gcm', $this->enc, OPENSSL_RAW_DATA, $this->prefix . pack('N', $this->index), $tag, $aad, 16);
- if ($c === false) throw new \RuntimeException('A-TBDE encryption failed');
- ($this->sink)(pack('N', strlen($c) + 16) . $c . $tag);
- $this->index++;
- }
-
- public static function readHeader($in): array
- {
- $head = self::readExact($in, 96);
- if (strlen($head) < 96 || substr($head, 0, 5) !== self::MAGIC) throw new UserError('Not an A-TBDE file', 400, 'atbde_format');
- if (ord($head[5]) !== self::VERSION || ord($head[6]) !== 1 || ord($head[7]) !== 1) throw new UserError('Unsupported A-TBDE version', 400, 'atbde_version');
- $iter = unpack('N', substr($head, 12, 4))[1];
- if ($iter < self::MIN_ITERATIONS || $iter > self::MAX_ITERATIONS) throw new UserError('Damaged A-TBDE file', 400, 'atbde_damaged');
- return [
- 'header' => substr($head, 0, 64),
- 'check' => substr($head, 64, 32),
- 'compressed' => ord($head[8]) === 1,
- 'type' => ord($head[9]),
- 'iterations' => $iter,
- 'salt' => substr($head, 16, 16),
- 'prefix' => substr($head, 32, 8),
- 'block' => unpack('N', substr($head, 40, 4))[1],
- ];
- }
-
- public static function decrypt($in, callable $out, string $password): int
- {
- $h = self::readHeader($in);
- [$enc, $mac] = self::derive($password, $h['salt'], $h['iterations']);
- if (!hash_equals(hash_hmac('sha256', $h['header'], $mac, true), $h['check'])) throw new UserError('Wrong password', 400, 'atbde_password');
- $limit = min(64 * 1048576, max(65536, $h['block'] * 2 + 1024));
- for ($i = 0; ; $i++) {
- $len = self::readExact($in, 4);
- if ($len === '') throw new UserError('A-TBDE file is truncated', 400, 'atbde_truncated');
- if (strlen($len) !== 4) throw new UserError('Damaged A-TBDE file', 400, 'atbde_damaged');
- $n = unpack('N', $len)[1];
- if ($n < 16 || $n > $limit) throw new UserError('Damaged A-TBDE file', 400, 'atbde_damaged');
- $blob = self::readExact($in, $n);
- if (strlen($blob) !== $n) throw new UserError('A-TBDE file is truncated', 400, 'atbde_truncated');
- $plain = null;
- foreach (["\x00", "\x01"] as $flag) {
- $r = openssl_decrypt(substr($blob, 0, -16), 'aes-256-gcm', $enc, OPENSSL_RAW_DATA, $h['prefix'] . pack('N', $i), substr($blob, -16), $h['header'] . pack('N', $i) . $flag);
- if ($r !== false) { $plain = [$r, $flag === "\x01"]; break; }
- }
- if ($plain === null) throw new UserError('Damaged A-TBDE file', 400, 'atbde_damaged');
- $data = $h['compressed'] ? @gzinflate($plain[0], max(1, $h['block'])) : $plain[0];
- if ($data === false) throw new UserError('Damaged A-TBDE file', 400, 'atbde_damaged');
- if ($data !== '') $out($data);
- if ($plain[1]) {
- if (fread($in, 1) !== '') throw new UserError('Damaged A-TBDE file', 400, 'atbde_damaged');
- return $h['type'];
- }
- }
- }
-
- private static function readExact($in, int $n): string
- {
- $s = '';
- while (strlen($s) < $n && !feof($in)) {
- $c = fread($in, $n - strlen($s));
- if ($c === false || $c === '') break;
- $s .= $c;
- }
- return $s;
- }
- }
-