【问题标题】:Decrypting byte array with Rijndael - lost Bytes使用 Rijndael 解密字节数组 - 丢失字节
【发布时间】:2018-09-05 04:00:43
【问题描述】:

我正在 .txt 文件中编写一个加密的 (Rijndael) 字节数组。 当我读出来时,我得到一个字节[48]。一旦我解密它,我就会得到一个字节[32]。

为什么我会在这里丢失字节?如果我在控制台中写入结果,它也会在特定点切割。

static void ShowEntries()
{
    string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    path = path + @"\SafePass\";

    byte[] file = File.ReadAllBytes(path + @"\crypt.txt");
    using (MemoryStream memory = new MemoryStream(file))
    {
        using (BinaryReader binary = new BinaryReader(memory))
        {
            byte[] result = binary.ReadBytes(file.Length);
            byte[] plainText = new byte[48];
            plainText = Decrypt(result);
            string SplainText = Converter(plainText);

            Console.WriteLine(SplainText);
        }
    }
}

static string Converter(byte[] data)
{            
    string base64 = Convert.ToBase64String(data);
    return base64;
}

static byte[] Decrypt(byte[] encryptedByte)
{
    {
        string password = @"mykey123"; // Your Key Here

        UnicodeEncoding UE = new UnicodeEncoding();
        byte[] key = UE.GetBytes(password);

        MemoryStream mem = new MemoryStream();

        RijndaelManaged RMCrypto = new RijndaelManaged();

        CryptoStream cs = new CryptoStream(mem,
            RMCrypto.CreateDecryptor(key, key),
            CryptoStreamMode.Write);

        cs.Write(encryptedByte, 0, encryptedByte.Length);

        byte[] cipherText = null;
        cipherText = mem.ToArray();

        cs.Close();
        return cipherText;
    }
}

【问题讨论】:

  • 在 cs.Close() 之前添加 cs.Flush()
  • 使用File.ReadAllTextFile.WriteAllBytes进行加密,使用File.ReadAllBytesFile.WriteAllText进行解密。我也认为BinaryReaderShowEntries 中的MemoryStream 没有用。您已经使用File.ReadAllBytes 读取了字节,只需传递该变量

标签: c#


【解决方案1】:

假设您的输入数据(即您要加密的内容)是 32 字节长,那么加密数据正在被填充,这意味着额外的冗余信息被添加到加密数据中。

In .NET, the default padding mode for symmetrical algorithms like Rijndael 是 PKCS #7。

我认为,如果您查看加密数组中的额外数据,所有额外值将是 16(32 字节输入,下一个块是 48,填充是差异:48-32=16)。

请注意,解密时将删除填充字节,前提是解密时使用与加密相同的填充模式。它不会影响您的数据。

但如果你真的想要,你可以将填充模式设置为无,或MSDN 中提到的其他值之一。

Here's a similar answer 到一个类似的问题,您也可以参考。

【讨论】:

  • 实际上我的问题是我的输入数据是 48 字节长,我没有得到完整的数据解密。读出的 .txt 文件是 48 个字节,但我一解密它,就只剩下 32 个字节了。
  • J€vÆ PA‰8êÅš(/jÓòzÐ' úE©Õ³ì$©Â¹½n™|e6'¨C—`ç)èô~Ì /MЍӻiz
  • 我觉得里面的一些符号会引起问题。
  • 不,我的意思是,你能把你用来加密文件的 C# 代码贴出来吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-06
  • 1970-01-01
  • 2015-11-04
  • 1970-01-01
  • 2016-08-28
  • 1970-01-01
相关资源
最近更新 更多