[RESOLVED] how can i encrypt a file?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 5 1234 ... LastLast
Results 1 to 15 of 66

Thread: [RESOLVED] how can i encrypt a file?

  1. #1
    Join Date
    Nov 2010
    Posts
    139

    [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???
    Last edited by katy_price; December 20th, 2010 at 04:12 PM.

  2. #2
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,583

    Re: how can i encrypt a file?

    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
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  3. #3
    Join Date
    Nov 2010
    Posts
    139

    Re: how can i encrypt a file?

    Thanks Eri523 il give the Cryptographic Services ago.

  4. #4
    Join Date
    Nov 2010
    Posts
    139

    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.

  5. #5
    Join Date
    Apr 2008
    Posts
    118

    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.

  6. #6
    Join Date
    Nov 2010
    Posts
    139

    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
    Last edited by katy_price; December 21st, 2010 at 12:48 PM.

  7. #7
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,583

    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?
    Last edited by Eri523; June 7th, 2011 at 07:55 PM.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  8. #8
    Join Date
    Nov 2010
    Posts
    139

    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?
    Last edited by katy_price; December 21st, 2010 at 03:51 PM.

  9. #9
    Join Date
    Apr 2008
    Posts
    118

    Re: how can i encrypt a file?

    Quote Originally Posted by katy_price View Post
    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
    Last edited by Moschops; December 21st, 2010 at 05:15 PM.

  10. #10
    Join Date
    Apr 2008
    Posts
    118

    Re: how can i encrypt a file?

    Quote Originally Posted by Eri523 View Post
    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.
    Last edited by Moschops; December 21st, 2010 at 05:16 PM.

  11. #11
    Join Date
    Nov 2010
    Posts
    139

    Re: how can i encrypt a file?

    Quote Originally Posted by Moschops View Post
    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?

  12. #12
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,583

    Re: how can i encrypt a file?

    Quote Originally Posted by katy_price View Post
    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 ): 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++?

    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...

    Quote Originally Posted by Moschops View Post
    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...
    Last edited by Eri523; December 21st, 2010 at 05:47 PM. Reason: Corrected sample command line
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  13. #13
    Join Date
    Nov 2010
    Posts
    139

    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;
    }

  14. #14
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,583

    Re: how can i encrypt a file?

    Quote Originally Posted by Moschops View Post
    [...]

    Seems the CopyTo class method for this class only exists in .Net 4
    Quote Originally Posted by katy_price View Post
    thanks i ran it vs 2010 it compiles [...]
    Oops! You were both quicker than me...

    [...] 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. 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...

    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 View Post
    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...
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  15. #15
    Join Date
    Nov 2010
    Posts
    139

    Re: how can i encrypt a file?

    Quote Originally Posted by Eri523 View Post
    if you invoke the program without command line parameters. 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.

    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

Page 1 of 5 1234 ... LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center