CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Jun 2001
    Location
    Islamabad, Pakistan
    Posts
    113

    Encrypting binary files

    I am encrypting files. Teh brief code is:

    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

    // some code to set rsa skiped here


    // input buffer
    byte[] inbuf = new byte[(new FileInfo(fileName)).Length];

    //output buffer
    byte[] outbuf = null;

    //stream
    FileStream fs = File.OpenRead(fileName);

    // read the file
    fs.Read(inbuf,0, inbuf.Length);
    fs.Close();
    outbuf = rsa.Encrypt(inbuf,false);


    //write to output file

    fs = File.OpenWrite(outputFile);
    fs.Write(outbuf,0,outbuf.Length);
    fs.Close();



    Now when the input file is a text file its works ok
    but when thefile is a binay file (a Serialized file to be exact)
    the outbuf = rsa.Encrypt(inbuf,false); crashes giving the error "bad length"

    not that the binay file if opned in notpad has chracters like
    

    Soo....whats wrong with length here ???

    Thanks!

  2. #2
    Join Date
    Aug 2002
    Location
    Germany, Berlin
    Posts
    60

    Re: Encrypting binary files

    Originally posted by FaisalJ
    Now when the input file is a text file its works ok
    but when thefile is a binay file (a Serialized file to be exact)
    the outbuf = rsa.Encrypt(inbuf,false); crashes giving the error "bad length"
    Assuming that the crash is due to the wrong public key a CryptographicException is thrown.
    If you use RSA, you have first to provide the generated public Key, which is used to encrypt the file, after transmission you can decrypt the file. You can forward the generated public key as a string by using

    pubKey = rsa.ToXmlString(false);

    after providing this key, you use it with

    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    rsa.FromXmlString(publicKey_Client);

    -then performing with this pubKey the encryption
    -transfer the encrypted byte[]
    -decrypt

    Hope that helps

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured