How to make a file unreadable by user only when saved to a disk, say on C drive?
Asked
Active
Viewed 277 times
-2
-
2Just pass the file through `CryptoStream` whenever you read or write it. But you will need to figure out where to store the key. Read http://blogs.msdn.com/b/ericlippert/archive/2011/09/27/keep-it-secret-keep-it-safe.aspx – SLaks Jan 12 '16 at 00:44
-
Encryption doesnt make data invisible to human eyes, just unreadable. So where is the data? Do you know how to save it to a file? Is it just text? – Ňɏssa Pøngjǣrdenlarp Jan 12 '16 at 01:05
-
If the file is for a single user on a single Windows machine, consider the Data Protection API. – Tom Blodget Jan 12 '16 at 02:22
-
@Plutonix, I meant 'unreadable'. Thank you for the precision. The data is created by the application at runtime and saved to the location on a disk where user stores information, eg. C drive. It is this data I wanted to save encrypted. But then when the application opens back this file, it needs to be decrypted. I just want the saved data unreadable by human eyes – codelearner Jan 13 '16 at 08:46
-
@Tom Blodget, can you show me an example? – codelearner Jan 13 '16 at 08:54
1 Answers
0
If the data originates in the application and is only for the current user on the same Windows machine,
// using System.Security.Cryptography;
var path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
@"/user data that only a program run by this user can read.dat";
Console.WriteLine(path);
var entropy = Encoding.UTF8.GetBytes("See http://security.stackexchange.com/a/58121");
var data = Encoding.UTF8.GetBytes(
@"Data to be stored in a way that only programs that run under
this account can decrypt but nobody's eyes can understand. But
if an admin forces a password change, it's irretrievable
(see http://stackoverflow.com/a/4755929/2226988).");
File.WriteAllBytes(path, ProtectedData.Protect(
data,
entropy,
DataProtectionScope.CurrentUser));
var readBack = ProtectedData.Unprotect(
File.ReadAllBytes(path),
entropy,
DataProtectionScope.CurrentUser);
Console.WriteLine(Encoding.UTF8.GetString(readBack));

Tom Blodget
- 20,260
- 3
- 39
- 72