坏数据:加密c#

本文关键字:加密 数据 | 更新日期: 2023-09-27 18:12:30

我是c#和密码学的新手,我通过从各种来源(如CodeProject和StackOverflow)获取数据来编写以下代码。

public class CryptoSafe
{
    private const int SaltSize = 8;
    public void EncryptAndWrite(FileInfo targetFile, string password)
    {
        FileStream stream = new FileStream(targetFile.FullName, FileMode.Open, FileAccess.Write);
        DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
        // 
        var keyGenerator = new Rfc2898DeriveBytes(password, SaltSize);
        var rijndael = Rijndael.Create();
        var length = rijndael.BlockSize;
        // BlockSize, KeySize in bit --> divide by 8
        cryptic.IV = keyGenerator.GetBytes(rijndael.BlockSize / 16);
        cryptic.Key = keyGenerator.GetBytes(rijndael.KeySize / 32);
        CryptoStream crStream = new CryptoStream(stream, cryptic.CreateEncryptor(), CryptoStreamMode.Write);
        byte[] data = ASCIIEncoding.ASCII.GetBytes(System.DateTime.Now.ToString("dd-MMM-yyyy HH;mm:ss"));
        crStream.Write(data, 0, data.Length);
        crStream.Close();
        stream.Close();
    }

    public string DecryptAndRead(FileInfo sourceFile, string password)
    {
        FileStream stream = new FileStream(sourceFile.FullName, FileMode.Open, FileAccess.Read);
        DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
        // read salt
        //var fileStream = sourceFile.OpenRead();
        //var salt = new byte[SaltSize];
        // fileStream.Read(salt, 0, SaltSize);
        // initialize algorithm with salt
        var keyGenerator = new Rfc2898DeriveBytes(password, SaltSize);
        var rijndael = Rijndael.Create();
        cryptic.IV = keyGenerator.GetBytes(rijndael.BlockSize / 16);
        cryptic.Key = keyGenerator.GetBytes(rijndael.KeySize / 32);
        // decrypt
        CryptoStream crStream = new CryptoStream(stream, cryptic.CreateDecryptor(), CryptoStreamMode.Read);
        StreamReader reader = new StreamReader(crStream);
        string data = reader.ReadToEnd();
        reader.Close();
        stream.Close();
        return data;
    }
}

加密工作正常,正在写入文件中。但是,在解密文件时,它给出了错误"坏数据"。我试着在SO上搜索,但没有多大帮助。

我做错了什么?请帮助!

坏数据:加密c#

那么,你做错了什么呢?

第一个DES自90年代以来一直是蛮力破解的。

第二,你有一个不同的随机盐加密和解密,所以你永远无法解密。

第三,有很多错误是与加密,这是看似容易,要么开始与一个更好的例子或使用一个高级库。