Asp.Net StreamReader 错误读取字符串

发布于 2025-01-18 04:12:54 字数 5600 浏览 1 评论 0原文

我目前正在开发一个简单的 AesGcm 编码器,它将某些域的密码存储在文本文件中(这是一项实验室作业)。我在从文件中取回存储的字符串时遇到问题,并且不知道如何修复它。欢迎任何帮助!

这是我的代码的一部分:

{
    using (var aes = new AesGcm(Encoding.UTF8.GetBytes(masterPassword.PadRight(32))))
    {
        var nonce = new byte[12];
        RandomNumberGenerator.Fill(nonce);
        var plaintextBytes = Encoding.UTF8.GetBytes(masterPassword);
        var ciphertext = new byte[plaintextBytes.Length];
        var tag = new byte[16];

        aes.Encrypt(nonce, plaintextBytes, ciphertext, tag);

        using (var fileWriter = new FileStream("TestData.txt", FileMode.OpenOrCreate, FileAccess.Write))
        {
            using(var streamWriter = new StreamWriter(fileWriter, System.Text.Encoding.UTF8))
            {
                var nonceString = System.Text.Encoding.UTF8.GetString(nonce);
                var cipherTextString = System.Text.Encoding.UTF8.GetString(ciphertext);
                var tagString = System.Text.Encoding.UTF8.GetString(tag);
                streamWriter.Write($"{nonceString}|{tagString}|{cipherTextString}\n");
            }
        }
    }
}

在初始化文本文件(任务所需)后,我需要在例如中放入一些信息(放入 masterPassword domain password )。在执行此操作之前,我首先通过查看 masterPassword 是否与我使用此函数在初始化时编码的密码匹配来验证用户:

{
    using (var aes = new AesGcm(Encoding.UTF8.GetBytes(masterPassword.PadRight(32))))
    {
        using(var reader = new StreamReader("TestData.txt", System.Text.Encoding.UTF8))
        {
            var line = reader.ReadLine().Split("|");

            foreach(var s in line)
                Console.WriteLine(s);

            var nonce = Encoding.UTF8.GetBytes(line[0]);
            var tag = Encoding.UTF8.GetBytes(line[1]);
            var ciphertext = Encoding.UTF8.GetBytes(line[2]);

            var plaintext = new byte[ciphertext.Length];

            aes.Decrypt(nonce, ciphertext, tag, plaintext);

            if (Encoding.UTF8.GetString(plaintext).Equals(masterPassword))
                return true;
            return false;
        }
    }
}

但由于某种原因,数据读取不正确,我得到的不是大小为 12 的随机数,而是大小为大小的随机数20.

这是用于测试目的的完整代码:

using System.Security.Cryptography;
using System.Text;

var arguments = Environment.GetCommandLineArgs();

switch (arguments[1])
{
    case "init":
         Initialize(arguments[2]);
        break;
    case "put":
        if(Validate(arguments[2]))
         //EncryptData(arguments[2], arguments[3], arguments[4]);
        else
            Console.WriteLine("Unauthorized!");
        break;
    case "get":
            //DecryptAsync(arguments[2], arguments[3]);
        break;
    default:
        Console.WriteLine("Invalid arguments");
        break;
}

void Initialize(string masterPassword)
{
    using (var aes = new AesGcm(Encoding.UTF8.GetBytes(masterPassword.PadRight(32))))
    {
        var nonce = new byte[12];
        RandomNumberGenerator.Fill(nonce);
        var plaintextBytes = Encoding.UTF8.GetBytes(masterPassword);
        var ciphertext = new byte[plaintextBytes.Length];
        var tag = new byte[16];

        aes.Encrypt(nonce, plaintextBytes, ciphertext, tag);

        using (var fileWriter = new FileStream("TestData.txt", FileMode.OpenOrCreate, FileAccess.Write))
        {
            using(var streamWriter = new StreamWriter(fileWriter, System.Text.Encoding.UTF8))
            {
                var nonceString = System.Text.Encoding.UTF8.GetString(nonce);
                var cipherTextString = System.Text.Encoding.UTF8.GetString(ciphertext);
                var tagString = System.Text.Encoding.UTF8.GetString(tag);
                streamWriter.Write($"{nonceString}|{tagString}|{cipherTextString}\n");
            }
        }
    }
}

