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

+ Recent posts