dongying7847 2014-06-23 17:55
浏览 173

C#PHP AES 256 CBC加密[关闭]

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条回答 默认 最新

  • doushun9875 2014-06-23 20:08
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致