我一直在尝试在 PHP 中使用以下 c# 代码的类似模式。我花了 7 天时间,试图在我的 EPin API 应用程序中实现一个简单的加密通信。问题是,来自 php 脚本的响应给了我空白
public static string AESDecryptText(string input, string key)
{
// Get the bytes of the string
byte[] bytesToBeDecrypted = Convert.FromBase64String(input);
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
keyBytes = SHA256.Create().ComputeHash(keyBytes);
byte[] bytesDecrypted = AESDecrypt(bytesToBeDecrypted, keyBytes);
string result = Encoding.UTF8.GetString(bytesDecrypted);
return result;
}
public static byte[] AESDecrypt(byte[] bytesToBeDecrypted, byte[] keyBytes)
{
byte[] decryptedBytes = null;
// Set your salt here, change it to meet your flavor:
// The salt bytes must be at least 8 bytes.
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(keyBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
cs.Close();
}
decryptedBytes = ms.ToArray();
}
}
return decryptedBytes;
}
来自其他线程的我的 PHP 代码..
function DecryptString($content, $password =
'4J2lh3Lz4q6ACo16VrL1oLDnh3k7G1KaXliUPVPV8o0='){
$password = mb_convert_encoding($password, "utf-16le");
$padding = 32 - (strlen($password) % 32);
$password .= str_repeat("\0", $padding);
$iv = substr($password, 0, 8);
$data = base64_decode($content);
$decrypted = openssl_decrypt($data, 'AES-256-CBC', $password,
OPENSSL_RAW_DATA, $iv);
$decrypted = mb_convert_encoding($decrypted, "utf-8", "utf-16le");
return $decrypted;
}
function decryption(){
$password = "4J2lh3Lz4q6ACo16VrL1oLDnh3k7G1KaXliUPVPV8o0=";
$content = "wKamNpehMEqJQ4NcUueNuXq1PbupsxwEvwcJ0CeI+8Q=";
echo $this->DecryptString($content, $password);
}
每次我打印,显示空白。请在这方面提供帮助
最佳答案
在您的 C# 代码中,您使用 SHA256
对密码进行哈希处理,并使用 Rfc2898DeriveBytes
创建 key 和 IV。 PHP 类似函数是 hash
(使用 sha256)和 hash_pbkdf2
.
与 C# AESDecryptText
方法等效的 PHP:
function AESDecryptText($content, $password){
$password = hash('sha256', $password, true);
$salt = pack("C*",1,2,3,4,5,6,7,8);
$bytes = hash_pbkdf2("sha1", $password, $salt, 1000, 48, true);
$key = substr($bytes, 0, 32);
$iv = substr($bytes, 32, 16);
return openssl_decrypt($content, 'AES-256-CBC', $key, 0, $iv);
}
一些注意事项:
- 每个密码的盐值应该是唯一的。
- IV应该是随机的,与密码或 key 无关。
你可以使用openssl_random_pseudo_bytes
创建随机字节。 - Salt 和 IV 不必是 secret 的,您可以将它们存储在密文旁边。
- 您应该考虑使用 HMAC 来验证您的密文。
你可以使用hash_hmac
为此目的。
关于c# - 从 C# 代码中查找 PHP 中的相似代码(AES-256 解密),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46784308/