我正在构建一个需要加密保存等的游戏。因此,我在开发一些功能来帮助我加密它们。但是,我目前拥有的唯一函数使用FileStreams进行输入和输出,但是我想使用字符串代替。这些功能在Files上可以正常工作,但是在从FileStreams到MemoryStreams到字符串交换时遇到了麻烦。
注意:我已删除了不相关的代码。 OurCodeWorld.GenerateRandomSalt()
100%可以正常工作,并通过FileStream加密进行了测试
完整代码:
Program.cs:
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
namespace Encryption_test
{
class Program
{
static public string encryptedExtension = ".aes";
static public string decryptedExtension = ".decrypted";
static void Main(string[] args)
{
string path = Environment.CurrentDirectory;
Log($"Current path: {path}");
string filePath = $"{path}/unencrypted.txt";
string message =
@"Hello world!
This is my message. 1234";
RunStackOverFlowString();
//Sleep forever...zzz
Thread.Sleep(10000);
Console.WriteLine();
float TicksToMs(long ticks)
{
return ticks / (float)Stopwatch.Frequency * 1000F;
}
void RunStackOverFlowString()
{
byte[] salt = OurCodeWorld.GenerateRandomSalt();
int iterations = 1024;
string password = "";
string enc = StackOverflow.EncryptString(message, password, salt, iterations);
Log($"Enc: {enc}");
string dec = StackOverflow.DecryptString(enc, password, salt, iterations);
Log($"Dec: {dec}");
}
private static void WriteFile(string path, string value)
{
FileStream _file = File.OpenWrite(path);
byte[] info = new UTF8Encoding(true).GetBytes(value);
_file.Write(info, 0, info.Length);
_file.Close();
}
private static string ReadFile(string filePath, long length = long.MaxValue)
{
FileStream _file = File.OpenRead(filePath);
if (length == long.MaxValue)
length = _file.Length;
byte[] b = new byte[length];
UTF8Encoding temp = new UTF8Encoding(true);
_file.Read(b, 0, b.Length);
_file.Close();
return temp.GetString(b);
}
private static void DeleteFile(string path)
{
File.Delete(path);
}
private static void CreateFile(string path)
{
if (File.Exists(path))
DeleteFile(path);
FileStream a = File.Open(path, FileMode.Create);
a.Close();
}
static void Log(string message)
{
Console.WriteLine(message);
}
}
}
StackOverFlow.cs:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
class StackOverflow
{
// Rfc2898DeriveBytes constants:
/// <summary>Decrypt a file.</summary>
/// <remarks>NB: "Padding is invalid and cannot be removed." is the Universal CryptoServices error. Make sure the password, salt and iterations are correct before getting nervous.</remarks>
/// <param name="sourceFilename">The full path and name of the file to be decrypted.</param>
/// <param name="destinationFilename">The full path and name of the file to be output.</param>
/// <param name="password">The password for the decryption.</param>
/// <param name="salt">The salt to be applied to the password.</param>
/// <param name="iterations">The number of iterations Rfc2898DeriveBytes should use before generating the key and initialization vector for the decryption.</param>
public static void DecryptFile(string sourceFilename, string destinationFilename, string password, byte[] salt, int iterations)
{
AesManaged aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
// NB: Rfc2898DeriveBytes initialization and subsequent calls to GetBytes must be eactly the same, including order, on both the encryption and decryption sides.
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
aes.Key = key.GetBytes(aes.KeySize / 8);
aes.IV = key.GetBytes(aes.BlockSize / 8);
aes.Mode = CipherMode.CBC;
ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);
using (FileStream destination = new FileStream(destinationFilename, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
{
try
{
using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
source.CopyTo(cryptoStream);
}
}
catch (CryptographicException exception)
{
if (exception.Message == "Padding is invalid and cannot be removed.")
throw new ApplicationException("Universal Microsoft Cryptographic Exception (Not to be believed!)", exception);
else
throw;
}
}
}
}
/// <summary>Encrypt a file.</summary>
/// <param name="sourceFilename">The full path and name of the file to be encrypted.</param>
/// <param name="destinationFilename">The full path and name of the file to be output.</param>
/// <param name="password">The password for the encryption.</param>
/// <param name="salt">The salt to be applied to the password.</param>
/// <param name="iterations">The number of iterations Rfc2898DeriveBytes should use before generating the key and initialization vector for the decryption.</param>
public static void EncryptFile(string sourceFilename, string destinationFilename, string password, byte[] salt, int iterations)
{
AesManaged aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
// NB: Rfc2898DeriveBytes initialization and subsequent calls to GetBytes must be eactly the same, including order, on both the encryption and decryption sides.
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
aes.Key = key.GetBytes(aes.KeySize / 8);
aes.IV = key.GetBytes(aes.BlockSize / 8);
aes.Mode = CipherMode.CBC;
ICryptoTransform transform = aes.CreateEncryptor(aes.Key, aes.IV);
using (FileStream destination = new FileStream(destinationFilename, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
{
using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
source.CopyTo(cryptoStream);
}
}
}
}
//THIS IS MY CODE
public static string EncryptString(string inputString, string password, byte[] salt, int iterations)
{
AesManaged aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
// NB: Rfc2898DeriveBytes initialization and subsequent calls to GetBytes must be eactly the same, including order, on both the encryption and decryption sides.
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
aes.Key = key.GetBytes(aes.KeySize / 8);
aes.IV = key.GetBytes(aes.BlockSize / 8);
aes.Mode = CipherMode.CBC;
ICryptoTransform transform = aes.CreateEncryptor(aes.Key, aes.IV);
var source = StringToStream(inputString);
var output = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(output, transform, CryptoStreamMode.Write);
source.CopyTo(cryptoStream);
return StreamToString(output);
}
public static string DecryptString(string inputString, string password, byte[] salt, int iterations)
{
AesManaged aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
// NB: Rfc2898DeriveBytes initialization and subsequent calls to GetBytes must be eactly the same, including order, on both the encryption and decryption sides.
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
aes.Key = key.GetBytes(aes.KeySize / 8);
aes.IV = key.GetBytes(aes.BlockSize / 8);
aes.Mode = CipherMode.CBC;
ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);
var source = StringToStream(inputString);
var output = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(output, transform, CryptoStreamMode.Write);
source.CopyTo(cryptoStream);
return StreamToString(output);
}
public static Stream StringToStream(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
public static string StreamToString(Stream s)
{
s.Position = 0;
byte[] buffer = new byte[s.Length];
s.Read(buffer, 0, (int)s.Length);
return Encoding.Default.GetString(buffer);
}
}
我已经测试了StreamToString
和StringToStream
方法,它们可以正常工作。当我运行DecryptString
时,没有输出,该函数返回乱码,通常看起来与此Dec: ?K???
?@?????n?l?r????T?
答案 0 :(得分:0)
使用和Encoding
完成字符串和二进制数据之间的转换。编码确定如何将字符转换为二进制数据。常见的编码是Unicode,UTF8或ASCII。如果您希望获得可预测的结果,则需要为两种转换使用特定的编码。
在StringToStream
中使用Encoding.Default
时,您根本没有指定编码。 StreamToString
无法提供可预测的结果,因为它使用当前的代码页(如果您在Windows系统上运行)。因此,您不能确定两种方法都使用相同的编码。
解决方案是在两端提供相同的编码:
Encoding.Default
答案 1 :(得分:0)
我测试了代码。有两个问题:
byte[] Encrypt(byte[] input, ...)
。加密代码无需在字符串之间进行转换。EncryptString
必须使用FlushFinalBlock
刷新加密流。如果不这样做,最后的数据将丢失。