gpt4 book ai didi

c# - 将 c# Rijndael 函数转换为 php 函数

转载 作者:可可西里 更新时间:2023-10-31 23:49:42 26 4
gpt4 key购买 nike

我正在尝试将 C# 函数转换为 PHP。

这是 C# 函数:

    public string Encrypt(string Value)
{
string RetVal = "";
if(Value != string.Empty && Value != null)
{
MemoryStream Buffer = new MemoryStream();
RijndaelManaged RijndaelManaged = new RijndaelManaged();
UnicodeEncoding UnicodeEncoder = new UnicodeEncoding();

byte[] KeyArray = new Byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
byte[] IVArray = new Byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
try
{
byte[] ValueBytes = UnicodeEncoder.GetBytes(Value);

CryptoStream EncryptStream = new CryptoStream(Buffer,
RijndaelManaged.CreateEncryptor(KeyArray, IVArray),
CryptoStreamMode.Write);

EncryptStream.Write(ValueBytes, 0, ValueBytes.Length);
EncryptStream.FlushFinalBlock();

// Base64 encode the encrypted data
RetVal = Convert.ToBase64String(Buffer.ToArray());
}
catch
{
throw;
}
}

return RetVal;
}

这是我在 PHP 中的尝试:

function EncryptString ($cleartext) 
{

$cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
$key128 = '111111111111111111111111111';
$iv = '111111111111111111111111111';

if (mcrypt_generic_init($cipher, $key128, $iv) != -1) //Parameter iv will be ignored in ECB mode
{
$cipherText = mcrypt_generic($cipher,$cleartext );
mcrypt_generic_deinit($cipher);
$encrypted = (bin2hex($cipherText));
return base64_encode($encrypted);
}
}

目前,当我使用这两个函数对测试短语“test”进行编码时,会得到不同的值。看起来 PHP 版本采用字符串作为 $key$iv 值,而 C# 版本采用字节数组。

如何修改我的 PHP 函数以模仿 C# 函数?

[edit] c# 函数是第 3 方的,我无权更改它;我需要用 PHP 编写等效的代码,以相同的方式对给定的字符串进行编码

最佳答案

查看 RijndaelManaged 文档并复制:

  • 加密模式(cbc)
  • block 大小
  • 填充模式(pkcs#7)

请注意,您可以从其他地方检索填充。

现在确保您对两侧使用完全相同的输入。您可以通过以十六进制值打印出 key 、IV 和纯文本来执行此操作。 key 大小和 IV 大小应该是算法所需的确切位数。要获得相同的纯文本,您需要使用相同的

最后您需要相同的密文编码,但看起来您已经涵盖了这一点。

关于c# - 将 c# Rijndael 函数转换为 php 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11195534/

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