C#1024bit加密出错了

时间:2013-04-01 21:44:11

标签: c# encryption

我正在使用此代码加密字节,我已经测试了1-255个字节,并且值大于128的每个字节都被解密为63

enter image description here

AEK is a 16char string
public byte[] AE1024(byte[] __test)
    {
        byte[] data = __test;
        byte[] rgbKey = ASCIIEncoding.ASCII.GetBytes(AEK.Substring(0, AEK.Length / 2));
        byte[] rgbIV = ASCIIEncoding.ASCII.GetBytes(AEK.Substring(AEK.Length / 2, AEK.Length / 2));
        MemoryStream memoryStream = new MemoryStream(1024);
        DESCryptoServiceProvider desCryptoServiceProvider = new DESCryptoServiceProvider();
        CryptoStream cryptoStream = new CryptoStream(memoryStream, desCryptoServiceProvider.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
        cryptoStream.Write(data, 0, data.Length);
        cryptoStream.FlushFinalBlock();
        byte[] result = new byte[(int)memoryStream.Position];
        memoryStream.Position = 0;
        memoryStream.Read(result, 0, result.Length);
        cryptoStream.Close();
        memoryStream.Dispose();
        return result;
    }

这是解密方法

public byte[] AD1024(byte[] __test)
    {
        byte[] data =__test;
        byte[] rgbKey = ASCIIEncoding.ASCII.GetBytes(AEK.Substring(0, AEK.Length / 2));
        byte[] rgbIV = ASCIIEncoding.ASCII.GetBytes(AEK.Substring(AEK.Length / 2, AEK.Length / 2));
        MemoryStream memoryStream = new MemoryStream(data.Length+1);
        DESCryptoServiceProvider desCryptoServiceProvider = new DESCryptoServiceProvider();
        ICryptoTransform x = desCryptoServiceProvider.CreateDecryptor(rgbKey, rgbIV);
        CryptoStream cryptoStream = new CryptoStream(memoryStream, x, CryptoStreamMode.Read);
        memoryStream.Write(data, 0, data.Length);
        memoryStream.Position = 0;
        string decrypted = new StreamReader(cryptoStream).ReadToEnd();
        cryptoStream.Close();
        memoryStream.Dispose();
        return Encoding.ASCII.GetBytes(decrypted);
    }

2 个答案:

答案 0 :(得分:2)

您看到63的原因是您正在使用ASCII编码。编码时,任何超过128的整数都将变为63(或?)。

static void Main()
{
    byte[] bytes = new[]{(byte)129};

    string asciiString = Encoding.ASCII.GetString(bytes);

    byte[] encodedBytes = Encoding.ASCII.GetBytes(asciiString);

    Console.WriteLine(bytes[0]);
    Console.WriteLine(asciiString);
    Console.WriteLine(encodedBytes[0]);

    Console.ReadLine();
}

以上输出:

129
?
63

由于字节> 128不对应ASCII或Unicode中的文本,我建议@usr在评论中说你的加密/解密例程已经破坏。

答案 1 :(得分:0)

你的解密方法是......创意......

为什么使用流阅读器?您的原始加密数据是byte [] ...不是字符串...

获得解密者

制作新的MemoryStream

使用解密器作为ICryptoTransform将其包装到具有CryptoStreamMode.Write的新CryptoStream中

将加密的字节写入CryptoStream

开始使用MemoryStreams缓冲区,它将保存明文字节数组