Files
jongryangje/app/Helpers/pii_encryption_helper.php

73 lines
2.1 KiB
PHP
Raw Permalink Normal View History

<?php
declare(strict_types=1);
/**
* PII(개인정보) 필드 암호화/복호화 헬퍼.
* encryption.key .env에 설정된 경우에만 동작. 키가 없으면 평문 유지(기존 데이터 호환).
*
* 저장 형식: 암호화된 값은 "ENC:" + base64(암호문) 으로 저장. "ENC:" 없으면 평문(기존)으로 간주.
*/
2026-04-08 00:23:21 +09:00
if (! function_exists('pii_encrypt')) {
function pii_encrypt(?string $value): string
{
if ($value === null || $value === '') {
return '';
}
try {
$config = config('Encryption');
if ($config->key === '') {
return $value;
}
$encrypter = service('encrypter');
$encrypted = $encrypter->encrypt($value);
return 'ENC:' . base64_encode($encrypted);
2026-04-08 00:23:21 +09:00
} catch (Throwable $e) {
return $value;
}
}
}
if (! function_exists('pii_decrypt')) {
function pii_decrypt(?string $value): string
{
if ($value === null || $value === '') {
return '';
}
if (strpos($value, 'ENC:') !== 0) {
return $value;
}
try {
$config = config('Encryption');
if ($config->key === '') {
return $value;
}
$encrypter = service('encrypter');
2026-04-08 00:23:21 +09:00
$payload = substr($value, 4);
// 현재 포맷: ENC: + base64(raw ciphertext)
$raw = base64_decode($payload, true);
if ($raw !== false) {
try {
return $encrypter->decrypt($raw);
} catch (Throwable $e) {
// legacy 포맷 재시도
}
}
2026-04-08 00:23:21 +09:00
// 레거시 포맷 호환:
// - ENC: + encrypter 반환값(rawData=false 환경 등) 또는
// - ENC: + 기타 문자열 포맷
return $encrypter->decrypt($payload);
} catch (Throwable $e) {
return $value;
}
}
}
/** 암호화 대상 개인정보 필드 (member 테이블) */
if (! defined('PII_ENCRYPTED_FIELDS')) {
define('PII_ENCRYPTED_FIELDS', ['mb_phone', 'mb_email']);
}