c# - Result of RSA encryption/decryption has 3 question marks -
i using rsa encrypt , decrypt small notepad file 1 or 2 words. after processing file result has 3 question marks on begging of result.
for example, if encrypt , decrypt notepad file word "hello" in it, result "???hello". did 3 question marks come from?
this 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 input file encoding utf8, , decoding ascii. try changing
string msg = encoding.ascii.getstring(decrypted);
to
string msg = encoding.utf8.getstring(decrypted);
the question marks generated byte order mark (bom) in front of text. uncommon utf-8 not require bom. more common utf-16 endianness issue, rest of plain text seems decode ascii, can not utf-16 encoded.
note ascii cannot show characters value 127 (7f
in hexadecimals) or higher. .net platform seems silently replace bom values question marks.
Comments
Post a Comment