C#PHP AES 256 CBC加密 [英] C# PHP AES 256 CBC Encryption
问题描述
你好,我正在尝试使用PHP和AES 256 CBC模式对服务器上的文件/字符串进行加密,
由于字符串以'ending0'结尾,我可以轻松地从其中删除填充AES的填充,但是我无法使用文件,因为其中一些文件包含空字节。在发送数据之前,我将其编码为base64字符串。
Hello I'm trying to encrypt files/strings on my server using PHP and AES 256 CBC mode, Because of strings ending with '\0' I can easly remove padding from them which AES adds, but with files I cannot because some of them contain null bytes. Before I send my data i encode it as base64 string.
这是我的C#解密函数
internal static byte[] __AES_DECRYPT(byte[] input, string _key, string _iv)
{
var myRijndael = new RijndaelManaged()
{
Padding = PaddingMode.Zeros,
Mode = CipherMode.CBC,
KeySize = 256,
BlockSize = 256
};
byte[] key = Encoding.ASCII.GetBytes(_key);
byte[] iv = Encoding.ASCII.GetBytes(_iv);
var decryptor = myRijndael.CreateDecryptor(key, iv);
var sEncrypted = input;
var fromEncrypt = new byte[sEncrypted.Length];
var msDecrypt = new MemoryStream(sEncrypted);
var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
return fromEncrypt;
}
此功能也适用于字符串和字节。
我相信PHP加密功能对文件来说是错误的,但对字符串有效。
This function works fine for strings and bytes too. I believe PHP encrypt function is wrong for files but works for strings.
function encrypt($str)
{
$key = 'keygoeshere';
$iv = "ivgoeshere";
$str =mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $str, MCRYPT_MODE_CBC, $iv);
//$str = str_replace("\0","",$str); this works for strings but not files.
return base64_encode($str);
}
推荐答案
如果您不想要要更改为另一种填充形式,只需在文件内容的末尾附加一个1字节,然后在解密时删除所有尾随的null,然后删除附加的1个字节。您不会意外删除属于该文件的任何0个字节。
If you don't want to change to another form of padding, just append a single 1 byte to the end of the file contents, and on decryption, after removing any trailing nulls, then remove the appended 1 byte. You won't accidently remove any 0 bytes that belong to the file.
这篇关于C#PHP AES 256 CBC加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!