728x90
개인정보 보안이 강화 되다 보니 db 에 데이터를 암호화 해서 보관해야 하는 경우가 있다. md5 는 복호화로 암호를 풀수는 없기 때문에 그럴때는 AES (Advanced Encryption Standard)를 사용 하는 것이 좋다.
<?php
function encrypt($plaintext, $key) {
$cipher = "aes-256-cbc"; // 암호화 알고리즘 및 모드
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, $key, true); // HMAC을 생성하여 데이터 무결성 보장
return base64_encode($iv . $hmac . $ciphertext_raw);
}
function decrypt($ciphertext, $key) {
$cipher = "aes-256-cbc";
$c = base64_decode($ciphertext);
$ivlen = openssl_cipher_iv_length($cipher);
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, $sha2len = 32);
$ciphertext_raw = substr($c, $ivlen + $sha2len);
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, $key, true);
if (hash_equals($hmac, $calcmac)) { // HMAC 일치 확인
return $original_plaintext;
}
return false; // HMAC이 일치하지 않으면 복호화 실패
}
// 사용 예제
$key = "my_secret_key"; // 암호화에 사용할 키
$plaintext = "Hello, world!"; // 암호화할 문자열
// 암호화
$ciphertext = encrypt($plaintext, $key);
echo "암호화된 문자열: " . $ciphertext . "\n";
// 복호화
$decrypted_text = decrypt($ciphertext, $key);
if ($decrypted_text !== false) {
echo "복호화된 문자열: " . $decrypted_text . "\n";
} else {
echo "복호화 실패\n";
}
?>
728x90
'PHP' 카테고리의 다른 글
spl_autoload_register 함수 (0) | 2024.03.18 |
---|---|
PHP Numeric and String Conversion with Decimal Precision (0) | 2024.03.15 |
php 에서 sass 파일 css 로 컴파일 하기 (0) | 2024.03.13 |
php form 태그 다중 checkbox 존재여부 체크 isset (implode, explode) (0) | 2024.01.25 |
php 암호화 복호화 AES (Advanced Encryption Standard) 예제 (0) | 2024.01.24 |