/*void EncryptData(string masterPassword, string domain, string password)
{
    using (var aes = new AesGcm(Encoding.UTF8.GetBytes(masterPassword.PadRight(32))))
    {
        var nonce = new byte[AesGcm.NonceByteSizes.MaxSize];
        RandomNumberGenerator.Fill(nonce);
        var plaintextBytes = Encoding.UTF8.GetBytes("|" + domain + "|" + password);
        var ciphertext = new byte[plaintextBytes.Length];
        var tag = new byte[AesGcm.TagByteSizes.MaxSize];

        using (var fileWriter = new FileStream("TestData.txt", FileMode.Open, FileAccess.Write))
        {
            fileWriter.Seek(0, SeekOrigin.End);
            var separator = Encoding.UTF8.GetBytes("|");
            var newLine = Encoding.UTF8.GetBytes("\n");
            byte[] buffer = nonce.Concat(separator).ToArray();
            aes.Encrypt(nonce, plaintextBytes, ciphertext, tag);
            buffer.Concat(tag).Concat(separator).Concat(ciphertext).Concat(plaintextBytes).Concat(newLine).ToArray();
            fileWriter.Write(buffer, 0, buffer.Length);
        }
    }
}*/

bool Validate(string masterPassword)
{
    using (var aes = new AesGcm(Encoding.UTF8.GetBytes(masterPassword.PadRight(32))))
    {
        using(var reader = new StreamReader("TestData.txt", System.Text.Encoding.UTF8))
        {
            var line = reader.ReadLine().Split("|");

            foreach(var s in line)
                Console.WriteLine(s);

            var nonce = Encoding.UTF8.GetBytes(line[0]);
            var tag = Encoding.UTF8.GetBytes(line[1]);
            var ciphertext = Encoding.UTF8.GetBytes(line[2]);

            var plaintext = new byte[ciphertext.Length];

            aes.Decrypt(nonce, ciphertext, tag, plaintext);

            if (Encoding.UTF8.GetString(plaintext).Equals(masterPassword))
                return true;
            return false;
        }
    }
}

I'm currently working on a simple AesGcm encoder that stores passwords for certain domains in a text file (It's a lab assignment). I'm having trouble fetching stored strings back from the file and I haven't a clue how to fix it. Any help is welcome!

Here is a part of my code:

