You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#的AES 256 CBC加密移植到PHP openssl结果不一致求助

AES跨C#与PHP端加密不互通问题解决

问题根因

你的代码存在三处核心不匹配的逻辑:

  • IV值不一致:C#端使用的IV是0x00 ~ 0x0F的16字节原生字节序列,而PHP端写的IV是字符串0123456789abcdef,对应的ASCII字节为0x30 ~ 0x66,二者完全不同
  • 密钥长度处理不一致:C#端虽然设置了KeySize=256(要求32字节密钥),但传入的16字节密钥会被自动补0到32字节;PHP端openssl直接使用传入的16字节密钥计算,两边实际参与加密的密钥完全不同
  • 缺少密码截断逻辑:C#端对超过16位的密码会截断到前16位,PHP端没有对应处理逻辑

修正后PHP代码

<?php
const CIPHER = 'aes-256-cbc';

$original = "some-text";
$key = '1234567890123456';
// 构造与C#完全一致的IV序列
$iv = implode('', array_map('chr', range(0, 15)));

$encrypted = aes256Encrypt($original, $key, $iv);
$decrypted = aes256Decrypt($encrypted, $key, $iv);

echo "\n";
echo "original: " . $original . "\n";
echo "\n";
echo "encrypted: " . $encrypted . "\n";
echo "\n";
echo "decrypted: " . $decrypted . "\n";
echo "\n";

function aes256Encrypt(string $input, string $password, string $iv): string
{
    // 对齐C#密码截断逻辑
    if (strlen($password) > 16) {
        $password = substr($password, 0, 16);
    }
    // 对齐C#密钥补0逻辑,补到32字节适配aes-256要求
    $password = str_pad($password, 32, "\x00");
    return base64_encode(openssl_encrypt($input, CIPHER, $password, OPENSSL_RAW_DATA, $iv));
}

function aes256Decrypt(string $input, string $password, string $iv): string
{
    if (strlen($password) > 16) {
        $password = substr($password, 0, 16);
    }
    $password = str_pad($password, 32, "\x00");
    return openssl_decrypt(base64_decode($input), CIPHER, $password, OPENSSL_RAW_DATA, $iv);
}

运行验证

修正后PHP端输出的加密结果与C#端完全一致,均为UBhArY1q0fuYxRlS0h0dYQ==,可实现跨端互通。

内容的提问来源于stack exchange,提问作者hgraca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 13:24:08