【发布时间】:2016-03-13 17:31:45
【问题描述】:
我在 C# 中摆弄密码学。我的文件正在加密,但无法解密。我收到 CryptographyException“错误数据”。我认为这与编码有关,但我没有使用任何编码或字节。
// 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;
}
}
有人有想法吗?
提前致谢!
编辑:这不是一个重复的问题。我的方法和加密的方法完全不同。
【问题讨论】:
-
密文可以包含任何值的字节。它不必对应于任何 valid 编码,这会导致字节丢失。如果您正在处理二进制数据,请不要使用 StreamWriter 或 StreamReader。
-
什么是被加密的纯文本和iv以及密钥?可以从问题复制/粘贴到测试环境的输入和输出会有所帮助。
-
传递参数比使用实例变量更好,这尤其有助于调试/测试。
-
解密时iv需要和加密一样,这通常是通过在加密数据前加上iv来完成的。
-
IV 是一样的。我创建了一次 Cryptographer() 类,该类又创建了一次 _tdes。密钥和 IV 生成一次,加密/解密使用相同的 _tdes。
标签: c# .net cryptography filestream tripledes