溫馨提示×

如何在CTF中使用PHP進行加密解密

PHP
小樊
145
2024-08-27 16:00:16
欄目: 編程語言

在CTF(Capture The Flag)中,使用PHP進行加密和解密是一種常見的方法,用于保護數據、驗證用戶身份等

  1. 使用base64加密和解密:

加密:

$plaintext = "Hello, World!";
$encrypted_text = base64_encode($plaintext);
echo $encrypted_text; // 輸出:SGVsbG8sIFdvcmxkIQ==

解密:

$encrypted_text = "SGVsbG8sIFdvcmxkIQ==";
$decrypted_text = base64_decode($encrypted_text);
echo $decrypted_text; // 輸出:Hello, World!
  1. 使用MD5進行哈希:
$plaintext = "Hello, World!";
$hashed_text = md5($plaintext);
echo $hashed_text; // 輸出:65a8e27d8879283831b664bd8b7f0ad4
  1. 使用AES加密和解密:

加密:

function encrypt_aes($plaintext, $key) {
    $ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
    $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);
    return base64_encode($iv.$hmac.$ciphertext_raw);
}

$plaintext = "Hello, World!";
$key = "your_secret_key";
$encrypted_text = encrypt_aes($plaintext, $key);
echo $encrypted_text;

解密:

function decrypt_aes($encrypted_text, $key) {
    $c = base64_decode($encrypted_text);
    $ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
    $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))
        return $original_plaintext;
    else
        return null;
}

$encrypted_text = "your_encrypted_text";
$key = "your_secret_key";
$decrypted_text = decrypt_aes($encrypted_text, $key);
echo $decrypted_text;

請注意,這些示例僅用于演示目的。在實際應用中,您需要根據CTF的具體要求和場景選擇合適的加密和解密方法。同時,確保密鑰和其他敏感信息的安全,不要將其暴露在代碼中。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女