{
    using (var aes = new AesGcm(Encoding.UTF8.GetBytes(masterPassword.PadRight(32))))
    {
        var nonce = new byte[12];
        RandomNumberGenerator.Fill(nonce);
        var plaintextBytes = Encoding.UTF8.GetBytes(masterPassword);
        var ciphertext = new byte[plaintextBytes.Length];
        var tag = new byte[16];

        aes.Encrypt(nonce, plaintextBytes, ciphertext, tag);

        using (var fileWriter = new FileStream("TestData.txt", FileMode.OpenOrCreate, FileAccess.Write))
        {
            using(var streamWriter = new StreamWriter(fileWriter, System.Text.Encoding.UTF8))
            {
                var nonceString = System.Text.Encoding.UTF8.GetString(nonce);
                var cipherTextString = System.Text.Encoding.UTF8.GetString(ciphertext);
                var tagString = System.Text.Encoding.UTF8.GetString(tag);
                streamWriter.Write(
quot;{nonceString}|{tagString}|{cipherTextString}\n");
            }
        }
    }
}

After I Initialize the text file (Required by the task) I need to put some info in e.g. (put masterPassword domain password). Before I do that i first validate the user by seeing if the masterPassword matches with the one i encoded on initialization using this function:

{
    using (var aes = new AesGcm(Encoding.UTF8.GetBytes(masterPassword.PadRight(32))))
    {
        using(var reader = new StreamReader("TestData.txt", System.Text.Encoding.UTF8))
        {
            var line = reader.ReadLine().Split("|");

            foreach(var s in line)
                Console.WriteLine(s);

            var nonce = Encoding.UTF8.GetBytes(line[0]);
            var tag = Encoding.UTF8.GetBytes(line[1]);
            var ciphertext = Encoding.UTF8.GetBytes(line[2]);

            var plaintext = new byte[ciphertext.Length];

            aes.Decrypt(nonce, ciphertext, tag, plaintext);

            if (Encoding.UTF8.GetString(plaintext).Equals(masterPassword))
                return true;
            return false;
        }
    }
}

But for some reason the data is improperly read and instead of getting a nonce of size 12 I get a nonce of size 20.

Here is the complete code for the purpose of testing:

using System.Security.Cryptography;
using System.Text;

var arguments = Environment.GetCommandLineArgs();

switch (arguments[1])
{
    case "init":
         Initialize(arguments[2]);
        break;
    case "put":
        if(Validate(arguments[2]))
         //EncryptData(arguments[2], arguments[3], arguments[4]);
        else
            Console.WriteLine("Unauthorized!");
        break;
    case "get":
            //DecryptAsync(arguments[2], arguments[3]);
        break;
    default:
        Console.WriteLine("Invalid arguments");
        break;
}

void Initialize(string masterPassword)
{
    using (var aes = new AesGcm(Encoding.UTF8.GetBytes(masterPassword.PadRight(32))))
    {
        var nonce = new byte[12];
        RandomNumberGenerator.Fill(nonce);
        var plaintextBytes = Encoding.UTF8.GetBytes(masterPassword);
        var ciphertext = new byte[plaintextBytes.Length];
        var tag = new byte[16];

        aes.Encrypt(nonce, plaintextBytes, ciphertext, tag);

        using (var fileWriter = new FileStream("TestData.txt", FileMode.OpenOrCreate, FileAccess.Write))
        {
            using(var streamWriter = new StreamWriter(fileWriter, System.Text.Encoding.UTF8))
            {
                var nonceString = System.Text.Encoding.UTF8.GetString(nonce);
                var cipherTextString = System.Text.Encoding.UTF8.GetString(ciphertext);
                var tagString = System.Text.Encoding.UTF8.GetString(tag);
                streamWriter.Write(
quot;{nonceString}|{tagString}|{cipherTextString}\n");
            }
        }
    }
}

/*void EncryptData(string masterPassword, string domain, string password)
{
    using (var aes = new AesGcm(Encoding.UTF8.GetBytes(masterPassword.PadRight(32))))
    {
        var nonce = new byte[AesGcm.NonceByteSizes.MaxSize];
        RandomNumberGenerator.Fill(nonce);
        var plaintextBytes = Encoding.UTF8.GetBytes("|" + domain + "|" + password);
        var ciphertext = new byte[plaintextBytes.Length];
        var tag = new byte[AesGcm.TagByteSizes.MaxSize];

        using (var fileWriter = new FileStream("TestData.txt", FileMode.Open, FileAccess.Write))
        {
            fileWriter.Seek(0, SeekOrigin.End);
            var separator = Encoding.UTF8.GetBytes("|");
            var newLine = Encoding.UTF8.GetBytes("\n");
            byte[] buffer = nonce.Concat(separator).ToArray();
            aes.Encrypt(nonce, plaintextBytes, ciphertext, tag);
            buffer.Concat(tag).Concat(separator).Concat(ciphertext).Concat(plaintextBytes).Concat(newLine).ToArray();
            fileWriter.Write(buffer, 0, buffer.Length);
        }
    }
}*/

bool Validate(string masterPassword)
{
    using (var aes = new AesGcm(Encoding.UTF8.GetBytes(masterPassword.PadRight(32))))
    {
        using(var reader = new StreamReader("TestData.txt", System.Text.Encoding.UTF8))
        {
            var line = reader.ReadLine().Split("|");

            foreach(var s in line)
                Console.WriteLine(s);

            var nonce = Encoding.UTF8.GetBytes(line[0]);
            var tag = Encoding.UTF8.GetBytes(line[1]);
            var ciphertext = Encoding.UTF8.GetBytes(line[2]);

            var plaintext = new byte[ciphertext.Length];

            aes.Decrypt(nonce, ciphertext, tag, plaintext);

            if (Encoding.UTF8.GetString(plaintext).Equals(masterPassword))
                return true;
            return false;
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文