[英]Result of RSA encryption/decryption has 3 question marks
I am using RSA to encrypt and decrypt small notepad file with 1 or 2 words. 我正在使用RSA加密和解密1或2个单词的小型记事本文件。 After processing file result has 3 question marks on the begging of result.
处理文件结果后,结果请求上有3个问号。
For example, if i encrypt and then decrypt notepad file with word "Hello" in it, result would be "???Hello". 例如,如果我加密然后用单词“ Hello”解密记事本文件,则结果将是“ ??? Hello”。 Where did that 3 question marks come from?
那三个问号来自哪里?
This is the code: 这是代码:
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);
}
}
It's likely that your input file encoding is UTF8, and you are decoding it into ASCII. 您的输入文件编码可能是UTF8,并且正在将其解码为ASCII。 Try changing
尝试改变
string msg = Encoding.ASCII.GetString(decrypted);
to 至
string msg = Encoding.UTF8.GetString(decrypted);
The question marks are generated by the Byte Order Mark (BOM) in front of the text. 问号由文本前面的字节顺序标记(BOM)生成。 It is uncommon for UTF-8 which does not require a BOM.
对于不需要BOM的UTF-8并不常见。 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.
对于UTF-16来说,字节序是个问题,但这种情况更为常见,但是由于其余的纯文本似乎都已解码为ASCII,因此无法对其进行UTF-16编码。
Note that ASCII cannot show any characters with value 127 ( 7F
in hexadecimals) or higher. 请注意,ASCII不能显示任何值为127(十六进制为
7F
)或更高的字符。 The .NET platform seems to silently replace the BOM values with question marks. .NET平台似乎用问号默默地替换了BOM值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.