【发布时间】:2019-12-27 01:31:21
【问题描述】:
我正在尝试使用openssl_decrypt 解密字符串。出于某种原因,无论我尝试了什么,它总是返回空。这是我正在使用的一个小功能; 不是生产代码。
PHP 代码
public function Decrypt($string)
{
$password = "somepassword";
$method = "aes-256-cbc";
$hashPassword = hash('sha256', $password);
$iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0);
return openssl_decrypt(base64_decode($string), $method, $hashPassword, OPENSSL_RAW_DATA, $iv);
}
另一方面,加密发生在c# 端,使用Xamarin 进行网络调用。下面是我目前使用的加密功能。
C# 代码
private static readonly byte[] FIELDS_KEY = SHA256.Create().ComputeHash(Encoding.ASCII.GetBytes("PASSWORDHERE"));
private static readonly byte[] FIELDS_IV = new byte[16] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
public static string EncryptString(string plainText)
{
// Instantiate a new Aes object to perform string symmetric encryption
Aes encryptor = Aes.Create();
encryptor.Mode = CipherMode.CBC;
// Set key and IV
byte[] aesKey = new byte[32];
Array.Copy(FIELDS_KEY, 0, aesKey, 0, 32);
encryptor.Key = aesKey;
encryptor.IV = FIELDS_IV;
// Instantiate a new MemoryStream object to contain the encrypted bytes
MemoryStream memoryStream = new MemoryStream();
// Instantiate a new encryptor from our Aes object
ICryptoTransform aesEncryptor = encryptor.CreateEncryptor();
// Instantiate a new CryptoStream object to process the data and write it to the
// memory stream
CryptoStream cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write);
// Convert the plainText string into a byte array
byte[] plainBytes = Encoding.ASCII.GetBytes(plainText);
// Encrypt the input plaintext string
cryptoStream.Write(plainBytes, 0, plainBytes.Length);
// Complete the encryption process
cryptoStream.FlushFinalBlock();
// Convert the encrypted data from a MemoryStream to a byte array
byte[] cipherBytes = memoryStream.ToArray();
// Close both the MemoryStream and the CryptoStream
memoryStream.Close();
cryptoStream.Close();
// Convert the encrypted byte array to a base64 encoded string
string cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);
// Return the encrypted data as a string
return cipherText;
}
老实说,我真的不确定我在这里遗漏了什么,当我检查输入的密码时,检查哈希密码和 IV 似乎都从 c# 函数的加密端结帐。
【问题讨论】:
-
嗯...为什么要使用散列密码来解密?加密没有使用散列密码,是吗?
-
在当前 PHP 代码中,
hash-方法将结果作为十六进制字符串返回。由于openssl_decrypt需要二进制数据,因此该字符串之后必须使用hex2bin进行转换。或者,可以将hash方法中的第三个参数$raw_output设置为TRUE,从而将结果直接作为二进制数据返回。 -
无法重现该问题。代码
https://pastebin.com/JFCHqtLi运行例如在https://repl.it/languages/php_cli -
圣洁抽烟@Topaco 有效!
$hashPassword = hash('sha256', $password, $raw_output = true);$raw_output=true做到了;我刚刚在那里有true!非常感谢您,如果您创建一个答案,我将很高兴接受它,再次感谢! -
记住@Topaco,cmets 可能会消失,但答案是永远的。我们喜欢这里的答案,提示,提示;)
标签: c# php encryption openssl