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
728x90

php 작업 중 db 에 암호화 해서 데이터를 넣어야 할 경우 다시 복호화 해서 사용자 화면에는 보여져야 하는 경우 AES 예제로 암호화 키 값을 넣어서 만들수 있는 예제 이다. 

 

$encryptionKey 값에 임의의 값을 넣어서 사용하면 된다. 

 

<?php

// 암호화 키 (16, 24 또는 32 바이트 여야 함)
$encryptionKey = 'your_secret_key';

// 암호화할 데이터
$dataToEncrypt = 'Hello, this is a secret message!';

// 암호화
$encryptedData = encryptData($dataToEncrypt, $encryptionKey);
echo 'Encrypted Data: ' . $encryptedData . "\n";

// 복호화
$decryptedData = decryptData($encryptedData, $encryptionKey);
echo 'Decrypted Data: ' . $decryptedData . "\n";

function encryptData($data, $key) {
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
    $encrypted = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv);
    return base64_encode($iv . $encrypted);
}

function decryptData($data, $key) {
    $data = base64_decode($data);
    $ivLength = openssl_cipher_iv_length('aes-256-cbc');
    $iv = substr($data, 0, $ivLength);
    $encrypted = substr($data, $ivLength);
    return openssl_decrypt($encrypted, 'aes-256-cbc', $key, 0, $iv);
}

?>

 

함수로 만들어 두면 변환해야 하는 데이터와 key 만 주면 되기에 조금 더 편하게 이용해 볼 수 있다. 

728x90

+ Recent posts