C# PHP AES 256 CBC Encryption [closed]

余生长醉 提交于 2019-12-31 07:48:06

问题


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.

Here is my C# decrypt function

 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;
    }

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:


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.



来源:https://stackoverflow.com/questions/24372308/c-sharp-php-aes-256-cbc-encryption

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!