加密写入:
// 生成随机 IV
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('AES-256-CBC'));
// 加密图片数据
$encrypted_image1_data = base64_encode(openssl_encrypt(file_get_contents($image1), 'AES-256-CBC', $web_site_key, 0, $iv));
$encrypted_image2_data = base64_encode(openssl_encrypt(file_get_contents($image2), 'AES-256-CBC', $web_site_key, 0, $iv));
// 准备 SQL 语句
$stmt = $conn->prepare("INSERT INTO encrypted_images (image1_data, image2_data, phone_number, iv,uid) VALUES (?, ?, ?, ?,?)");
// 绑定参数并执行 SQL 语句
$stmt->bindParam(1, $encrypted_image1_data);
$stmt->bindParam(2, $encrypted_image2_data);
$stmt->bindParam(3, $phone_number);
$iv_base64 = base64_encode($iv);
$stmt->bindParam(4, $iv_base64);
$stmt->bindParam(5, $uid);
try {
if ($stmt->execute()) {
$array = array(
"code" => 200,
"msg" => "提交成功"
);
$apidata = json_encode($array);
echo $apidata;
} else {
throw new Exception("插入失败");
}
} catch (Exception $e) {
$array = array(
"code" => 400,
"msg" => $e->getMessage()
);
$apidata = json_encode($array);
echo $apidata;
} finally {
exit;
}
解密读取:
// 获取需要解密的记录
$stmt = $conn->prepare("SELECT phone_number, image1_data, image2_data, iv FROM encrypted_images WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// 解密图像数据
$iv = base64_decode($row['iv']);
$decrypted_image1_data = openssl_decrypt(base64_decode($row['image1_data']), 'AES-256-CBC', $web_site_key, 0, $iv);
$decrypted_image2_data = openssl_decrypt(base64_decode($row['image2_data']), 'AES-256-CBC', $web_site_key, 0, $iv);
// 可以将解密后的图像数据保存为文件或显示在页面上
// file_put_contents('decrypted_image1.jpg', $decrypted_image1_data);
// file_put_contents('decrypted_image2.jpg', $decrypted_image2_data);
// 或者以base64的格式返回
$array = array(
"code" => 200,
"phone" => $row['phone_number'],
"img1" => base64_encode($decrypted_image1_data),
"img2" => base64_encode($decrypted_image1_data)
);
$apidata = json_encode($array);
echo $apidata;
exit;
感谢您的来访,获取更多精彩文章请收藏本站。
© 版权声明
THE END
暂无评论内容