1
0
Fork 0
php-coding/15.work2.api.php

55 lines
1.4 KiB
PHP

<?php
function apply_xor(string $data, string $key) : string
{
$result = '';
$l = strlen($data);
$kl = strlen($key);
for ($i = 0; $i < $l; $i++) {
// 获取当前字符的密钥字符
$keyChar = $key[$i % $kl];
// 对当前字符进行按位异或运算
$substr = $data[$i] ^ $keyChar;
$result .= $substr;
}
return $result;
}
function custom_encrypt(string $raw, string $key) : string
{
return apply_xor($raw, $key);
}
function custom_decrypt(string $encrypted, string $key) : string
{
return apply_xor($encrypted, $key);
}
// 如果请求是 POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 获取 POST 请求的原始数据
$post_data = file_get_contents('php://input');
// 将 JSON 数据解码为 PHP 数组
$data = json_decode($post_data, true);
// 如果有明文
if (isset($data['raw_text'])) {
// 加密
$raw_text = $data['raw_text'];
$key = $data['key'];
$enc_text = custom_encrypt($raw_text, $key);
echo $enc_text;
exit; // 加密完成后终止脚本执行
}
// 如果有密文
if (isset($data['enc_text'])) {
// 解密
$enc_text = $data['enc_text'];
$key = $data['key'];
$raw_text = custom_decrypt($enc_text, $key);
echo $raw_text;
exit; // 解密完成后终止脚本执行
}
}