我如何使用TripleDESCryptographyServiceProvider类?

时间:2016-03-13 17:31:45

标签: c# .net cryptography filestream tripledes

我正在摆弄c#中的加密技术。我的文件已加密,但无法解密。我得到一个CryptographyException“Bad Data”。我认为它与编码有关,但我没有使用任何编码或字节。

// Encrypts the data
    public bool encrypt ( ) {
        try {
            // Create or open the specified file.
            FileStream fStream = File.Open ( _encPath, FileMode.OpenOrCreate );

            // Create a CryptoStream using the FileStream 
            // and the passed key and initialization vector (IV).
            CryptoStream cStream = new CryptoStream ( fStream,
                _tdes.CreateEncryptor ( _tdes.Key, _tdes.IV ),
                CryptoStreamMode.Write );

            // Create a StreamWriter using the CryptoStream.
            StreamWriter sWriter = new StreamWriter ( cStream );

            // Write the data to the stream 
            // to encrypt it.
            sWriter.WriteLine ( _content );

            // Close the streams and
            // close the file.
            sWriter.Close ( );
            cStream.Close ( );
            fStream.Close ( );
        } catch ( CryptographicException e ) {
            Console.WriteLine ( "A Cryptographic error occurred: {0}", e.Message );
            return false;
        } catch ( UnauthorizedAccessException e ) {
            Console.WriteLine ( "A file access error occurred: {0}", e.Message );
            return false;
        }

        return true;
    }

 // Decrypts the file
    public bool decrypt ( ) {
        try {
            // Create or open the specified file. 
            FileStream fStream = File.Open ( _path, FileMode.OpenOrCreate );

            // Create a CryptoStream using the FileStream 
            // and the passed key and initialization vector (IV).
            CryptoStream cStream = new CryptoStream ( fStream,
                _tdes.CreateDecryptor ( _tdes.Key, _tdes.IV ),
                CryptoStreamMode.Read ); // Exception happens here

            // Create a StreamReader using the CryptoStream.
            StreamReader sReader = new StreamReader ( cStream );

            // Read the data from the stream 
            // to decrypt it.
            String val = sReader.ReadLine ( );

            // Close the streams and
            // close the file.
            sReader.Close ( );
            cStream.Close ( );
            fStream.Close ( );

            File.WriteAllText ( _decPath, val );
        } catch ( CryptographicException e ) {
            Console.WriteLine ( "A Cryptographic error occurred: {0}", e.Message );
            return false;
        } catch ( UnauthorizedAccessException e ) {
            Console.WriteLine ( "A file access error occurred: {0}", e.Message );
            return false;
        }

        return true;
    }
}

有人有想法吗?

提前致谢!

编辑:这不是一个重复的问题。我的方法与加密方法完全不同。

编辑2:Hex dump

1 个答案:

答案 0 :(得分:0)

您的代码实际上在linqpad 5(.net 4.6)中为我工作。

您确定要在运行之间删除或正确清除文件吗?考虑到使用流写入加密文件的方式,您可能只是从运行到运行整体部分更新文件。