-
[RESOLVED] how can i encrypt a file?
what i want to do is open a file using my application only, i have a winforms program created in c++/cli. my program will call and open a specific file when a user enters the right credentials. at the moment i am using the system() function to do this.
system("C:\\Users\\katy\\Desktop\\monk.drn.txt");
my problem is that this file can be opened by any other app. so what i was told to do was to create a file extension, so that when that file is clicked only my program will open, which i did.*** however this didnt actually work has i first thought it would, because when the user logged in, the system() function opened the file, which then ran my program again....(because my program is associated with the file) which is not what i wanted. i want if the user clicks the file > my program opens> they log in> the file shows.
anyways i found that by using the file extension that a user can go through another root and open and view the file in other apps such as word etc.....so then i decided to go for encrypting the file. however i wasnt sure how encrypting and decrypting the file would work in my program because its a login program, i have tried the encrypt and decrpyt functions msdn doc showed but that didnt work, is there an alternative method of doing this can anyone help please???
-
Re: how can i encrypt a file?
:eek: Actually, the title of this thread scared me a bit because cryptography is a really vast field and even understanding some clearly delimited parts of it may require in-depth knowledge of quite complex concepts.
But the first idea that came to my mind after reading your post doesn't even have to do with cryptography itself at all, at least not at application level: Why not simply set the access permissions to the file in question so that only authorized users can gain access to it? Of course that would change the sequence of steps required to get to the file: They log into Windows with appropriate credentials > start your app (which actually may be unrestricted) > open the file (which is restricted to certain users).
But the threads you started recently suggest that your app itself is targeted to access control and maybe cryptography, so that may not be the approach you want. A simple MSDN search for ".NET encrypt" yields slightly below 700k hits, the first of which leads to an article on codeproject.com whose title contains the promising word "Simplified". I didn't actually read the article and the code samples it contains are VB .NET which probably is not your language, but it may still be worth a look.
Some more "creative clicks" (i.e. not just simply clicking on links in front of me) took me to the MSDN article on Cryptographic Services which also looks like a good point to start from. But again, be warned it's a really vast topic.
I didn't even dare to start a Google search on that because it certainly would spit out literally millions of hits... ;)
HTH
-
Re: how can i encrypt a file?
Thanks Eri523 il give the Cryptographic Services ago.
-
Re: how can i encrypt a file?
hi, i have looked and read Cryptographic Services but i have no idea how to use that for my program, its quite advanced, i just wanted something simple like the IO encryption method. i have searched online for something similar to it but had no luck. :(
-
Re: how can i encrypt a file?
I suggest you grab this cryptographic library:
http://www.cryptopp.com/
This page
http://www.codeguru.com/cpp/misc/mis...le.php/c11953/
provides a very simple example of how to use it to encrypt and decrypt. Once you get that sample code working, you should be able to then wrap it into your own code easily.
-
Re: how can i encrypt a file?
sorry i have read about cryto++ and i dont think it applies to my program.
background: i have been given an assignment from college to create a username and password login system. the login system has to be used to protect a file that is important to a user.
my program works so far the user can enroll and then login: enrollment involves the user entering a desired username and password, these then get stored in a database (Access). login: is when they enter the username and password they enrolled with, which then gets compared to the one in the database if there is a match my program will the open the file. like i said before at the moment to demonstrate that my program can open a file, i have used the system() function which opens any document i.e doc, txt etc.
system("C:\\Users\\katy\\Desktop\\monk.drn.txt"); <-------opens when the user enters the correct username and password.
my problem is that the file can also be opened and the content viewed by other apps. hence why i want to encrypt. what is the best and easiest encryption method. i have been searching google for 2 days now and have had no luck
-
Re: how can i encrypt a file?
In the meantime I hacked together a minimalistic encryption/decryption sample program (console type) for files which uses .NET's cryptographic services. I would say this is really the bare minimum needed and I can't simplify it any more, IOW make it less advanced.
Here it goes:
Code:
// CryptEx1.cpp: Hauptprojektdatei.
// Cryptography example
#include "stdafx.h"
using namespace System;
using namespace System::IO;
using namespace System::Security::Cryptography;
int main(array<System::String ^> ^args)
{
// Validate command line arguments:
if (args->Length != 4 || String::Compare(args[0], "encrypt", true) && String::Compare(args[0], "decrypt", true)) {
Console::WriteLine("Usage: CryptEx1 <encrypt|decrypt> <password> <input file> <output file>");
return 1;
}
// Create key from password:
// Salt array simply copied from
// http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes.aspx:
array<Byte>^ abSalt = gcnew array<Byte>{0x00,0x01,0x02,0x03,0x04,0x05,0x06,0xF1,0xF0,0xEE,0x21,0x22,0x45};
Rfc2898DeriveBytes ^keygen = gcnew Rfc2898DeriveBytes(args[1], abSalt);
array<unsigned char> ^achKey = keygen->GetBytes(32); // Key length: 32 bytes
// Create crypto algorithm object, set the key and create crypto transformer:
AesManaged ^cryptalg = gcnew AesManaged();
array<unsigned char> ^achIV = gcnew array<unsigned char>(16);
Array::Clear(achIV, 0, achIV->Length); // Set up all-zero initialization vector
cryptalg->IV = achIV; // ... not sure why this is required or whether it's really a good idea... :o
cryptalg->Key = achKey;
ICryptoTransform ^cryptrans;
if (!String::Compare(args[0], "encrypt", true))
cryptrans = cryptalg->CreateEncryptor();
else // Decrypt
cryptrans = cryptalg->CreateDecryptor();
// Open files:
FileStream ^fInput;
try {
fInput = gcnew FileStream(args[2], FileMode::Open, FileAccess::Read);
}
catch (Exception ^e) {
Console::WriteLine("Failed to open input file {0}, reason: {1}", args[2], e->Message);
return 1;
}
FileStream ^fOutput = gcnew FileStream(args[3], FileMode::Create, FileAccess::Write);
// Create crypto stream (filter) attached to the input file:
CryptoStream ^cryptstream = gcnew CryptoStream(fInput, cryptrans, CryptoStreamMode::Read);
// Process (i.e. encrypt or decrypt) data while copying from input file to output file:
try {
cryptstream->CopyTo(fOutput);
}
catch (Exception ^e)
{
Console::WriteLine("Error encountered during encryption/decryption: {0}", e->Message);
return 1;
}
// Close all streams involved:
cryptstream->Close();
fOutput->Close();
fInput->Close();
// That's all folks.
return 0;
}
Do you get the point, Katy? If you have open questions feel free to ask, though I must admit that I'm no real expert on cryptography either.
Be careful if you test that program with real-life data: It will overwrite a pre-existing output file without any warning and leave a garbled output file if invoked to decrypt with the wrong password.
Be aware that if you use the user's password to generate the key (a method that this demo program suggests), the decrypted file will be user-dependent, i.e. no other user can decrypt it. If multiple users would need to access the same file that way, you would need to store an individual encrypted version of the file for each of them.
Of course, you also can apply the encryption algorithm discussed in the thread "problem creating decode function" to files, but I already warned you that it is really, really, really weak.
Another bad idea is hard-coding the key in your program, as any more or less talented hacker could easily retrieve it from there.
Moschops, I only had a prief peek on the CodeGuru article you linked to, and it looked quite interesting. Thanks! :) As I understood it, the crypto library itself is native, but comes with some sort of managed wrapper. Do you have any experience with using it in a managed environment?
And, BTW, would using it really be simpler that what I posted above?
-
Re: how can i encrypt a file?
hey thanks. am i supposed to incllude any additional libs? because i get the following errors:
error C2039: 'CopyTo' : is not a member of 'System::Security::Cryptography::CryptoStream'
error C2061: syntax error : identifier 'AesManaged'
error C2065: 'AesManaged' : undeclared identifier
error C2065: 'cryptalg' : undeclared identifier
error 2065: 'cryptalg' : undeclared identifier
error C2065: 'cryptalg' : undeclared identifier
error C2065: 'cryptalg' : undeclared identifier
error C2065: 'cryptalg' : undeclared identifier
error C2227: left of '->CreateDecryptor' must point to class/struct/union/generic type
error left of '->CreateEncryptor' must point to class/struct/union/generic type
error C2227: left of '->IV' must point to class/struct/union/generic type 31
error C2227: left of '->Key' must point to class/struct/union/generic type
also where do i put the file string path: to find the file to be encrypted?
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
katy_price
sorry i have read about cryto++ and i dont think it applies to my program...
what is the best and easiest encryption method. i have been searching google for 2 days now and have had no luck
Perhaps I'm just mis-understanding your question; Crypto++ is a very simple and easy way to encrypt a file that is very portable and very easy to use. How does that not apply to your need to encrypt something in an easy way?
The "best" encryption method (to my knowledge) involves using a one-time pad, but that would be utterly useless for your needs.
Anyway, with regards to "error C2039: 'CopyTo' : is not a member of 'System::Security::Cryptography::CryptoStream' "
Are you using the version listed here?
http://msdn.microsoft.com/en-us/libr...ptostream.aspx
Where the CopyTo is as defined here?
http://msdn.microsoft.com/en-us/library/dd782932.aspx
Seems the CopyTo class method for this class only exists in .Net 4
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
Eri523
Moschops, I only had a prief peek on the CodeGuru article you linked to, and it looked quite interesting. Thanks! :) As I understood it, the crypto library itself is native, but comes with some sort of managed wrapper. Do you have any experience with using it in a managed environment?
And, BTW, would using it really be simpler that what I posted above?
Hiya Eri.
I'm a big fan of Crypto++. I find it does a good job in abstracting away the frankly pretty tricksy details of encryption and decryption. When I look at your code and the sample I pointed to, I find them to about the same level of complexity, but I've no doubt that someone very used to the MS .net environment would find yours easier to get to grips with, and of course someone else with different experience might find the crypto++ to be easier. I'd tend towards the Crypto++ for actual use, but only because I trust it more in terms of encryption security than the MS provided libraries.
In a managed environment, I couldn't say, to be honest. It's solid C++ code with nothing OS dependent; no reason why it couldn't be wrapped into an MS Managed C++ environment, but I've never done it. Most (in fact, for the past few years, all) of what I write daily has to be portable across various platforms so I've no experience of the managed environment.
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
Moschops
Seems the CopyTo class method for this class only exists in .Net 4
thanks i ran it vs 2010 it compiles but i get this exception:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in kl.exe
Additional information: Index was outside the bounds of the array. on this line
Code:
Rfc2898DeriveBytes ^keygen = gcnew Rfc2898DeriveBytes(args[1], abSalt);
.
plus where/how does this code encrypt a file when there is no file path? i am confused. what i want to do is encrypt a file in one program, then use my login program to open and decrypt that file. sorry does this make sense? can you help me do this please?
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
katy_price
hey thanks. am i supposed to incllude any additional libs? because i get the following errors:
[...]
The program compiled with default project settings on my VC++ 2010 Express and both the offending classes/methods AesManaged and CryptoStream::CopyTo() are defined in mscorlib, so no additional references to runtime assemblies should be needed. And actually only these two are problematic, the rest are consequential errors.
As to the Windows version: Both should be available on XP SP3 and up, Vista SP1 and up, and of course any variant of 7. But the problem seems to be the .NET Framwork version: AesManaged needs at least 3.5 and CryptoStream::CopyTo() has the highest requirements, it is only available in .NET 4.
And especially CryptoStream::CopyTo() is a really helpful tool in this program: Without it the neat one-line copy procedure would need to be replaced by a much more convoluted loop (OTOH not really that complicated either).
So I strongly suspect you are using a VC++ version before 2010 because 2010 comes packaged with .NET 4. Therefore my question to anyone who knows (because I don't :o): Would installing .NET 4 be enough and would it cooperate with whatever version of VC++ Katy has, or would she need to switch to a newer version of VC++?
Quote:
also where do i put the file string path: to find the file to be encrypted?
This is a "pure" command line program, requiring no extra console input at all. That means the program takes all its information from the command line. It displays a usage message when invoked without command line parameters (or with parameters that are so obviously wrong that it can be detected in the first line of main() that actually generates code) and would be used by entering a command line like this one:
Code:
cryptex1 encrypt My123Password test.txt test.txt.encrypted
But of course you first would need a version of the program that works... :o
Quote:
Originally Posted by
Moschops
The "best" encryption method (to my knowledge) involves using a one-time pad, but that would be utterly useless for your needs.
Well, you probably know that though it actually is proven to be unbreakable it is only of theoretical use because it needs a private key of the same size as the plaintext that needs to be transmitted over a secure channel in order to use it. And if you would be able to do that, you could send the plaintext over that channel in the first place... ;) :D
-
Re: how can i encrypt a file?
i found this example. It creates a file which has the
sample string in it with a simple masking operation
performed on the data first. Then it reads it back
and unmasks it so it can restore the original contents.
i would like help to convert it so it reads through each character in the text and converts it, instead of creating the string in the code and converting it. i just dont know where to start. can you give me some pointers please.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
char mask(char ch)
{
return ch = ~ch;
}
int _tmain(int argc, _TCHAR* argv[])
{
string str("text to change.\n1234567890\n");
ofstream ofs("testdata.txt",ios::binary);
if(!ofs)
{
cout << "Can't open output file!\n";
return -1;
}
string str2;
str2.resize(str.size());
transform(str.begin(), str.end(), str2.begin(), mask);
ofs << str2; // add error checks
ofs.close();
ifstream ifs("testdata.txt",ios::binary);
if(!ifs)
{
cout << "Can't open input file!\n";
return -1;
}
str.clear();
ifs >> str; // add error checks
// cout << str << endl;
str2.clear();
str2.resize(str.size());
transform(str.begin(), str.end(), str2.begin(), mask);
cout << str2 << endl;
return 0;
}
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
Moschops
[...]
Seems the CopyTo class method for this class only exists in .Net 4
Quote:
Originally Posted by
katy_price
thanks i ran it vs 2010 it compiles [...]
Oops! You were both quicker than me... :)
Quote:
[...] but i get this exception:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in kl.exe
Additional information: Index was outside the bounds of the array. on this line
Code:
Rfc2898DeriveBytes ^keygen = gcnew Rfc2898DeriveBytes(args[1], abSalt);
That line shouldn't be reached at all if you invoke the program without command line parameters. :confused: But if it is actually reached, args[1] is out of range of course.
I was so confident that there was no bug in the simple part of the code that checks this that I didn't test this case in the first place. I now have tested it and it works as expected with the version I have here. Don't know what could be different in your version... :ehh:
Quote:
plus where/how does this code encrypt a file when there is no file path? i am confused. what i want to do is encrypt a file in one program, then use my login program to open and decrypt that file. sorry does this make sense? can you help me do this please?
That should have been answered in post #12.
Quote:
Originally Posted by
katy_price
i found this example. [...]
The "encryption" algorithm used by that program is as weak as the one we discussed in the thread I linked to in post #7. I seriously would recommend against using it.
And please get back into the habit of using code tags... ;)
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
Eri523
if you invoke the program without command line parameters. :confused: But if it is actually reached, args[1] is out of range of course.
sorry what do you mean by this? do i have to change something in the code. i dont actually understand this program. how do i decrypt the file. plus i get the exception so really i can't use it.
Quote:
The "encryption" algorithm used by that program is as weak as the one we discussed in the thread I linked to in post #7. I seriously would recommend against using it.
i think i would like to use this one though because i understand what its doing, i just don't know how to implement it into my program and make it work the way i need it to. i want to separate the encrypt and decrypt sections, i want to put the encrypt code in a separate program and use the decrypt code in my actuall login program. i dont know how to change the code so it encrytps and decrypts the whole text in a file. can you help please
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
katy_price
sorry what do you mean by this? do i have to change something in the code.
I don't think you should need to change something in the code. (But maybe something actually got changed on the program's way to you and you may need to revert that.) As I already said above, that shouldn't happen when the program is invoked without command line parameters. Or are you actually invoking it with some parameters when that happens? If so, please tell me what they are, as exact as possible, so I can debug that problem myself. I feel obliged to correct that bug if it is one, since it's my program.
Quote:
i dont actually understand this program. how do i decrypt the file. plus i get the exception so really i can't use it.
I already posted a command line to encrypt a file in post #12. Maybe you got confused by "test.txt.encrypted"? That's just a file name with an unusually long file name extension. Assuming .cry as the extension for the encrypted file (which is non-standard as well but looks more familiar), the command line to encrypt the file test.txt would look like this:
Code:
cryptex1 encrypt My123Password test.txt test.cry
To decryt the file again, you would use something like:
Code:
cryptex1 decrypt My123Password test.cry test_decrypted.txt
Clear now?
Quote:
i think i would like to use this one though because i understand what its doing, i just don't know how to implement it into my program and make it work the way i need it to.
I really don't like that idea but if you insist on it... :rolleyes: I assume your app is no real-life app anyway.
Quote:
i want to separate the encrypt and decrypt sections, i want to put the encrypt code in a separate program and use the decrypt code in my actuall login program.
The algorithm used in that program uses some sort of "built-in key" that is the same for both encryption and decryption. But beyond that, what makes up a symmetric encryption, this algorithm also uses the identical program code for both encryption and decryption. Therefore it can be called something like a "super-symmetrical encryption" but that term doesn't really exist.
Quote:
i dont know how to change the code so it encrytps and decrypts the whole text in a file.
This algorithm is used much the same like the algorithm we already discussed in our earlier thread. You just use a binary NOT instead of addition and subtraction for both encryption and decryption.
To apply the algorithm to an entire file it's best to see the data as a sequence of bytes instead of a string, i.e. a binary file rather than a text file. I usually don't recommend that, but if the files are not too large you can make your life easier by reading the entire file into a single array<Byte>, apply the binary NOT to each and every single byte and finally write it back. That's all.
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
Eri523
Oops! You were both quicker than me... :)
I was so confident that there was no bug in the simple part of the code that checks this that I didn't test this case in the first place.
i ran your program but the command window closes straightaway. i have tried using system("PAUSE"); so i can see what message is showing but that doesnt work, however i can just make out what it says just before it closes.
Code:
Console::WriteLine("Usage: CryptEx1 <encrypt|decrypt> <password> <input file> <output file>");
.
i still actually dont understand how this would work with my program. i understand the encryption part, because then i will have an encrypted file for my program to decrypt. but how will the decryption part of this code work in my program? my program is meant to be used to open and decrypt the file when the user logs in with their enrolled username and password. i cant see how this decryption in this program will work in my program as my program is not run on console
-
Re: how can i encrypt a file?
i debugged your program and it doesnt go past this section of code.
Code:
if (args->Length != 4 || String::Compare(args[0], "encrypt", true) && String::Compare(args[0], "decrypt", true)) {
Console::WriteLine("Usage: CryptEx1 <encrypt|decrypt> <password> <input file> <output file>");
return 1;
}
i can't type anything in the command window.
i dont know if i am explaining what i want correctly. basically all i want to show is that my program can, when a user logs in, open and decrypt a file that was encrypted. lets say i encrypt a file using this code. Then if a user wants to view the content of that file then they would need to use my program to do it, they will need to enter their username and password. the file will then open and appear to them in the decyprted mode (readable) as my program would have decrypted it when they entered their correct credentials (which was stored in the database when they enrolled). i dont want console use my program uses winforms. i can understand erypting it using the command line but the user will be the one to decrypt it using my login program. the only reason i am using encryting it is to make sure the file content is not readable in other apps. is what i want to do possible?? if you have any other ideas on how i can go about doing this please say. thanks.
p.s the only reason why i'm suggesting i need two programs is because i dont know if what i want to do is possible if i have just my Login program doing both the encryption and decryption. because the file would only they be encrypted during the course of run time just like the decrypted file, if i'm wrong please say.
-
Re: how can i encrypt a file?
You are using the program incorrectly.
This is a "command line" or "console" program. You run it by opening a "command line" or "console". If you're using some kind of Windows, I expect the command line is tucked away under accessories or something similar. If you can't find it, you can run "command" directly in whatever Windows uses these days to let you run commands. Probably something like that windows key and "r", unless the ability to run commands of your choice has been revoked in the latest version. I wouldn't be surprised.
Once you have a command window (it will probably be a window with a black background and white text, with something like "C:\" and a little flashing cursor), you can start typing.
Then, if you change directory using the "cd" command to wherever you put the program you made, you can run it by typing
"CryptEx1 <encrypt|decrypt> <password> <input file> <output file>"
where you have a choice between encrypt and decrypt, and have to fill in the rest. For example, you might type exactly the following:
CryptEx1 encrypt yourPassword fileToEncrypt.txt nameOfOutputFile.txt
That would encrypt, with the password "yourPassword" the file called "fileToEncrypt.txt" and create a file called "nameOfOutputFile.txt" which would be the encrypted file.
However, you don't want a console driven program. That's fine, but I think you need to think more about what you DO want.
As I see it, your decrypt programme needs to do the following:
Confirm password is correct.
Fetch name of file from user.
Open file.
Read in and apply decryption.
Display file.
If the whole purpose is just to show that you can do this, then you don't need to use "real" encryption and you can just hardcode the acceptable password and login into your code. It's not very safe, but if this is just an exercise in reading and manipulating data, then actually using a hardcore encryption library and protecting the password is not important. You can just do something very simple to the file. If it's a text file, you could just remove every space and put some other character in there that's not used elsewhere in the text file, and call that your encryption. This would remove completely the need to use the encryption libraries you're struggling with.
So now, your encryption code reads something like this:
Get name of file from user.
Open file, read in a character.
If character is " ", change to "¬"
Write out character to new file.
When read all characters, close files.
Your decryption code is something like this:
Get name of file from user.
Ask user for password.
If password is not correct, end here.
Open file, read in a character.
If character is "¬", change to " "
Write out character to new file.
When read all characters, close files.
Open new file and display text to user.
-
Re: how can i encrypt a file?
Thanks for jumping in, Moschops. I am already close to desperation while trying to find even more ways to explain the simple task of invoking a command line tool... :(
Your assumptions about the Windows command shell are mainly correct except that the command shell nowadays is called cmd instead of command. While command actually is still available, it has severe drawbacks, just to mention the lack of long filename support now.
Katy, system("pause"); actually is of limited use in this program because its main() function has a total of four exit points (all these return statements) instead of one. Actually it uses the console only to output error messages, so if the program finishes and nocthing went wrong, you'll see no console output coming from it at all.
Actually, you can use that command line tool from your application, either using system() with an appropriately constructed command string (which has the disadvantage of opening a console window), ShellExecute() or any .NET-style equivalent, which probably exists, I just don't know it.
But especially because of the fact that this program uses the console to only output error messages, it shoulcn't be too difficult to port it into a C++ function (or method) that encapsulates all that crypto stuff.
-
Re: how can i encrypt a file?
I will not begin my monologue about how the kids are taught to code at school these days starting at the level of a GUI instead of a command line. This is not the time or place :p Thanks for correcting my mistakes regarding the renaming of "command" to "cmd". I haven't been forced to use Windows since the days of WinXP so I'm a bit out of touch.
I forgot to ask; Katy, is this an exercise for educational purposes, or do you need to actually make something to use? If you actually need to make something work, can you not just zip the file up using a password? That would solve all your problems in an effective, free and portable way.
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
Moschops
You are using the program incorrectly.
So now, your encryption code reads something like this:
Get name of file from user.
Open file, read in a character.
If character is " ", change to "¬"
Write out character to new file.
When read all characters, close files.
Your decryption code is something like this:
Get name of file from user.
Ask user for password.
If password is not correct, end here.
Open file, read in a character.
If character is "¬", change to " "
Write out character to new file.
When read all characters, close files.
Open new file and display text to user.
this is too simple. i would like to use the code i posted in post #13 . i just wanted help incorporating the decryption part in my program as it uses command too. i am not going to bother ask a user for a file, i am going to use a default filename of my choice that i specify in my program to decrypt. (this file will already need to be encrypted), which i would have done in a seperate program. the username and password that the user enrolled with will be the key to open and view the file content (providing they enter the name and password they enrolled with. i am running out of time i cant now fit in users choosing their own file name they wish to encrypt (however this would be done during enrollement) and then login would be to dercypt (the key would be their username and password). this would be ideal so each user would have their own files they want to encrypt and decrypt to view them. if any off you have any suggestions on how i can do this quickly please say. bearing in mind i am still new to programming and may need some examples preferably ones that i can integrate in my program. thanks
if i was to use the file name the user enters during enrollment how would the file remain encrypted if the user edits it? in essence what i want to do during the enrollment stage is this:
Open the file to be masked as input.
Open an output file.
Loop reading the input file a character at a time.
Mask each character read and write it to the output file.
When EOF is reached on input:
Close both files.
Delete the original file.
Rename the output file as the original.
all this using the program posted in post 13.
i dont know what to do for decryption - login stage
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
Moschops
I haven't been forced to use Windows since the days of WinXP so I'm a bit out of touch.
I'm actually using XP (Pro SP3) myself here right now, and the transition from command to cmd has already been done there.
Although the zip encryption isn't really secure either, using it looks like a really elegant idea to me here. I, myself, don't know how to zip and unzip files programmatically without using 3rd-party tools, however.
Katy, if the encryption itself is not part of the assignment (please be honest... :D) and you're really short of time, I'm willing to do the port of the sample program into a C++ function for you. You will then see how similar the two actually are. (Actually, the laziest way to port it would be to simply rename the main() function and remove/comment the console output statements, but then it would have an interface that wouldn't be really appropriate for an easy-to-handle C++ function.)
I'm not willing to promise anything more for now, though.
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
Eri523
Although the zip encryption isn't really secure either, using it looks like a really elegant idea to me here.
The latest version has some pretty serious AES options and is now approved for use by various quite serious chaps. It does still have the less secure options too, though.
-
Re: how can i encrypt a file?
[QUOTE=Eri523;1987893]
Katy, if the encryption itself is not part of the assignment (please be honest... :D) QUOTE]
it is a part of the assignment, how i do it is another matter. like i said it would make sense to have each user enter their own file they wish to encrypt during the enrollment process. somehow i will need to link the username and password the user enters to the file they wish to encrypt. so when they log in with that user name the file they entered during enrollment will be opened in a decrypt mode so they can view and edit its contents.....all this instead of having a default file name which i put in my program and open in decrypted mode. doing it this way would mean i would have to have two prgrams one to encrypt and my login program to decrypt, this file would then be availble to all users who enrolled and login. has i would only have one file (specified in the program itself).
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
Moschops
The latest version has some pretty serious AES options and is now approved for use by various quite serious chaps. It does still have the less secure options too, though.
Thanks for the update. :)
Quote:
Originally Posted by
katy_price
it is a part of the assignment, how i do it is another matter.
So, do you want a port of the sample program? If using it would be considered cheating be aware though that many teachers are prepared to find out if students copied something from the net.
Quote:
like i said it would make sense to have each user enter their own file they wish to encrypt during the enrollment process. somehow i will need to link the username and password the user enters to the file they wish to encrypt.
Why not simply make the file name part of the user record in your database?
Quote:
all this instead of having a default file name which i put in my program and open in decrypted mode. doing it this way would mean i would have to have two prgrams one to encrypt and my login program to decrypt, this file would then be availble to all users who enrolled and login. has i would only have one file (specified in the program itself).
If having a single file shared by all users wouldn't be a problem (I don't know what it is to be used for at all), then why not? Note that this would prevent you from generating the encryption key from the user's passowrd. You either would need to hard-code the key (not really recommended in real life, as stated above) or store it in some other central place.
Would using separate programs for encryption and decryption be a problem? If not, they could share common encryption/decryption code by simple copy and paste or they could share a common compilation unit containing the code, but that may require some advanced project settings.
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
Eri523
So, do you want a port of the sample program?
yes please, i don't know whats best...or safer. have one default file and all users can open and decrypt it when they log in (each having their own username and password) or have each user have their own specified files. which idea so you think is better in terms of design?
Quote:
Why not simply make the file name part of the user record in your database?
oh yea, lol. and then have them enter it again during login? i think this way will require alot of coding. with error handling etc. i think i will just have a default file name and every user can have access to it.
Quote:
You either would need to hard-code the key (not really recommended in real life, as stated above) or store it in some other central place
.
which one is the easiest to do lol? and what do you mean by central place a database?
Quote:
If not, they could share common encryption/decryption code by simple copy and paste or they could share a common compilation unit containing the code.
sorry but i dont know what you mean by this? any how, i've decided to have two programs one to encrypt and then my login program will open and decrypt the file when a user logs in. il need to specify the file path in my program. i just need some help with how to code the two processes (encryption/decryption). however i do think the simple encryption/decryption code i posted in post 13 is the best, i kinda understand what its doing, i just need to know how to integrate it into my program can you help in that way?
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
katy_price
yes please [...]
Ok, here it goes:
Code:
// CryptEx2.cpp: Hauptprojektdatei.
// Cryptography example, encapsulating the crypto functionality in a single function
#include "stdafx.h"
using namespace System;
using namespace System::IO;
using namespace System::Security::Cryptography;
/* The crypto function
The argument bMode determines whether to encrypt (true) or decrypt.
The return value indicates success (true) or failure. Of course this is the absolute
minimum of status information possible (except no status information at all).
*/
bool Crypt(String ^strInputFileName, String ^strOutputFileName, String ^strPassword, bool bMode)
{
// Create key from password:
// Salt array simply copied from
// http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes.aspx:
array<Byte>^ abSalt = gcnew array<Byte>{0x00,0x01,0x02,0x03,0x04,0x05,0x06,0xF1,0xF0,0xEE,0x21,0x22,0x45};
Rfc2898DeriveBytes ^keygen = gcnew Rfc2898DeriveBytes(strPassword, abSalt);
array<unsigned char> ^achKey = keygen->GetBytes(32); // Key length: 32 bytes
// Create crypto algorithm object, set the key and create crypto transformer:
AesManaged ^cryptalg = gcnew AesManaged();
array<unsigned char> ^achIV = gcnew array<unsigned char>(16);
Array::Clear(achIV, 0, achIV->Length); // Set up all-zero initialization vector
cryptalg->IV = achIV; // ... not sure why this is required or whether it's really a good idea... :o
cryptalg->Key = achKey;
ICryptoTransform ^cryptrans;
if (bMode) // Encrypt
cryptrans = cryptalg->CreateEncryptor();
else // Decrypt
cryptrans = cryptalg->CreateDecryptor();
// Open files:
FileStream ^fInput;
try {
fInput = gcnew FileStream(strInputFileName, FileMode::Open, FileAccess::Read);
}
catch (...) {
return false;
}
FileStream ^fOutput = gcnew FileStream(strOutputFileName, FileMode::Create, FileAccess::Write);
// Create crypto stream (filter) attached to the input file:
CryptoStream ^cryptstream = gcnew CryptoStream(fInput, cryptrans, CryptoStreamMode::Read);
// Process (i.e. encrypt or decrypt) data while copying from input file to output file:
try {
cryptstream->CopyTo(fOutput);
}
catch (...) {
return false;
}
// Close all streams involved:
cryptstream->Close();
fOutput->Close();
fInput->Close();
// That's all folks.
return true;
}
int main(array<System::String ^> ^args)
{
// Validate command line arguments:
if (args->Length != 4 || String::Compare(args[0], "encrypt", true) && String::Compare(args[0], "decrypt", true)) {
Console::WriteLine("Usage: CryptEx2 <encrypt|decrypt> <password> <input file> <output file>");
return 1;
}
// Call the do-all crypto function:
bool bCryptMode = !String::Compare(args[0], "encrypt", true);
if (!Crypt(args[2], args[3], args[1], bCryptMode)) {
Console::WriteLine("Some sort of error happened during encryption/decryption... :o");
return 1;
}
return 0;
}
The changes are simple, aren't they? :)
At first sight it might look easier to have wrapped the entire body of Crypt() into a single catch-all. I decided against that because that way it's easier to change the function to give more detailed status information. The consequence of this is, however, that not everything is caught, in particular failure to open the output file, the most likely reason of wich IMO are insufficient access permissions. So you should either take care that this doesn't happen in the first place or catch possible exceptions outside of Crypt() to avoid risking your app being terminated due to an uncaught exception.
Quote:
i don't know whats best...or safer.
Of course it's safest to rely on industry standard crypto technology, developed for you by people who know what they're doing. Provided, of course, that you're not required to know in detail what's going on inside the crypto black-box.
Quote:
have one default file and all users can open and decrypt it when they log in (each having their own username and password) or have each user have their own specified files. which idea so you think is better in terms of design?
That's not a matter of design. It's a matter of whether it's appropriate that all users share the same data.
Quote:
Quote:
Why not simply make the file name part of the user record in your database?
oh yea, lol. and then have them enter it again during login?
Not necessairily. You could have them pick the file during enrollment and leave its name unchanged later. Of course I don't know whether that's appropriate in your scenario. If you actually want them to be able to change the chosen file, that doesn't necessairily need to be done during login. If it's rarely needed you can bury it deeply within some menu hierachy or the like...
Quote:
i think i will just have a default file name and every user can have access to it.
Again, that depends on whether it's appropriate to have them share a single common file.
Quote:
Quote:
You either would need to hard-code the key (not really recommended in real life, as stated above) or store it in some other central place.
which one is the easiest to do lol?
Of course hard-coding the key is the simplest solution, and if security isn't really a concern you may decide to do that.
Quote:
and what do you mean by central place a database?
Especially I don't mean the user database if they all share a common file and hence need a common key. Of course, the most central place of all would be hard-coding the key in your app, and whether this really is an option depends on your security needs. Another possible option would be to store it in an application-specific configuration file, but that may open up a whole new can of worms... (You probably already have seen that I'm involved in an extensive thread about this around here... :D)
Quote:
Quote:
If not, they could share common encryption/decryption code by simple copy and paste or they could share a common compilation unit containing the code.
sorry but i dont know what you mean by this?
If you don't understand this, probably the best option is copy-paste. But then you need to take care that the two programs that are used always use the same crypto code and, in case it is hard-coded inside the programs, the same key.
Quote:
however i do think the simple encryption/decryption code i posted in post 13 is the best, i kinda understand what its doing, i just need to know how to integrate it into my program can you help in that way?
As what you're writing apparently is no real-life app you have the choice between all the crypto approaches discussed around here. I think I can recall at least four off the top of my head. Essentially, it seems to be mainly a matter of personal taste... :)
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
katy_price
hi, i have tried to run your code on its own in vs 2010 and the command window comes up and disappears right away. what is it supposed to do?
I'm really out of ideas how I might explain how to use this simple command line app. :(
Quote:
i still dont get how i can put this in my winforms app thats my issue. i jus wanted a encrypt function in a program that encypts the content of a file and then a function in my program that decrypts the content of the same file when a user logs in.
Maybe you should simply extract the Crypt() function from the second sample program, use it the way its interface suggests to use it and see what happens? :o
Quote:
i wanted you to help me convert the simple code in post #13 so that i can achieve this.
So I'd suggest that you first make an attempt of your own to port the crypt algorithm from post #13 into your program. If you can't even do this I don't know what to do anymore either.
I have offered you a black-box crypto solution (except the fact that you can look into the box and have the opportunity to understand what it does) and all you have to do is use it.
Quote:
the code you have seems a bit complicated and involves the command window. i mean like when in your code does the file name go? i dont get how this will work in my program at all.
The Crypt() function has no relation to the command line whatsoever. It takes two file names (input and output file) and I have tried to pick the parameter names so that their usage is obvious, at least after reading the comment that precedes the function definition.
I'm really starting to run out of ideas how to explain all this any further... :o :(
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
Eri523
It takes two file names (input and output file) and I have tried to pick the parameter names so that their usage is obvious
ok sorry think i'm a bit slow lol. do you mean i have to put my filenames in here
Code:
// Open files:
FileStream ^fInput;
try {
fInput = gcnew FileStream("john.txt", FileMode::Open, FileAccess::Read);
}
catch (...) {
return false;
}
FileStream ^fOutput = gcnew FileStream("can.txt", FileMode::Create, FileAccess::Write);
like i've put john.txt, am i required to have the full path? anyway this is still weird for me how do i serparate the dercyption code from the encryption as they are supposed to be in separate programs. also if it doesnt involve the console why does it say console::writeline?
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
katy_price
do you mean i have to put my filenames in here
Code:
// Open files:
FileStream ^fInput;
try {
fInput = gcnew FileStream("john.txt", FileMode::Open, FileAccess::Read);
}
catch (...) {
return false;
}
FileStream ^fOutput = gcnew FileStream("can.txt", FileMode::Create, FileAccess::Write);
No. It's easiest to consider the Crypt() function a black-box and leave it unchanged. Instead, you should pass the file names as parameters when you call it:
Code:
if (!Crypt("john.txt", "can.txt", "WhateverPassword", bCryptMode)) {
// Run away and cry...
return 1;
}
Of course you wouldn't hard-code neither the file names nor the password in your actual code but I hope you get the idea.
Quote:
like i've put john.txt, am i required to have the full path?
That depends on whether the file is located in the current working directory (CWD) of your app or not. If you're not sure it's alway better to use the fully qualified path; that would never do any harm if it's actually not needed.
Quote:
anyway this is still weird for me how do i serparate the dercyption code from the encryption as they are supposed to be in separate programs.
In the scenario we have here it's not really sensible to separate the encryption and decryption code. The two are so similar that they're best left together in a common function. Whether you actually want to encrypt or decrypt is determined by the bMode parameter you pass to Crypt().
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
Eri523
No. It's easiest to consider the Crypt() function a black-box and leave it unchanged. Instead, you should pass the file names as parameters when you call it:
Code:
if (!Crypt("john.txt", "can.txt", "WhateverPassword", bCryptMode)) {
// Run away and cry...
return 1;
}
Of course you wouldn't hard-code neither the file names nor the password in your actual code but I hope you get the idea.
why cant i do that how else would i get the file to open. where do i put it then. plus where do i put your code in my program for it to work? how will it know what file to encypt and decrypt if i dont put the file name in.
i am so confused i dont understand what your saying. plus would the file that is encrypted always be encrypted? even after i decrypt it? like after the user opens, sees the file edits it etc...and then closes it, does the encryted file remain encrypted even when edited?
do i put this in my main.cpp file? do i call the crypt function when the user enrolls/login? i dont totally understand. :(
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
katy_price
why cant i do that how else would i get the file to open. where do i put it then. [...] how will it know what file to encypt and decrypt if i dont put the file name in.
If you refer to opening the file for encryption/decryption, this is encapsulated inside the Crypt() function and this one just needs the file name to access the file. And, as I understand your design, you would leave opening the file for viewing/editing up to the associated application, e.g. Notepad for .txt.
And of course you indeed need to pass the file names to Crypt(), but you would most likely do that as a string variable, not a hard-coded string literal.
Quote:
plus where do i put your code in my program for it to work?
The best place to put it is the compilation unit (i.e. .cpp file) from where you call it, and most likely it would only be called from a single class or at least compilation unit. That way you don't need to prototype Crypt(). main.cpp would actually be about the worst possible place to put it, BTW.
Quote:
plus would the file that is encrypted always be encrypted? even after i decrypt it? like after the user opens, sees the file edits it etc...and then closes it, does the encryted file remain encrypted even when edited?
While the user views/edits the file you would have two copies of the file, one encrypted and one decrypted. It actually would not be a good idea to try to encrypt/decrypt the file in-place, i.e. passing the same file name as input file and output file to Crypt() because then the function would try to simultaneously read and write the same file which is pretty likely to fail. After the user has edited the file you would need to re-encrypt it because then the encrypted and decrypted copy of the file are out of sync.
There actually is a way of leaving the file encryped even while you edit it and handle encryption/decryption transparently: EFS. But I don't think this is applicable in your program.
Quote:
do i call the crypt function when the user enrolls/login?
Decrypting the file upon login of the user and re-encrypting it (possibly only in case the user actually changed it) upon logout is a natural option. Of course that would mean there is a decrypted copy of the file the entire time the user stays logged in, which I think isn't critical here. An option to only have a decrypted copy the minimum required time span would be to decrypt it just prior to opening it for viewing/editing and re-encrypting it right after that's finished, but depending on the way you open the file that may be complicated. From a security point of view this is safer, but IMO not really necessary in your app.
Quote:
i dont totally understand. :(
Just hold on! :thumb: I think we're really close now and will finaly get that sorted out, just like in all those other threads... :)
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
katy_price
do you mean pass a string like this?
Code:
system("C:\\Users\\katanya\\Desktop\\monk.drn.txt");
or is the above how i would open the file after i decrypt it like so (below)?
Code:
if (!Crypt("john.txt", "can.txt", "WhateverPassword", bCryptMode)) {
// Run away and cry...
return 1;
}
The first snippet would be for opening the file, the second one for either encryption or decryption, depending on the value of bCryptMode. It wouldn't make sense to hard-code the file names (and the password) like it is done in both samples when you do this in your actual app though, unless you have a single common file shared by all users.
Quote:
so il put the code you gave me in a cpp file not a header file aswell? will i need a pointer to call the function?
Quote:
The best place to put it is the compilation unit (i.e. .cpp file) from where you call it,
Oh do you mean like my login.cpp file, il put it in there, that way i dont need a pointer. i am abit confused on how to call the actual function if i wanted to decrypt it? i would call the encrypt function in the enrollment.cpp file. that would mean i'd have the your code twice in the program?
If you only need to call Crypt() from a single one of your .cpp files, the easiest option would be to paste the Crypt() function definition into that file. In that case you wouldn't need a .h file for it. And no, you don't need a pointer to call it.
If you need to call it from more than one .cpp file, having the Crypt() function definition in each of them isn't really an option. In fact it would lead to linker errors unless you take special precautions. In this case it's best to put the Crypt() definition into its own .cpp file (e.g. Crypt.cpp) and add that file to your project. Then you would need a .h file for it and it has to be #included in every .cpp file the function is called from. The .h file wouldn't really be spectacular. This is enough:
Code:
// Crypt.h
#pragma once
bool Crypt(String ^, String ^, String ^, bool);
Quote:
the thing is, once the file opens i was planning on making my program close, is that not a good idea because if the user edits and closes the file it would not get re-encrypted because my program would have closed before the user closes the file. if i was to change it how would my program know when to re-encrypt it, i would need to connect the closing of the file with the re-encyption of the file. how?
Your app should stay open at least until re-encryption of the file. How else should it know which user is logged in if any at all when it comes to re-encryption?
The more secure variant of leaving the file unencrypted for the minimum time requires your app to detect when the app launched for viewing/editing the file is closed. In a native app, one option would be to use ShellExecuteEx() instead of system() to open the file and then wait for the process handle returned by that function to get signaled which indicates that the process has finished. But this approach can quickly get pretty complex (you will likely need a worker thread for that, e.g.), so I would recommend using the simpler variant of decrypting the file upon login of the user and re-encrypt it upon logout. Aside from that, ShellExecuteEx() is a native API function (BTW, system() is a native function as well, though it's no Windows API but part of the C++ runtime library) and while you can call them from C++/CLI it is usually preferable to use a .NET equivalent if there is one. I'm sure there actually is one for this, I just didn't find it yet.
In contrast, determining whether re-encryption is needed is much simpler. I would suggest to clear the archive attribute of the decrypted file right after decryption. When time comes for possible re-encryption, you simply check whether that attribute is set now. If it is, the file has been changed in the meantime and you need to re-encrypt it. This would involve the .NET runtime functions IO::File::GetAttributes() and SetAttributes().
Quote:
plus how comes this is in the main.cpp....where would i put this part of the code then. i have a main function already.
In a console app it is common practice to have a function like Crypt() in the compilation unit containing main() (which usually is not called main.cpp, BTW). In a Windows Forms app, however, there usually is no reason to change anything in main.cpp at all. Here you would put it into login.cpp, enrollment.cpp or its own compilation unit like Crypt.cpp, e.g, but not into more than one of them at a time. I have already pointed this out above.
EDIT: The way I described defining Crypt() in its own compilation unit above would put it into the global namespace. While this works, it isn't necessarily considered good style. It should better reside in the namespace that contains all your Windows Forms classes, but I'll leave that for later at the moment for the sake of simplicity (and weariness after writing this long post).
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
Eri523
depending on the value of bCryptMode
how do i determining the value of bmode? this is weird, how would i call the crypt() function if i wanted to encrypt a file? if i cant put the name of the password as the parameter?
i dont know how i'm supposed to call the function if i wanted to encrypt a file. i thought below was right, but apparently i shouldn't put the name of the password or filename when calling the file, so how would this work where would i put them?
Code:
Crypt("peter.txt", "john.txt", good123, .... )
however i still dont know how i would write the bmode lets say for encryption?
Quote:
so I would recommend using the simpler variant of decrypting the file upon login of the user and re-encrypt it upon logout.
i dont have a logout option, this isnt necessary, all i want is for when the user closes the file that my program closes too, whilst the user edits the file i will have the login window be invisible and the program end when they close the file...however i will deal with this section after i actually get the file to be encrypted and decrypted, at this rate i dont think it will happen.
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
katy_price
how do i determining the value of bmode? this is weird, how would i call the crypt() function if i wanted to encrypt a file? if i cant put the name of the password as the parameter?
It's that simple: Set the boolean mode parameter to true if you want to encrypt and to false if you want to decrypt.
Of course you need to specify the password for both encryption and decryption. And of course they have to be the same (for the same file) or you won't get a valid output file after decryption. Imagine you were a hacker who wants to steal Katy's secret file, and you have the Crypt() function. If you could use it to decrypt the file without specifying the password you would instantly get hands on the secret data and hence the encryption would be pointless. ;)
Quote:
i dont know how i'm supposed to call the function if i wanted to encrypt a file. i thought below was right, but apparently i shouldn't put the name of the password or filename when calling the file, so how would this work where would i put them?
Code:
Crypt("peter.txt", "john.txt", good123, .... )
It would be right, provided that a) the file names you use for encryption and decryption are always the same, b) good123 has been declared as
and previously set to the appropriate password and c) the .... is replaced by a boolean variable (or a boolean expression) that evaluates to true because you want to encrypt.
Quote:
i dont have a logout option, this isnt necessary, all i want is for when the user closes the file that my program closes too, whilst the user edits the file i will have the login window be invisible and the program end when they close the file
Well, then you have to bite the bullet and use the "wait for process to finish" approach I described above. I think I'll go and look for a .NET alternative to ShellExecuteEx() in advance, and maybe we're lucky and this .NET feature simplifies things a bit... :) Or maybe someone who knows comes along, reads the thread despite the 30+ posts it already has and tells us what to use.
Quote:
...however i will deal with this section after i actually get the file to be encrypted and decrypted, at this rate i dont think it will happen.
Dividing programming tasks into manageable steps is always a good idea, especially if the task is of the somewhat more complex kind, and that process waiting thing definitely doesn't simplify the app as a whole.
For testing purposes you can replace the process waiting thing by a simple box containing a button that says "click me when you're done editing the file". Actually, you don't even need to create a form for this. A simple message box will do. That way you can test the parts of the app you already have without having that complex waiting stuff.
-
Re: how can i encrypt a file?
i can't convert my program from vc++ express 2008 to 2010 i get the following error: The following error has occurred during XML parsing: File: System error: -2147154677. The file has failed to load.
i dont know what it means or how to fix it. i need to convert to 2010 in order to use the AesManaged class and the copyTo function.
-
Re: how can i encrypt a file?
Sorry, I have no experience with that kind of error and don't know how to fix it. :( But maybe one of the experts comes along who knows about that and posts a solution. However, there's a chance that the particular expert who knows the answer doesn't read this thread anymore because it's become too long. While it's likely that some of them aren't around durig the holidays anyway, I would suggest you start a separate thread about that issue if you haven't got a solution (or at least a hint to one) yet some days after the holidays.
But did you happen to try to compile your project (with the Crypt() function) under 2008 after you have installed 2010? Maybe that works now that .NET 4 is available.
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
Eri523
But did you happen to try to compile your project (with the Crypt() function) under 2008 after you have installed 2010? Maybe that works now that .NET 4 is available.
The crypt function doesnt work on visual c++ 08 the lastest .net is 3.5 so i couldnt compile it
-
Re: how can i encrypt a file?
sorry i mean the 'AesManaged' class is not in .net 3.5 is there an equivalent to AesManaged in 3.5. CopyTo isn't either. i can't use 2010 because my program will not convert.
-
Re: how can i encrypt a file?
i found the RijndaelManaged class which encypts and decrypts files so i replaced the AesManaged class with that. i only have one error left which is with the copyTo because its saying its not a member of the CryptoStream class.
Code:
int main(array<System::String ^> ^args)
{
// Validate command line arguments:
if (args->Length != 4 || String::Compare(args[0], "encrypt", true) && String::Compare(args[0], "decrypt", true)) {
Console::WriteLine("Usage: CryptEx2 <encrypt|decrypt> <password> <input file> <output file>");
return 1;
}
// Call the do-all crypto function:
bool bCryptMode = !String::Compare(args[0], "encrypt", true);
if (!Crypt(args[2], args[3], args[1], bCryptMode)) {
Console::WriteLine("Some sort of error happened during encryption/decryption... :o");
return 1;
}
error: "int __clrcall main(cli::array<class System::String ^ >^)" (?main@@$$HYMHP$01AP$AAVString@System@@@Z) already defined.
should i rename the function to mainBody? will i need to declare it in the h.file too.
also are both files going to be input files and out put files depending on whether i am decrypting or encrypting. e.g when i decrypt the file the file in decrypt mode will be the input file and then when the file is encrypted that will be the output file and vis versa?
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
katy_price
i found the RijndaelManaged class which encypts and decrypts files so i replaced the AesManaged class with that.
RijndaelManaged is a really good choice. :thumb: And one of the things that are especially nice is that it supports all the features of AesManaged I used as well, so aside from changing the class name the transition requires no code changes at all.
Quote:
i only have one error left which is with the copyTo because its saying its not a member of the CryptoStream class.
To overcome this problem replace this part of the Crypt() function:
Code:
// Process (i.e. encrypt or decrypt) data while copying from input file to output file:
try {
cryptstream->CopyTo(fOutput);
}
catch (...) {
return false;
}
by this:
Code:
// Process (i.e. encrypt or decrypt) data while copying from input file to output file:
try {
const int nBufferSize = 512;
array<Byte> ^abBuffer = gcnew array<Byte>(nBufferSize);
int nBytesRead;
do {
nBytesRead = cryptstream->Read(abBuffer, 0, nBufferSize);
if (!nBytesRead) break;
fOutput->Write(abBuffer, 0, nBytesRead);
} while (nBytesRead == nBufferSize);
}
catch (...) {
return false;
}
You see, it's actually a bit more convoluted, but not really scary either. :)
Quote:
error: "int __clrcall main(cli::array<class System::String ^ >^)" (?main@@$$HYMHP$01AP$AAVString@System@@@Z) already defined.
should i rename the function to mainBody? will i need to declare it in the h.file too.
I assume you get this error when compiling the code from the crypto example as part of your project. Your project already contains a main() function, so you don't need the one from the crypto example at all. Simply delete it. The main() in CryptEx2 didn't do anything besides validating the command line parameters and calling Crypt() at all anyway.
Quote:
also are both files going to be input files and out put files depending on whether i am decrypting or encrypting. e.g when i decrypt the file the file in decrypt mode will be the input file and then when the file is encrypted that will be the output file and vis versa?
The file name parameters to Crypt() are always in the sequence input -> output, regardless of whether you're encrypting or decrypting. So, when encrypting, the plaintext file comes first and when decrypting the encrypted file comes first.
-
Re: how can i encrypt a file?
Code:
// Process (i.e. encrypt or decrypt) data while copying from input file to output file:
try {
const int nBufferSize = 512;
array<Byte> ^abBuffer = gcnew array<Byte>(nBufferSize);
int nBytesRead;
do {
nBytesRead = cryptstream->Read(abBuffer, 0, nBufferSize);
if (!nBytesRead) break;
fOutput->Write(abBuffer, 0, nBytesRead);
} while (nBytesRead == nBufferSize);
}
catch (...) {
return false;
}
thanks. whats the buffer for, whats happening here? are you creating space for the info read in the input file to put into the output file.
also i have declared the password like so: String ^ good123; But i get this error:string ref is not set to instance of a string. parameter name: s
so i wrote it like String ^ good123 = strPassword; but i get another error. i am not sure whats wrong
bool encrypt = true;
i called the function like so:
Code:
Crypt("authentication methods.txt", "john.txt", good123, encrypt);
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
katy_price
whats the buffer for, whats happening here? are you creating space for the info read in the input file to put into the output file.
An obvious choice in this situation would have been to transfer the data byte by byte using the ReadByte() and WriteByte() methods. I prefer to move data in mid-size chunks in such situations, though. This is more efficient because the overhead for calling the read and write methods would be incurred for every single byte, while it's only incurred once for every 512 bytes using the buffer.
You also frequently see suggestions around here to transfer files in a single large chunk, but this would fail or be at least really inefficient if the file size is above or close to the total amount of memory available. Though this can be quite efficient for small to mid-size files I, personally don't like it, mainly for historical reasons, because I learned programming on systems that had less memory than it's common today, by several magnitudes.
The buffer size of 512 bytes, BTW, has historical reasons as well. It has been the size of a single disk sector under DOS, under Windows for a long time, and also still on most of the systems nowadays. Large hard disks (in the Tbyte range) may have larger sector sizes nowadays, however.
Quote:
also i have declared the password like so: String ^ good123; But i get this error:string ref is not set to instance of a string. parameter name: s
so i wrote it like String ^ good123 = strPassword; but i get another error. i am not sure whats wrong
If the (tracking handle to the) string actually hasn't been assigned a live string I would have expected that you get a NullReferenceException being thrown. I never have seen an error message looking like what you describe. I think I'll need to see concrete code in order to diagnose the problem.
-
Re: how can i encrypt a file?
sorry i worked out how to do the password: String ^ strPassword = "length123";
thanks it works. all i need to do now is link the closure of the file to my program so i know when to re-encrypt it. plus i have been looking for a function to open the file instead of system(), i looked at shellExecute() but i got some ambigious error. anyways thanks for your help so far, you've been great :)
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
katy_price
Code:
encryption:
String ^strInputFileName ="peter.txt";
String ^strOutputFileName = "hungry.txt";
decryption:
String ^ strInputFileName = "hungry.txt";
String ^strOutputFileName ="peter.txt";
reencryption:
String ^strInputFileName = "peter.txt";;
String ^strOutputFileName = "hungry.txt";
This looks correct, provided that the password parameter is the same for all three calls and the mode parameter is set to true, false, true, in that sequence.
Quote:
this doesnt work how i would like it too because the hungry file remains in plain text which makes it visible to other apps.
What do you mean by "remains unencrypted"? Based on the sequence described above, there never should be an unencrypted file named hungry.txt at all.
Quote:
if i put a new filename in the outputfile for decryption , when that file is edited it doesnt get updated when re-encrypted.
Maybe the file you re-encrypt actually isn't the file that you have edited?
Quote:
sorry am abit confused do you know how i can get it to run how i would like?
Well, unfortunately your description of what's going on isn't really clear. Some more information might be helpful, maybe with code.
Note that if you use the user's password as the password parameter to Crypt(), you need an individual encrypted file for each user, even if the original plaintext file should be the same for all users. That's because the contents of the file the encryption results in of course depends on the password.
-
Re: how can i encrypt a file?
to avoid the problem of the file been left in a readable state, after encryption and re-encryption i delete the monk file and it seems to do the trick. i used system("del monk.txt"); to delete the file, i dont actually like using the system funtion because i can see the cmd window. when deleting the file it just flashes on and off but when i call the file using it, it actually stays open until i close the file, which is annoying, but i couldnt find any other function that would do what i wanted and was easy to implement.
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
katy_price
with this order the monk file is always readable. without running the program i can open and read the monk file through windows explorer. [...] i have debugged the program at each stage and it is always readable. the problem is the file does not get destroyed after it is encrypted and the output is sent to another file. [...]
all users will use the same password paramater and the same file.
Ah, now I've got what your problem was. :) If all users share the same file (and the same versin of that file) and all use the same encryption key, you can simply "ping pong" between the encrypted and the plaintext version of the file. I.e. always delete the plaintext file after encryption. And there would be no need to delete the encrypted file since it is no security risk and will be overwritten the next time you encrypt anyway.
The shared key actually can raise some security concenrns if it is hard-coded inside your app, but as protecting a shared key can really complicate things I think we should put aside the concerns for now, for the sake of simplicity.
Quote:
so when the file is encrypted and if the plain text file gets destroyed there would be no file with text to encrypt the next time round (e.g another user enrolls). the output filestream would just create a new file with the same name but this would have no text to encrypt.
I don't really get what you mean by this, however. :ehh:
Quote:
Originally Posted by
katy_price
to avoid the problem of the file been left in a readable state, after encryption and re-encryption i delete the monk file and it seems to do the trick.
Yes, indeed. But just FYI I'd like to mention that deleted files can be restored under certain circumstances. While normal users usually aren't able to do that, any apprentice hacker will likely have a program for this task. Fixing this security hole would require some sort of secure deletion, which can be quite tricky, as this thread in the Non-VC++ forum illustrates. This is, however, non-managed stuff. I just wanted to point you there to scare you a bit. :D But like with the hard-coded key, I think we should put aside these security concerns as well for now.
Quote:
i used system("del monk.txt"); to delete the file, i dont actually like using the system funtion because i can see the cmd window.
Yes, I consider using system() calls painful as well, and for the deletion I have found an alternative that's even clean .NET style: the IO::File::Delete() method. :)
Quote:
when deleting the file it just flashes on and off but when i call the file using it, it actually stays open until i close the file, which is annoying, but i couldnt find any other function that would do what i wanted and was easy to implement.
It took some time but I've even found a .NET alternative for this as well: the Diagnostics::Process class! :cool: It took some time to find it because I didn't expect to find it in the System::Diagnostics namespace. The class can do a lot of fancy things most of which we dont't even need here, and a significant part of them indeed is related to diagnostics, which obviously is the reason why they put it there.
Using this class, you can replace this:
Code:
system("monk.txt");
by this:
Code:
Diagnostics::Process ^proc = Diagnostics::Process::Start("monk.txt");
Diagnostics::Debug::Assert(proc != nullptr, "Process::Start() returned nullptr");
proc->WaitForExit();
proc->Close();
You can look up the methods used here on MSDN, starting from the link I gave you above, to understand what's going on here. (It's really a bunch of stuff to read, however.)
The Assert() is there to catch the case when the call to Process::Start() didn't actually start a new process to open the file, but instead delegated opening the file to an instance of the associated app that's already running. This can't actually happen as long as you're opening .txt files and theye associated to Notepad, but it's easily possible if you want to open .doc files with Word, for instance.
This sequence of comands is blocking (as is the system() call) and will render your app irresponsive as long as the target file is opened, but if you, as I understood the description of your app, will have either closed or hidden all GUI elements when this is called, the user can't interact with your app anyway at this point. So, the blocking nature of that command sequence isn't much of a pain and will rather simplify things, so a worker thread is dispensable for instance.
-
Re: how can i encrypt a file?
wow the Diagnostics::Process stuff is amazing, thanks alot. i have learned alot of things, thanks for all your help. i wish i could give you a gift lol :).
-
Re: how can i encrypt a file?
Quote:
Originally Posted by
katy_price
[...] thanks for all your help.
You're welcome. :)
Quote:
i wish i could give you a gift lol :).
How about some reputation points? :D I always appreciate them.