gpt4 book ai didi

c# - RSA加解密结果有3个问号

转载 作者:太空宇宙 更新时间:2023-11-03 20:16:23 27 4
gpt4 key购买 nike

我正在使用 RSA 加密和解密带有 1 或 2 个单词的小记事本文件。处理后的文件结果在结果开头有3个问号。

例如,如果我加密然后解密其中包含单词“Hello”的记事本文件,结果将是“???Hello”。这 3 个问号是从哪里来的?

这是代码:

    public partial class Form1 : Form
{

private RSAParameters publicKey;
private RSAParameters privateKey;

public string result;

public Form1()
{
InitializeComponent();
var rsa = new RSACryptoServiceProvider();
this.publicKey = rsa.ExportParameters(false);
this.privateKey = rsa.ExportParameters(true);
}

private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
}

private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
textBox1.Text = openFileDialog1.FileName;
}

private void button2_Click(object sender, EventArgs e)
{
FileStream fileStream = new FileStream(textBox1.Text, FileMode.Open);

byte[] buffer = new byte[fileStream.Length];
int len = (int)fileStream.Length;
fileStream.Read(buffer, 0, len);

var rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(publicKey);

var encrypted = rsa.Encrypt(buffer, false);

result = Convert.ToBase64String(encrypted);
MessageBox.Show(result);
}

private void button3_Click(object sender, EventArgs e)
{

var rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(privateKey);

byte[] toDecode = Convert.FromBase64String(result);

var decrypted = rsa.Decrypt(toDecode, false);

string msg = Encoding.ASCII.GetString(decrypted);
MessageBox.Show(msg);
}
}

最佳答案

您的输入文件编码可能是 UTF8,而您正在将其解码为 ASCII。尝试改变

string msg = Encoding.ASCII.GetString(decrypted);

string msg = Encoding.UTF8.GetString(decrypted);

问号由 Byte Order Mark (BOM) 生成在正文前。不需要 BOM 的 UTF-8 并不常见。 UTF-16 更常见,其中字节序是一个问题,但由于纯文本的其余部分似乎解码为 ASCII,因此不能使用 UTF-16 编码。

请注意,ASCII 不能显示任何值为 127(7F,十六进制)或更高的字符。 .NET 平台似乎默默地用问号替换了 BOM 值。

关于c# - RSA加解密结果有3个问号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16450573/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com