RSA加密/解密的结果有3个问号 [英] Result of RSA encryption/decryption has 3 question marks
问题描述
我使用RSA加密和解密1或2个字的小记事本文件。处理后文件结果有3个问号,对结果的乞讨。
I am using RSA to encrypt and decrypt small notepad file with 1 or 2 words. After processing file result has 3 question marks on the begging of result.
例如,如果我加密,然后解密记事本文件与单词Hello,它的结果将是你好。这3个问号来自哪里?
For example, if i encrypt and then decrypt notepad file with word "Hello" in it, result would be "???Hello". Where did that 3 question marks come from?
这是代码:
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。尝试更改
It's likely that your input file encoding is UTF8, and you are decoding it into ASCII. Try changing
string msg = Encoding.ASCII.GetString(decrypted);
到
string msg = Encoding.UTF8.GetString(decrypted);
问号是由字节顺序标记(BOM)。对于不需要BOM的UTF-8,这是不常见的。这是更常见的UTF-16,其中endianness是一个问题,但因为其余的纯文本似乎解码为ASCII,它不能是UTF-16编码。
The question marks are generated by the Byte Order Mark (BOM) in front of the text. It is uncommon for UTF-8 which does not require a BOM. It is more common for UTF-16 where endianness is an issue, but as the rest of the plain text seems to decode to ASCII, it can not be UTF-16 encoded.
请注意,ASCII不能显示任何值为127( 7F
十六进制)或更高的字符。 .NET平台似乎默认用问号替换BOM值。
Note that ASCII cannot show any characters with value 127 (7F
in hexadecimals) or higher. The .NET platform seems to silently replace the BOM values with question marks.
这篇关于RSA加密/解密的结果有3个问号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!