In my c# program, I have an image which is successfully stored in a byte[] data called bytes. I successfully write it into a .txt file using the following code
using (FileStream file = new FileStream("text.txt", FileMode.Create, FileAccess.Write))
{
file.Write(bytes, 0, numToWrite);
file.Close();
}
The above code stores the exact content I wish to store.
Whenever I wish to read the content of the file, text.txt, into textbox I only get the first line or little part of the first line. But when I open the file, text.txt, I see the complete content.
This is the code I use to read the file
string kk = File.ReadAllText("text.txt");
You have said at the start of the question that you have a byte[] that you are writing into the file. It's not clear why you decided not to use File.WriteAllBytes but let's assume that your code is correctly writing all the data into the file called "text.txt", which has been explained in comments does not magically make this a text file.
Using File.ReadAllText is not going to work because The data in the file is binary data, not text. As you can see from the remarks on the documentation, it will try to decide the encoding of the text file (which won't work because it contains binary data) and will do end of line processing which you won't want for a binary file.
The best way to read the data back is to use File.ReadAllBytes, which gives you back a byte[], just like you started with.
in My application, i read .DSS format audio Files into Byte Array,with following code
byte[] bt = File.ReadAllBytes(Filepath);
but i am unable to get data into Byte's. but In the Audio player it is playing ,
here how can i read the files into Byte Array.
Here i am attaching Snap, what bt have, it show's 255 for all bytes.
TIA
To ensure this is not the issue with File.ReadAllBytes, try to read file using stream, like this:
using (var fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, (int) fileStream.Length);
// use buffer;
}
UPDATE: as it's not working too, there should be issue with your file. Try to find any process that may be blocking and using it at the moment. Also, try to open the file with any HEX editor and see if there really any meaningful data present. I'd also create clean testing app/sandbox to test if it's working.
Well, the Dss format is copyrighted, and you'll likely not find a lot of information about it.
255 or 0xFF is commonly used in Dss files to indicate that a byte is not in use. You will see many of them in the header of the Dss file, later in the audio part they will be more sparse.
That means: a value of 255 in the region of bytes 83-97 which you show does NOT mean that something went wrong.
I have a program which saves a little .txt file with a highscore in it:
// Create a file to write to.
string createHighscore = _higscore + Environment.NewLine;
File.WriteAllText(path, createText);
// Open the file to read from.
string createHighscore = File.ReadAllText(path);
The problem is that the user can edit the file as simple as possible β with a texteditor. So I want to make the file unreadable / uneditable or encrypt it.
My thinking was that I could save the data in a resource file, but can I write in a resource file?
Or save it as .dll, encrypt/decrypt it or look for a MD5-sum/hash.
You can't prevent the user from modifying the file. It's their computer, so they can do whatever they want (that's why the whole DRM issue is⦠difficult).
Since you said you're using the file to save an high-score, you have a couple of alternatives. Do note that as previously said no method will stop a really determined attacker from tampering with the value: since your application is running on the user computer he can simply decompile it, look at how you're protecting the value (gaining access to any secret used in the process) and act accordingly. But if you're willing to decompile an application, find out the protection scheme used and come up with a script/patch to get around it only to change a number only you can see, well, go for it?
Obfuscate the content
This will prevent the user from editing the file directly, but it won't stop them as soon as the obfuscation algorithm is known.
var plaintext = Encoding.UTF8.GetBytes("Hello, world.");
var encodedtext = Convert.ToBase64String(plaintext);
Save the ciphertext to the file, and reverse the process when reading the file.
Sign the content
This will not prevent the user from editing the file or seeing its content (but you don't care, an high-score is not secret) but you'll be able to detect if the user tampered with it.
var key = Encoding.UTF8.GetBytes("My secret key");
using (var algorithm = new HMACSHA512(key))
{
var payload = Encoding.UTF8.GetBytes("Hello, world.");
var binaryHash = algorithm.ComputeHash(payload);
var stringHash = Convert.ToBase64String(binaryHash);
}
Save both the payload and the hash in the file, then when reading the file check if the saved hash matches a newly computed one. Your key must be kept secret.
Encrypt the content
Leverage .NET's cryptographic libraries to encrypt the content before saving it and decrypt it when reading the file.
Please take the following example with a grain of salt and spend due time to understand what everything does before implementing it (yes, you'll be using it for a trivial reason, but future you β or someone else β may not). Pay special attention on how you generate the IV and the key.
// The initialization vector MUST be changed every time a plaintext is encrypted.
// The initialization vector MUST NOT be reused a second time.
// The initialization vector CAN be saved along the ciphertext.
// See https://en.wikipedia.org/wiki/Initialization_vector for more information.
var iv = Convert.FromBase64String("9iAwvNddQvAAfLSJb+JG1A==");
// The encryption key CAN be the same for every encryption.
// The encryption key MUST NOT be saved along the ciphertext.
var key = Convert.FromBase64String("UN8/gxM+6fGD7CdAGLhgnrF0S35qQ88p+Sr9k1tzKpM=");
using (var algorithm = new AesManaged())
{
algorithm.IV = iv;
algorithm.Key = key;
byte[] ciphertext;
using (var memoryStream = new MemoryStream())
{
using (var encryptor = algorithm.CreateEncryptor())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
using (var streamWriter = new StreamWriter(cryptoStream))
{
streamWriter.Write("MySuperSecretHighScore");
}
}
}
ciphertext = memoryStream.ToArray();
}
// Now you can serialize the ciphertext however you like.
// Do remember to tag along the initialization vector,
// otherwise you'll never be able to decrypt it.
// In a real world implementation you should set algorithm.IV,
// algorithm.Key and ciphertext, since this is an example we're
// re-using the existing variables.
using (var memoryStream = new MemoryStream(ciphertext))
{
using (var decryptor = algorithm.CreateDecryptor())
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
using (var streamReader = new StreamReader(cryptoStream))
{
// You have your "MySuperSecretHighScore" back.
var plaintext = streamReader.ReadToEnd();
}
}
}
}
}
As you seem to look for relatively low security, I'd actually recommend going for a checksum. Some pseudo-code:
string toWrite = score + "|" + md5(score+"myKey") + Environment.NewLine
If the score would be 100, this would become
100|a6b6b0a8e56e42d8dac51a4812def434
To make sure the user didn't temper with the file, you can then use:
string[] split = readString().split("|");
if (split[1] != md5(split[0]+"myKey")){
alert("No messing with the scores!");
}else{
alert("Your score is "+split[0]);
}
Now of course as soon as someone gets to know your key they can mess with this whatever they want, but I'd consider that beyond the scope of this question. The same risk applies to any encryption/decryption mechanism.
One of the problems, as mentioned in the comments down below, is that once someone figures out your key (through brute-forcing), they could share it and everybody will be able to very easily change their files. A way to resolve this would be to add something computer-specific to the key. For instance, the name of the user who logged in, ran through md5.
string toWrite = score + "|" + md5(score+"myKey"+md5(System.username /**or so**/)) + Environment.NewLine
This will prevent the key from being "simply shared".
Probably your best bet is securing the whole file using standard NT security and programmatically change the access control list to protect the whole file from being edited by unwanted users (excepting the one impersonating your own application, of course).
Cryptography can't help here because the file could be still editable using a regular text editor (for example, notepad) and the end user can corrupt the file just adding an extra character (or dropping one too).
There's an alternate approach which doesn't involve programming effort...
Tell your users that once they've manually edited the whole text file they've lost your support. At the end of the day, if you're storing this data is because it's required by your application. Corrupting it or doing the risky task of manually editing it can make your application produce errors.
Another alternate approach which involves programming effort...
Whenever you change the file from your application, you can compute a MD5 or SHA hash and store in a separate file, and once you want to read or write it again, you're going to check that the whole file produces the same hash before writing on it again.
This way, the user can still edit your file manually, but you'll know when this unexpected behavior was done by the user (unless the user also manually computes the hash whenever the file is changed...).
Something I have not yet seen mentioned is storing the high score on an online leader board. Obviously this solution requires a lot more development, but since you are talking about a game, you could probably make use of a third party provider like Steam, Origin, Uplay, ... This has the added advantage of leader boards not just being for your machine.
You cannot save data in a dll, and both Resource file and txt file are editable. It sounds like encryption is the only way for you. You can encrypt the string before saving it to a txt file. Take a look at this thread:
Encrypt and decrypt a string
You can serialize it and deserialize with encryption with CryptoStream :
Serialize file :
Create and open FileStream in write mode
Create Cryptostream and pass your filestream
Write contents to Cryptostream (encrypt)
Deserialize file :
Create and open FileStream in read mode
Create Cryptostream and pass your filestream
Read from Cryptostream (decrypt)
You can find examples and more information here :
msdn.microsoft.com/en-us/library/system.security.cryptography.cryptostream.aspx
http://www.codeproject.com/Articles/6465/Using-CryptoStream-in-C
Example :
byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8 }; // Where to store these keys is the tricky part,
byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
string path = #"C:\path\to.file";
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
// Encryption and serialization
using (var fStream = new FileStream(path, FileMode.Create, FileAccess.Write))
using (var cryptoStream = new CryptoStream(fStream , des.CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
BinaryFormatter serializer = new BinaryFormatter();
// This is where you serialize your data
serializer.Serialize(cryptoStream, yourData);
}
// Decryption
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (var cryptoStream = new CryptoStream(fs, des.CreateDecryptor(key, iv), CryptoStreamMode.Read))
{
BinaryFormatter serializer = new BinaryFormatter();
// Deserialize your data from file
yourDataType yourData = (yourDataType)serializer.Deserialize(cryptoStream);
}
Simple solution:
To mitigate the hackish user ability to change the score, you can write it as a binary I guess.
Another solution:
Write the data in a SQLite DB?
You can name your file as something that doesn't suggest it has a score table in it (e.g. YourApp.dat) and encrypt the contents.
The accepted answer here contains the code for encryption and decryption of text.
Update
I also suggest using some Guid as a password for the encryption.
You can't write in Resources, more information exists in this answer
The reason that you can't change a resource string at runtime, is
because the resource is compiled into your executable. If you reverse
engineer the compiled *.exe or *.dll file, you can actually see your
string in the code. Editing an already compiled executable file is
never a good idea (unless you're trying to hack it), but when you try
to do it from the executables code, it just plain impossible, as the
file is locked during execution.
You can add Read Only or Hidden attributes to your files using
File.SetAttributes, But still user can remove the attributes
from windows and edit the file.
An example:
File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
Another way I could suggest is to save the data in a file with some
weird extensions so that the user can't think of it as an editable or
important file. somthing like ghf.ytr (Can't think of somthing
more weird right now!)
I'd also suggest making a text file with .dll extension and saving it in one of windows folders like system32. This way user will have a really hard time trying to find out where does the score information go!
Here is a code to make an text file not editable. in the same way you use this technique to make it not readable etc.
string pathfile = #"C:\Users\Public\Documents\Filepath.txt";
if (File.Exists(pathfile))
{
File.Delete(pathfile);
}
if (!File.Exists(pathfile))
{
using (FileStream fs = File.Create(pathfile))
{
Byte[] info = new UTF8Encoding(true).GetBytes("your text to be written to the file place here");
FileSecurity fsec = File.GetAccessControl(pathfile);
fsec.AddAccessRule(new FileSystemAccessRule("Everyone",
FileSystemRights.WriteData, AccessControlType.Deny));
File.SetAccessControl(pathfile, fsec);
}
}
I'm having trouble copying a file and then verifying the integrity of the file afterward. I've tried every file copying method I can think of (File.Copy, filestreams, trying to do a binary copy) but the file hash is always different after the copy. I've been searching around and I notice a lot of people saying that copying a file from a network share can cause this but I get the same results from shares as I do just straight from my hard drive.
//File hashing method:
private byte[] hashFile(string file)
{
try
{
byte[] sourceFile = ASCIIEncoding.ASCII.GetBytes(file);
byte[] hash = new MD5CryptoServiceProvider().ComputeHash(sourceFile);
return hash;
...
Using this method the origional file and the copied file always produce the same hash (individually) through every run but the two hashes are not the same. Does anyone know of a way to copy files without changing the file hash?
I Think you are Hashing the FileName .. and not Content !
so sure it wont compute as same!
check the Value and Length of file and byte[] sourceFile
It seems you are passing the filename instead of the file contents to the hash function.
Use something like this:
byte[] hash = md5.ComputeHash(File.ReadAllBytes(filename));
Or this:
using (var stream = File.Open(filename)) {
byte[] hash = md5.ComputeHash(stream);
}
I have a flash app which sends raw data for a jpg image to a particular url Send.aspx . In Send.aspx I am using request.binaryread() to get the total request length and then read in the data to a byte array.
Then I am writing the data as jpg file to the server. The code is given below:
FileStream f = File.Create(Server.MapPath("~") + "/plugins/handwrite/uploads/" + filename);
byte[] data = Request.BinaryRead(Request.TotalBytes);
f.Write(data, 0, data.Length);
f.Close();
The file is getting created but there is no image in it. It always shows up as empty in any graphic viewer. What part am I missing. Am I supposed to use jpg encoding first before writing it to file? Thanks in advance
Well, you should use a using statement for your file stream, but other than that it looks okay to me.
A few suggestions for how to proceed...
Is it possible that the client isn't providing the data properly? Perhaps it's providing it as base64-encoded data?
Have you already read some data from the request body? (That could mess things up.)
I suggest you look closely at what you end up saving vs the original file:
Are they the same length? If not, which is longer?
If they're the same length, do their MD5 sums match?
If you look at both within a binary file editor, do they match at all? Any obvious differences?