gpt4 book ai didi

C# <-> PHP 动态 AES key 交换

转载 作者:搜寻专家 更新时间:2023-10-31 21:08:32 25 4
gpt4 key购买 nike

我想制作一个在 C# 和 PHP 之间进行动态 key 交换的加密通信系统。目前,我有一个有效的加密/解密 PHP <-> PHP 和 C# <-> C#,但由于某种原因它无法正常工作 PHP <-> C#。问题在于,C# 代码解密的字符串生成的输出比 PHP 预期的要长,但将输出视为简单字符串时,数据是相同的。例如,从 C# 发送到 PHP 的字符串“daa”,解密长度为 28,这不是应该的长度。从 PHP 发送到 C# 的字符串也是如此,我收到编译器错误 ArgumentException: length

C#代码:

public static string EncryptTest(string input)
{
string key = "256 bit key (32 char)";

input = Md5Sum(input).Substring(0, 4) + input;

var encoding = new UTF8Encoding();
var Key = encoding.GetBytes(key);
byte[] encrypted;
byte[] result;

using (var rj = new RijndaelManaged())
{
try
{
rj.Padding = PaddingMode.PKCS7;
rj.Mode = CipherMode.CBC;
rj.KeySize = 256;
rj.BlockSize = 256;
rj.Key = Key;
rj.GenerateIV();

using (ICryptoTransform encryptor = rj.CreateEncryptor())
{
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter writer = new StreamWriter(cs))
{
writer.Write(input);
}
}

encrypted = ms.ToArray();
result = new byte[rj.BlockSize / 8 + encrypted.Length];

// Result is built as: IV (plain text) + Encrypted(data)
Array.Copy(rj.IV, result, rj.BlockSize / 8);
Array.Copy(encrypted, 0, result, rj.BlockSize / 8, encrypted.Length);
}
}
}
finally
{
rj.Clear();
}
}
return Convert.ToBase64String(result);
}

public static string DecryptTest(string input)
{
string key = "256 bit key (32 char)";

byte[] data = Convert.FromBase64String(input);

if (data.Length < 32)
return null;

var encoding = new UTF8Encoding();
var Key = encoding.GetBytes(key);

using (RijndaelManaged aes = new RijndaelManaged())
{
aes.Padding = PaddingMode.PKCS7;
aes.Mode = CipherMode.CBC;
aes.KeySize = 256;
aes.BlockSize = 256;
aes.Key = Key;

// Extract the IV from the data first.
byte[] iv = new byte[aes.BlockSize / 8];
Array.Copy(data, iv, iv.Length);
aes.IV = iv;

// The remainder of the data is the encrypted data we care about.
byte[] encryptedData = new byte[data.Length - iv.Length];
Array.Copy(data, iv.Length, encryptedData, 0, encryptedData.Length);

using (ICryptoTransform decryptor = aes.CreateDecryptor())
{
using (MemoryStream ms = new MemoryStream(encryptedData))
{
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(cs))
{
string output = reader.ReadToEnd();

if (output.Length < 4)
return null;

string dataHash = output.Substring(0, 4);
string dataInput = output.Substring(4);
string dataInputHash = Md5Sum(dataInput).Substring(0, 4);

if (dataHash != dataInputHash)
return null;

return dataInput;
}
}
}
}
}
}

private static string Md5Sum(string strToEncrypt)
{
UTF8Encoding ue = new UTF8Encoding();
byte[] bytes = ue.GetBytes(strToEncrypt);

MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] hashBytes = md5.ComputeHash(bytes);

string hashString = "";

for (int i = 0; i < hashBytes.Length; i++)
{
hashString += Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
}

return hashString.PadLeft(32, '0');
}

PHP代码:

$key = "256 bit key (32 char)";

function iv()
{
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
return mcrypt_create_iv($iv_size, MCRYPT_RAND);
}
function encrypt($data, $key32)
{
# Prepend 4-chars data hash to the data itself for validation after decryption
$data = substr(md5($data), 0, 4).$data;
# Prepend $iv to decrypted data
$iv = iv();
$enc = $iv.mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key32, $data, MCRYPT_MODE_CBC, $iv);
return base64_encode($enc);
}
function decrypt($data, $key32)
{
$data = base64_decode($data);
if ($data === false || strlen($data) < 32)
return null;
$iv = substr($data, 0, 32);
$encrypted = substr($data, 32);
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key32, $encrypted, MCRYPT_MODE_CBC, $iv), "\0");
if ($decrypted === false || is_null($decrypted) || strlen($decrypted) < 4)
return null;
$dataHash = substr($decrypted, 0, 4);
$data = substr($decrypted, 4);
if (substr(md5($data), 0, 4) !== $dataHash)
return null; // it breaks here, md5 sum is not correct because of the length
return $data;
}

最佳答案

PHP/mcrypt 不使用 PKCS#7 填充,它使用 0..n 字节的零填充,其中 n 是 block 大小。


要在加密前用 PKCS#7 填充明文,请使用:

$pad = $blockSize - (strlen($data) % $blockSize);
$pdata = $data . str_repeat(chr($pad), $pad);

解密后要取消填充明文,只需执行:

$pad = ord($pdata[strlen($pdata) - 1]);
$data = substr($pdata, 0, strlen($pdata) - $pad);

PKCS#7 现在是填充的临时标准。零填充是不确定的;如果明文本身以零结尾,它可能会改变明文。

关于C# <-> PHP 动态 AES key 交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27588629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com