FHM31052601IBL - implementasi enkripsi PII pasien dan data medis (UU PDP)

- Tambah .env loader di index.php untuk IBL_ENCRYPT_KEY dan IBL_ENCRYPT_SEARCH_KEY
- Library Ibl_encryptor: AES-256-GCM encrypt/decrypt + trigram blind index untuk partial search
- SQL migration: tambah kolom _enc dan _bidx di 16 tabel (m_patient, m_patientaddress, hasil lab, log)
- Script backup_pdp_tables.sh: backup tabel terdampak sebelum migrasi
- Script migrate_encrypt_patient.php: enkripsi batch 178K data PII pasien
- Script migrate_encrypt_results.php: enkripsi data medis hasil lab dan log
- Patient.php: search via trigram blind index, add_new/edit enkripsi sebelum save

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
sas.fajri
2026-05-31 14:07:42 +07:00
parent cf8ef0e590
commit c410d7bbd9
9 changed files with 1858 additions and 133 deletions

View File

@@ -28,6 +28,7 @@ class Patient extends MY_Controller
{
parent::__construct();
$this->db_smartone = $this->load->database("onedev", true);
$this->load->library('ibl_encryptor');
}
function _add_address(&$pat) {
if (count($pat) == "0") {
@@ -76,113 +77,149 @@ class Patient extends MY_Controller
{
$prm = $this->sys_input;
$max_rst = 100;
$tot_count =0;
$number_limit = 10;
$number_offset = (!isset($prm['current_page'])?1:$prm['current_page'] - 1) * $number_limit ;
$number_limit = 10;
$number_offset = (!isset($prm['current_page']) ? 1 : $prm['current_page'] - 1) * $number_limit;
$q = [
'noreg' => "",
'name' => '',
'hp' => '',
'dob' => '',
'address' => ''
];
$where_noreg = '';
$where_name = '';
$where_hp = '';
$where_dob = '';
$where_addr = "AND M_PatientAddressNote = 'Utama'";
$search_address = '';
if (!empty($prm['noreg'])) {
$noreg = $this->db_smartone->escape_like_str($prm['noreg']);
$where_noreg = "AND M_PatientNoReg LIKE '%{$noreg}%'";
}
if ($prm['noreg'] != '')
$q['noreg'] = "AND M_PatientNoReg like '%{$prm['noreg']}%'";
if ($prm['search'] != '')
{
if (!empty($prm['search'])) {
$e = explode('+', $prm['search']);
if (isset($e[0])){
$e[0] = str_replace("'", "\\'", $e[0]);
$q['name'] = "AND M_PatientName LIKE '%{$e[0]}%'";
}
if (isset($e[1]))
$q['hp'] = "AND ((M_PatientHP LIKE '%{$e[1]}%' and M_PatientHP IS NOT NULL) OR (M_PatientHP IS NULL AND '{$e[1]}' = ''))";
if (isset($e[2]))
$q['dob'] = "AND ((DATE_FORMAT(M_PatientDOB, '%d-%m-%Y') LIKE '%{$e[2]}%' and M_PatientDOB IS NOT NULL) OR (M_PatientDOB IS NULL AND '{$e[2]}' = ''))";
if (isset($e[3]))
$q['address'] = "AND M_PatientAddressDescription LIKE '%{$e[3]}%'";
// name — trigram blind index (min 3 karakter)
if (!empty($e[0]) && mb_strlen(trim($e[0])) >= 3) {
$toks = $this->ibl_encryptor->query_tokens($e[0]);
$conds = [];
foreach ($toks as $tok) {
$tok_esc = $this->db_smartone->escape_str($tok);
$conds[] = "JSON_CONTAINS(M_PatientName_bidx, '\"$tok_esc\"')";
}
if ($conds) $where_name = 'AND (' . implode(' AND ', $conds) . ')';
}
// hp — trigram blind index
if (!empty($e[1]) && mb_strlen(trim($e[1])) >= 3) {
$toks = $this->ibl_encryptor->query_tokens($e[1]);
$conds = [];
foreach ($toks as $tok) {
$tok_esc = $this->db_smartone->escape_str($tok);
$conds[] = "JSON_CONTAINS(M_PatientHP_bidx, '\"$tok_esc\"')";
}
if ($conds) $where_hp = 'AND (' . implode(' AND ', $conds) . ')';
}
// dob — trigram blind index (format dd-mm-yyyy)
if (!empty($e[2]) && mb_strlen(trim($e[2])) >= 3) {
$toks = $this->ibl_encryptor->query_tokens($e[2]);
$conds = [];
foreach ($toks as $tok) {
$tok_esc = $this->db_smartone->escape_str($tok);
$conds[] = "JSON_CONTAINS(M_PatientDOB_bidx, '\"$tok_esc\"')";
}
if ($conds) $where_dob = 'AND (' . implode(' AND ', $conds) . ')';
}
// address — trigram blind index
if (!empty($e[3]) && mb_strlen(trim($e[3])) >= 3) {
$toks = $this->ibl_encryptor->query_tokens($e[3]);
$conds = [];
foreach ($toks as $tok) {
$tok_esc = $this->db_smartone->escape_str($tok);
$conds[] = "JSON_CONTAINS(M_PatientAddressDescription_bidx, '\"$tok_esc\"')";
}
if ($conds) $where_addr = 'AND (' . implode(' AND ', $conds) . ')';
}
}
if($q['address'] == ''){
$q['address'] = "AND M_PatientAddressNote = 'Utama'";
}
$sql = "SELECT 'N' divider,M_PatientID, M_PatientNoReg,M_PatientEmail,M_PatientPrefix,M_PatientSuffix,
concat(M_TitleName,' ',IFNULL(M_PatientPrefix,''),' ',M_PatientName,' ',IFNULL(M_PatientSuffix,'')) M_PatientName,
M_PatientName M_PatientRealName, M_TitleID, M_TitleName, M_SexID, M_SexName,
M_PatientHP, M_PatientPOB, M_PatientDOB, DATE_FORMAT(M_PatientDOB,'%d-%m-%Y') as dob_ina,
$sql = "SELECT 'N' divider, M_PatientID, M_PatientNoReg, M_PatientPrefix, M_PatientSuffix,
concat(M_TitleName,' ',IFNULL(M_PatientPrefix,''),' ',M_PatientName,' ',IFNULL(M_PatientSuffix,'')) M_PatientNameRaw,
M_TitleID, M_TitleName, M_SexID, M_SexName,
M_PatientDOB,
'' M_PatientAddress,
M_PatientAddressID,
M_PatientAddressDescription, M_PatientM_IdTypeID, M_PatientIDNumber,
M_PatientAddressRegionalCd,
M_PatientAddressLocation,
M_PatientAddressCity,
M_PatientAddressVillage,
M_PatientAddressDistrict,
M_PatientAddressState,
M_PatientAddressCountry,
M_PatientAddressCountryCode,
IFNULL(M_PatientNote, '') M_PatientNote, M_PatientPhoto, IF(M_PatientPhone IS NULL OR M_PatientPhone = '', M_PatientHP, M_PatientPhone) hp,
-- fn_fo_patient_visit(M_PatientID) info,
M_PatientAddressM_KelurahanID M_KelurahanID, 0 M_DistrictID, 0 M_CityID, 0 M_ProvinceID, M_PatientM_ReligionID,
IFNULL(M_ReligionName, '-') M_ReligionName,
M_PatientAddressRegionalCd, M_PatientAddressLocation, M_PatientAddressCity,
M_PatientAddressVillage, M_PatientAddressDistrict, M_PatientAddressState,
M_PatientAddressCountry, M_PatientAddressCountryCode,
M_PatientAddressM_KelurahanID M_KelurahanID, 0 M_DistrictID, 0 M_CityID, 0 M_ProvinceID,
M_PatientM_ReligionID, IFNULL(M_ReligionName, '-') M_ReligionName,
IFNULL(Patient_SignatureUrl, '') image_signature,
M_PatientNote
FROM m_patient
join m_title on M_PatientM_TitleID = M_TitleID
join m_sex on M_PatientM_SexID = M_SexID
join m_patientaddress on M_PatientAddressM_PatientID = M_PatientID and M_PatientAddressIsActive = 'Y' {$q['address']}
left join m_religion on m_patientm_religionid = m_religionid
left join patient_signature on Patient_SignatureM_PatientID = M_PatientID and Patient_SignatureIsActive = 'Y'
where M_PatientIsActive = 'Y'
{$q['noreg']}
{$q['name']}
{$q['hp']}
{$q['dob']}
group by M_PatientID
limit $number_limit offset $number_offset";
//echo $sql;
IFNULL(M_PatientNote, '') M_PatientNote, M_PatientPhoto,
M_PatientM_IdTypeID,
M_PatientName_enc, M_PatientHP_enc, M_PatientDOB_enc,
M_PatientEmail_enc, M_PatientPhone_enc, M_PatientPOB_enc,
M_PatientIDNumber_enc, M_PatientAddressDescription_enc
FROM m_patient
JOIN m_title ON M_PatientM_TitleID = M_TitleID
JOIN m_sex ON M_PatientM_SexID = M_SexID
JOIN m_patientaddress ON M_PatientAddressM_PatientID = M_PatientID
AND M_PatientAddressIsActive = 'Y' {$where_addr}
LEFT JOIN m_religion ON M_PatientM_ReligionID = M_ReligionID
LEFT JOIN patient_signature ON Patient_SignatureM_PatientID = M_PatientID
AND Patient_SignatureIsActive = 'Y'
WHERE M_PatientIsActive = 'Y'
{$where_noreg}
{$where_name}
{$where_hp}
{$where_dob}
GROUP BY M_PatientID
LIMIT {$number_limit} OFFSET {$number_offset}";
$query = $this->db_smartone->query($sql);
if ($query) {
$rows = $query->result_array();
foreach ($rows as $k => $v)
{
$rows[$k]['M_PatientName'] = stripslashes($rows[$k]['M_PatientName']);
$rows[$k]['M_PatientAddress'] = stripslashes($rows[$k]['M_PatientAddressDescription']);
$info = $this->db_smartone->query("SELECT fn_fo_patient_visit(?) info", [$v['M_PatientID']])->row();
$rows[$k]['info'] = json_decode($info->info);
$references = [];
$sql = "SELECT M_ReferenceID, M_ReferenceName
FROM m_patient_reference
join m_reference on M_PatientReferenceM_ReferenceID = M_ReferenceID
WHERE M_PatientReferenceM_PatientID = ? AND M_PatientReferenceIsActive = 'Y'";
$query = $this->db_smartone->query($sql, [$v['M_PatientID']]);
if ($query) {
$references = $query->result_array();
}
$rows[$k]['references'] = $references;
}
$result = array("total" => $tot_page, "records" => $rows, "sql"=> $this->db_smartone->last_query());
$this->sys_ok($result);
}
else {
$this->sys_error_db("m_patient rows",$this->db_smartone);
exit;
if (!$query) {
$this->sys_error_db("m_patient rows", $this->db_smartone);
return;
}
$rows = $query->result_array();
$enc = $this->ibl_encryptor;
foreach ($rows as $k => $v) {
$name = $enc->decrypt($v['M_PatientName_enc']) ?? $v['M_PatientNameRaw'];
$hp = $enc->decrypt($v['M_PatientHP_enc']) ?? '';
$phone = $enc->decrypt($v['M_PatientPhone_enc']) ?? '';
$dob_dec = $enc->decrypt($v['M_PatientDOB_enc']) ?? date('d-m-Y', strtotime($v['M_PatientDOB']));
$addr = $enc->decrypt($v['M_PatientAddressDescription_enc']) ?? '';
$rows[$k]['M_PatientName'] = $name;
$rows[$k]['M_PatientAddress'] = $addr;
$rows[$k]['M_PatientAddressDescription'] = $addr;
$rows[$k]['M_PatientHP'] = $hp;
$rows[$k]['M_PatientEmail'] = $enc->decrypt($v['M_PatientEmail_enc']) ?? '';
$rows[$k]['M_PatientPhone'] = $phone;
$rows[$k]['M_PatientPOB'] = $enc->decrypt($v['M_PatientPOB_enc']) ?? '';
$rows[$k]['M_PatientIDNumber'] = $enc->decrypt($v['M_PatientIDNumber_enc']) ?? '';
$rows[$k]['dob_ina'] = $dob_dec;
$rows[$k]['hp'] = $phone ?: $hp;
// bersihkan kolom _enc dari response
foreach (array_keys($rows[$k]) as $col) {
if (substr($col, -4) === '_enc') unset($rows[$k][$col]);
}
unset($rows[$k]['M_PatientNameRaw'], $rows[$k]['M_PatientDOB']);
$info = $this->db_smartone->query("SELECT fn_fo_patient_visit(?) info", [$v['M_PatientID']])->row();
$rows[$k]['info'] = json_decode($info->info);
$ref_query = $this->db_smartone->query(
"SELECT M_ReferenceID, M_ReferenceName
FROM m_patient_reference
JOIN m_reference ON M_PatientReferenceM_ReferenceID = M_ReferenceID
WHERE M_PatientReferenceM_PatientID = ? AND M_PatientReferenceIsActive = 'Y'",
[$v['M_PatientID']]
);
$rows[$k]['references'] = $ref_query ? $ref_query->result_array() : [];
}
$this->sys_ok(["total" => 0, "records" => $rows]);
}
@@ -199,24 +236,35 @@ class Patient extends MY_Controller
$M_IdTypeID = $prm['M_PatientM_IdTypeID'];
}
$patient_name = str_replace("'", "\\'", $prm['M_PatientName']);
$dob_str = date('d-m-Y', strtotime($prm['M_PatientDOB']));
$ptn = [
'M_PatientName' => $patient_name,
'M_PatientM_TitleID' => $prm['M_PatientM_TitleID'],
'M_PatientPrefix' => $prm['M_PatientPrefix'],
'M_PatientSuffix' => $prm['M_PatientSuffix'],
'M_PatientM_SexID' => $prm['M_PatientM_SexID'],
'M_PatientM_ReligionID' => $prm['M_PatientM_ReligionID'],
'M_PatientDOB' => $prm['M_PatientDOB'],
'M_PatientPOB' => $prm['M_PatientPOB'],
'M_PatientHP' => $prm['M_PatientHP'],
'M_PatientPhone' => $prm['M_PatientPhone'],
'M_PatientEmail' => $prm['M_PatientEmail'],
'M_PatientM_IdTypeID' => $M_IdTypeID ,
'M_PatientIDNumber' => $prm['M_PatientIDNumber'],
'M_PatientNote' => $prm['M_PatientNote'],
'M_PatientUserID' => $userid,
'M_PatientCreated' => date('Y-m-d H:i:s'),
'M_PatientCreatedUserID' => $userid
'M_PatientName' => $patient_name,
'M_PatientName_enc' => $this->ibl_encryptor->encrypt($patient_name),
'M_PatientName_bidx' => $this->ibl_encryptor->search_bidx($patient_name),
'M_PatientM_TitleID' => $prm['M_PatientM_TitleID'],
'M_PatientPrefix' => $prm['M_PatientPrefix'],
'M_PatientSuffix' => $prm['M_PatientSuffix'],
'M_PatientM_SexID' => $prm['M_PatientM_SexID'],
'M_PatientM_ReligionID' => $prm['M_PatientM_ReligionID'],
'M_PatientDOB' => $prm['M_PatientDOB'],
'M_PatientDOB_enc' => $this->ibl_encryptor->encrypt($dob_str),
'M_PatientDOB_bidx' => $this->ibl_encryptor->search_bidx($dob_str),
'M_PatientPOB' => $prm['M_PatientPOB'],
'M_PatientPOB_enc' => $this->ibl_encryptor->encrypt($prm['M_PatientPOB']),
'M_PatientHP' => $prm['M_PatientHP'],
'M_PatientHP_enc' => $this->ibl_encryptor->encrypt($prm['M_PatientHP']),
'M_PatientHP_bidx' => $this->ibl_encryptor->search_bidx($prm['M_PatientHP']),
'M_PatientPhone' => $prm['M_PatientPhone'],
'M_PatientPhone_enc' => $this->ibl_encryptor->encrypt($prm['M_PatientPhone']),
'M_PatientEmail' => $prm['M_PatientEmail'],
'M_PatientEmail_enc' => $this->ibl_encryptor->encrypt($prm['M_PatientEmail']),
'M_PatientM_IdTypeID' => $M_IdTypeID,
'M_PatientIDNumber' => $prm['M_PatientIDNumber'],
'M_PatientIDNumber_enc' => $this->ibl_encryptor->encrypt($prm['M_PatientIDNumber']),
'M_PatientNote' => $prm['M_PatientNote'],
'M_PatientUserID' => $userid,
'M_PatientCreated' => date('Y-m-d H:i:s'),
'M_PatientCreatedUserID' => $userid
];
$this->db_smartone->insert('m_patient', $ptn);
@@ -235,21 +283,22 @@ class Patient extends MY_Controller
$address_description = str_replace("'", "\\'", $prm['M_PatientAddressDescription']);
// save address
$add = [
'M_PatientAddressM_PatientID' => $id,
'M_PatientAddressDescription' => $address_description,
'M_PatientAddressUserID'=> $userid,
'M_PatientAddressRegionalCd' => $prm['M_PatientAddressRegionalCd'],
'M_PatientAddressLocation' => $prm['M_PatientAddressLocation'],
'M_PatientAddressCity' => $prm['M_PatientAddressCity'],
'M_PatientAddressVillage' => $prm['M_PatientAddressVillage'],
'M_PatientAddressDistrict' => $prm['M_PatientAddressDistrict'],
'M_PatientAddressState' => $prm['M_PatientAddressState'],
'M_PatientAddressCountry' => $prm['M_PatientAddressCountry'],
'M_PatientAddressCountryCode' => $prm['M_PatientAddressCountryCode'],
'M_PatientAddressNote' => isset($prm['M_PatientAddressNote']) ? $prm['M_PatientAddressNote'] : 'Utama',
'M_PatientAddressCreated' => date('Y-m-d H:i:s'),
'M_PatientAddressCreatedUserID' => $userid
'M_PatientAddressM_PatientID' => $id,
'M_PatientAddressDescription' => $address_description,
'M_PatientAddressDescription_enc' => $this->ibl_encryptor->encrypt($address_description),
'M_PatientAddressDescription_bidx' => $this->ibl_encryptor->search_bidx($address_description),
'M_PatientAddressUserID' => $userid,
'M_PatientAddressRegionalCd' => $prm['M_PatientAddressRegionalCd'],
'M_PatientAddressLocation' => $prm['M_PatientAddressLocation'],
'M_PatientAddressCity' => $prm['M_PatientAddressCity'],
'M_PatientAddressVillage' => $prm['M_PatientAddressVillage'],
'M_PatientAddressDistrict' => $prm['M_PatientAddressDistrict'],
'M_PatientAddressState' => $prm['M_PatientAddressState'],
'M_PatientAddressCountry' => $prm['M_PatientAddressCountry'],
'M_PatientAddressCountryCode' => $prm['M_PatientAddressCountryCode'],
'M_PatientAddressNote' => isset($prm['M_PatientAddressNote']) ? $prm['M_PatientAddressNote'] : 'Utama',
'M_PatientAddressCreated' => date('Y-m-d H:i:s'),
'M_PatientAddressCreatedUserID' => $userid
];
$this->db_smartone->insert('m_patientaddress', $add);
$err = $this->db_smartone->error();
@@ -290,23 +339,34 @@ class Patient extends MY_Controller
$prm = $this->sys_input;
$userid = $this->sys_user["M_UserID"];
$prm['M_PatientDOB'] = date('Y-m-d', strtotime($prm['M_PatientDOB']));
$patient_name = str_replace("'", "\\'", $prm['M_PatientName']);
$patient_name = str_replace("'", "\\'", $prm['M_PatientName']);
$dob_str = date('d-m-Y', strtotime($prm['M_PatientDOB']));
$this->db_smartone->set('M_PatientName', $patient_name)
->set('M_PatientName_enc', $this->ibl_encryptor->encrypt($patient_name))
->set('M_PatientName_bidx', $this->ibl_encryptor->search_bidx($patient_name))
->set('M_PatientM_TitleID', $prm['M_PatientM_TitleID'])
->set('M_PatientPrefix', $prm['M_PatientPrefix'])
->set('M_PatientSuffix', $prm['M_PatientSuffix'])
->set('M_PatientSuffix', $prm['M_PatientSuffix'])
->set('M_PatientM_SexID', $prm['M_PatientM_SexID'])
->set('M_PatientM_ReligionID', $prm['M_PatientM_ReligionID'])
->set('M_PatientDOB', $prm['M_PatientDOB'])
->set('M_PatientDOB_enc', $this->ibl_encryptor->encrypt($dob_str))
->set('M_PatientDOB_bidx', $this->ibl_encryptor->search_bidx($dob_str))
->set('M_PatientPOB', $prm['M_PatientPOB'])
->set('M_PatientPOB_enc', $this->ibl_encryptor->encrypt($prm['M_PatientPOB']))
->set('M_PatientHP', $prm['M_PatientHP'])
->set('M_PatientHP_enc', $this->ibl_encryptor->encrypt($prm['M_PatientHP']))
->set('M_PatientHP_bidx', $this->ibl_encryptor->search_bidx($prm['M_PatientHP']))
->set('M_PatientPhone', $prm['M_PatientPhone'])
->set('M_PatientPhone_enc', $this->ibl_encryptor->encrypt($prm['M_PatientPhone']))
->set('M_PatientEmail', $prm['M_PatientEmail'])
->set('M_PatientEmail_enc', $this->ibl_encryptor->encrypt($prm['M_PatientEmail']))
->set('M_PatientM_IdTypeID', $prm['M_PatientM_IdTypeID'])
->set('M_PatientIDNumber', $prm['M_PatientIDNumber'])
->set('M_PatientIDNumber_enc', $this->ibl_encryptor->encrypt($prm['M_PatientIDNumber']))
->set('M_PatientNote', $prm['M_PatientNote'])
->set('M_PatientUserID', $userid)
->set('M_PatientUserID', $userid)
->set('M_PatientLastUpdatedUserID', $userid)
->where('M_PatientID', $prm['id'])
->update('m_patient');
@@ -325,7 +385,7 @@ class Patient extends MY_Controller
$ptn = json_encode($prm);
$id_address = isset($prm['M_PatientAddressID']) && $prm['M_PatientAddressID'] > 0 ? $prm['M_PatientAddressID']:0;
$address_description = str_replace("'", "\\'", $prm['M_PatientAddressDescription']);
$address_description = str_replace("'", "\\'", $prm['M_PatientAddressDescription']);
$this->db_smartone->set('M_PatientAddressRegionalCd', $prm['M_PatientAddressRegionalCd'])
->set('M_PatientAddressLocation', $prm['M_PatientAddressLocation'])
->set('M_PatientAddressCity', $prm['M_PatientAddressCity'])
@@ -334,8 +394,10 @@ class Patient extends MY_Controller
->set('M_PatientAddressState', $prm['M_PatientAddressState'])
->set('M_PatientAddressCountry', $prm['M_PatientAddressCountry'])
->set('M_PatientAddressCountryCode', $prm['M_PatientAddressCountryCode'])
->set('M_PatientAddressDescription', $address_description )
->set('M_PatientAddressUserID', $userid )
->set('M_PatientAddressDescription', $address_description)
->set('M_PatientAddressDescription_enc', $this->ibl_encryptor->encrypt($address_description))
->set('M_PatientAddressDescription_bidx', $this->ibl_encryptor->search_bidx($address_description))
->set('M_PatientAddressUserID', $userid)
->set('M_PatientAddressLastUpdatedUserID', $userid)
->where('M_PatientAddressID', $id_address)
->update('m_patientaddress');

View File

@@ -0,0 +1,87 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Ibl_encryptor
{
private $key;
private $search_key;
private $cipher = 'aes-256-gcm';
private $tag_length = 16;
public function __construct()
{
$passphrase = $_ENV['IBL_ENCRYPT_KEY'] ?? '';
$passphrase_s = $_ENV['IBL_ENCRYPT_SEARCH_KEY'] ?? '';
if ($passphrase === '' || $passphrase_s === '') {
log_message('error', 'Ibl_encryptor: IBL_ENCRYPT_KEY atau IBL_ENCRYPT_SEARCH_KEY kosong di .env');
}
// Derive 32-byte key dari passphrase via SHA-256
$this->key = hash('sha256', $passphrase, true);
$this->search_key = hash('sha256', $passphrase_s, true);
}
// Enkripsi plaintext → base64(iv[12] + tag[16] + ciphertext)
public function encrypt($plaintext)
{
if ($plaintext === null || $plaintext === '') return null;
$iv = random_bytes(12);
$tag = '';
$ct = openssl_encrypt((string)$plaintext, $this->cipher, $this->key, OPENSSL_RAW_DATA, $iv, $tag, '', $this->tag_length);
if ($ct === false) return null;
return base64_encode($iv . $tag . $ct);
}
// Dekripsi base64(iv + tag + ciphertext) → plaintext
public function decrypt($ciphertext)
{
if ($ciphertext === null || $ciphertext === '') return null;
$raw = base64_decode($ciphertext);
if (strlen($raw) < 12 + $this->tag_length) return null;
$iv = substr($raw, 0, 12);
$tag = substr($raw, 12, $this->tag_length);
$ct = substr($raw, 12 + $this->tag_length);
$pt = openssl_decrypt($ct, $this->cipher, $this->key, OPENSSL_RAW_DATA, $iv, $tag);
return $pt === false ? null : $pt;
}
// Hasilkan JSON array trigram token untuk kolom _bidx (partial search)
public function search_bidx($value)
{
if ($value === null || $value === '') return null;
$norm = mb_strtolower(trim((string)$value), 'UTF-8');
$len = mb_strlen($norm, 'UTF-8');
$tokens = [];
if ($len <= 3) {
$tokens[] = $this->_token($norm);
} else {
for ($i = 0; $i <= $len - 3; $i++) {
$tokens[] = $this->_token(mb_substr($norm, $i, 3, 'UTF-8'));
}
}
return json_encode(array_values(array_unique($tokens)));
}
// Hasilkan array trigram token dari query string (untuk WHERE JSON_CONTAINS)
public function query_tokens($value)
{
if ($value === null || $value === '') return [];
$norm = mb_strtolower(trim((string)$value), 'UTF-8');
$len = mb_strlen($norm, 'UTF-8');
$tokens = [];
if ($len <= 3) {
$tokens[] = $this->_token($norm);
} else {
for ($i = 0; $i <= $len - 3; $i++) {
$tokens[] = $this->_token(mb_substr($norm, $i, 3, 'UTF-8'));
}
}
return array_values(array_unique($tokens));
}
private function _token($str)
{
return hash_hmac('sha256', $str, $this->search_key);
}
}