de li
de li

Reputation: 932

Read encrypted text files in c#

I have encypt a text file by the System.Security.Cryptography.Aes class. And I want to read it.

The encrypted file is like this:

첅ꙟ䤀檐⑆놞豱놈⦜튞㌝⑾钏짼ጻ뤻諓襬ꆅ㵶�紧음즼덦힪쀗ᏢⰃ䑹ᙙ鹛賹ɗꬖ濬⇊쭩폹憺㇞䔣�❷제蠒鶰܇꼺秵Ā輱쭇뎀固쑍㘘킭мុ喀�螙돸忁葪⭻ꓻ颇弔ѯ랮

I am using this code to read this:

var lines = File.ReadAllLines(encryptedtxtpath);

And also with a specific encoding:

var lines = File.ReadAllLines(encryptedtxtpath, System.Text.Encoding.UTF8);

However the lines variable I got is totally different like this:

"��_�\0I�jF$��q����)��3~$����;;�ӊl���v=]�'}LǼ�f�h����s�m�,yDY[���W�.��o�!i��ӺaT��1#E��w'����\a\a:��y\01�Gˀ��VM�6��<����U�ޙ������_j�{+��z釘_o��"

How can I read the original file in my code?

Any help is appreciated!

Upvotes: 1

Views: 5090

Answers (1)

weirdev
weirdev

Reputation: 1398

If you want the encrypted data from the file so you can decrypt it later in code you'll want:

byte[] fileBytes = File.ReadAllBytes(encryptedtxtpath);

Reading the encrypted file as text will not work, because encrypted data will appear random.

To decrypt fileBytes, feed it into the decryption component of the class you used to encrypt the data in the first place. You will get a byte array back. From here you can write the binary directly to disk, or, if the decrypted data is text, use:

Encoding.UTF8.GetString(decrypyedbytesarray)

to get a string representation of the data. Replace UTF8 with the appropriate encoding.

Upvotes: 4

Related Questions