gpt4 book ai didi

c# - Blowfish 无效长度异常

转载 作者:太空宇宙 更新时间:2023-11-03 20:23:23 31 4
gpt4 key购买 nike

我正在用 Blowfish 算法加密我的文件,但我似乎对此一无所知。每当我尝试 Encipher() 时,它都会抛出一个异常,提示“无效长度”。我认为当它用 8 进行模数时​​,长度必须为零,我认为这意味着应该有 8 x 8 block 流来开始加密。我该怎么办?

Blowfish的加密方法:

public void Encipher(byte[] data, int length)
{
uint xl, xr;
if ((length % 8) != 0) <-- Exception Line
throw new Exception("Invalid Length");
for (int i = 0; i < length; i += 8)
{
// Encode the data in 8 byte blocks.
xl = (uint)((data[i] << 24) | (data[i + 1] << 16) | (data[i + 2] << 8) | data[i + 3]);
xr = (uint)((data[i + 4] << 24) | (data[i + 5] << 16) | (data[i + 6] << 8) | data[i + 7]);
Encipher(ref xl, ref xr);
// Now Replace the data.
data[i] = (byte)(xl >> 24);
data[i + 1] = (byte)(xl >> 16);
data[i + 2] = (byte)(xl >> 8);
data[i + 3] = (byte)(xl);
data[i + 4] = (byte)(xr >> 24);
data[i + 5] = (byte)(xr >> 16);
data[i + 6] = (byte)(xr >> 8);
data[i + 7] = (byte)(xr);
}
}

我的加密方式:

private void EncryptFile(string szFilePath, string szInfoFile, string szKey, string szEncryptedFile = "")
{
// Blowfish
Blowfish alg = new Blowfish(Encoding.Unicode.GetBytes(szKey));

// Open file
System.IO.FileStream originalStream = System.IO.File.OpenRead(szFilePath);

// Store original file length
long originalLength = originalStream.Length;
System.IO.File.WriteAllText(szInfoFile, originalLength.ToString());

Byte[] buffer = new byte[originalStream.Length + (originalStream.Length % 8)];
originalStream.Read(buffer, 0, buffer.Length);
originalStream.Close();

// Encrypt
alg.Encipher(buffer, buffer.Length);

string szEncFile;

if (szEncryptedFile != string.Empty) szEncFile = szEncryptedFile; else szEncFile = szFilePath;

System.IO.FileStream stream = new System.IO.FileStream(szEncFile, System.IO.FileMode.Create);
stream.Write(buffer, 0, buffer.Length);
stream.Close();
}

谢谢。

最佳答案

如果您想要做的是将一个值四舍五入到下一个可被 8 整除的值,那么您应该改为这样做:

Byte[] buffer = new byte[originalStream.Length + (8-(originalStream.Length % 8))];

关于c# - Blowfish 无效长度异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12143873/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com