728x90
<?php
function evpKDF($password, $salt, $keySize = 8, $ivSize = 4, $iterations = 1, $hashAlgorithm = "md5") {
$targetKeySize = $keySize + $ivSize;
$derivedBytes = "";
$numberOfDerivedWords = 0;
$block = NULL;
$hasher = hash_init($hashAlgorithm);
while ($numberOfDerivedWords < $targetKeySize) {
if ($block != NULL) {
hash_update($hasher, $block);
}
hash_update($hasher, $password);
hash_update($hasher, $salt);
$block = hash_final($hasher, TRUE);
$hasher = hash_init($hashAlgorithm);
// Iterations
for ($i = 1; $i < $iterations; $i++) {
hash_update($hasher, $block);
$block = hash_final($hasher, TRUE);
$hasher = hash_init($hashAlgorithm);
}
$derivedBytes .= substr($block, 0, min(strlen($block), ($targetKeySize - $numberOfDerivedWords) * 4));
$numberOfDerivedWords += strlen($block)/4;
}
return array(
"key" => substr($derivedBytes, 0, $keySize * 4),
"iv" => substr($derivedBytes, $keySize * 4, $ivSize * 4)
);
}
function decrypt($ciphertext, $password) {
$ciphertext = base64_decode($ciphertext);
if (substr($ciphertext, 0, 8) != "Salted__") {
return false;
}
$salt = substr($ciphertext, 8, 8);
$keyAndIV = evpKDF($password, $salt);
$decryptPassword = openssl_decrypt(
substr($ciphertext, 16),
"aes-256-cbc",
$keyAndIV["key"],
OPENSSL_RAW_DATA, // base64 was already decoded
$keyAndIV["iv"]);
return $decryptPassword;
}
$key = "secret phrase";
$strg = $_POST['l'];
$rawText = decrypt($strg, $key);
echo "decrypt: " . $rawText;
?>
function encrypt($message, $password) {
// Generate random salt
$salt = openssl_random_pseudo_bytes(8);
// Derive key and IV using the password and salt
$keyAndIV = evpKDF($password, $salt);
// Encrypt the message using AES-256-CBC and the derived key and IV
$encrypted = openssl_encrypt(
$message,
"aes-256-cbc",
$keyAndIV["key"],
OPENSSL_RAW_DATA,
$keyAndIV["iv"]
);
// Prepend the "Salted__" header and the salt to the encrypted message
$result = "Salted__" . $salt . $encrypted;
// Base64-encode the result and return it
return base64_encode($result);
}
728x90
'자료' 카테고리의 다른 글
Mega 할당량초과 무시 다운로드 방법 프로그램 공유 (2) | 2023.07.17 |
---|---|
네이버 로그인 소스코드 (0) | 2023.04.06 |
JS,PHP CryptoJS (0) | 2023.03.23 |
winhttp.IWinHttpRequest::Option 속성 (1) | 2022.11.21 |
iTunes 자동 백업을 비활성화하는 방법 (0) | 2022.11.04 |