CryptoStream?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • weixiang

    #1

    CryptoStream?

    Hi,

    I want to use DES and CryptoStream to serialize a encrypted stream to a file
    with a header "CRYPT". And I wrote these code:

    To store:

    FileStream fileStream = new FileStream(file Name, FileMode.Create ,
    FileAccess.Writ e, FileShare.None) ;
    byte[] signture = AE.GetBytes("CR YPT");
    fileStream.Writ e(signture, 0, 5);

    ICryptoTransfor m ct = des.CreateDecry ptor(key, iv);
    CryptoStream cryptoStream = new CryptoStream(fi leStream, ct,
    CryptoStreamMod e.Write);

    IFormatter formatter = new BinaryFormatter ();
    formatter.Binde r = new DataSNBinder();
    formatter.Seria lize(cryptoStre am, MYDATA);

    cryptoStream.Fl ush();
    fileStream.Clos e();

    To load:

    FileStream fileStream = new FileStream(file Name, FileMode.Open,
    FileAccess.Read );
    fileStream.Seek (5, SeekOrigin.Begi n);
    ICryptoTransfor m ct = des.CreateDecry ptor(key, iv);
    CryptoStream cryptoStream = new CryptoStream(fi leStream, ct,
    CryptoStreamMod e.Read);
    formatter = new BinaryFormatter ();
    formatter.Binde r = new DataSNBinder();
    MYDATA = (MYDATA)formatt er.Deserialize( cryptoStream);
    cryptoStream.Cl ose();

    And with that code I can not load the saved file. What's the problem?

    And, what's the exact meaning of CryptoStream.Cl ose()? If I replace the
    CryptoStream.Fl ush() with Close(), it will crash. But the encrypted file
    size is somewhat smaller than the original data size, is that mean a problem
    in my code?

    Thank you very much
    weixiang


  • weixiang

    #2
    Re: CryptoStream?

    Thank you. I'll test that ASAP.

    What's the CryptoStream.Cl ose() mean? It will throw a exception if I use
    that to instead CryptoStream.Fl ush()

    "Rob Teixeira [MVP]" <RobTeixeira@@m sn.com> wrote in message
    news:uk4BrhXUDH A.2088@TK2MSFTN GP10.phx.gbl...[color=blue]
    > I haven't run the code, but I immediately noticed something that needs to
    > get fixed.
    > After the last write into the CrypoStream, you MUST call FlushFinalBlock
    > (not Flush).
    > The final block of cypher data must be properly padded according to the
    > cypher, otherwise, you can't decrypt.
    >
    > -Rob [MVP]
    >
    > "weixiang" <weixiang@yahoo .com> wrote in message
    > news:#CkbJwSUDH A.2316@tk2msftn gp13.phx.gbl...[color=green]
    > > Hi,
    > >
    > > I want to use DES and CryptoStream to serialize a encrypted stream to a[/color]
    > file[color=green]
    > > with a header "CRYPT". And I wrote these code:
    > >
    > > To store:
    > >
    > > FileStream fileStream = new FileStream(file Name, FileMode.Create ,
    > > FileAccess.Writ e, FileShare.None) ;
    > > byte[] signture = AE.GetBytes("CR YPT");
    > > fileStream.Writ e(signture, 0, 5);
    > >
    > > ICryptoTransfor m ct = des.CreateDecry ptor(key, iv);
    > > CryptoStream cryptoStream = new CryptoStream(fi leStream, ct,
    > > CryptoStreamMod e.Write);
    > >
    > > IFormatter formatter = new BinaryFormatter ();
    > > formatter.Binde r = new DataSNBinder();
    > > formatter.Seria lize(cryptoStre am, MYDATA);
    > >
    > > cryptoStream.Fl ush();
    > > fileStream.Clos e();
    > >
    > > To load:
    > >
    > > FileStream fileStream = new FileStream(file Name, FileMode.Open,
    > > FileAccess.Read );
    > > fileStream.Seek (5, SeekOrigin.Begi n);
    > > ICryptoTransfor m ct = des.CreateDecry ptor(key, iv);
    > > CryptoStream cryptoStream = new CryptoStream(fi leStream, ct,
    > > CryptoStreamMod e.Read);
    > > formatter = new BinaryFormatter ();
    > > formatter.Binde r = new DataSNBinder();
    > > MYDATA = (MYDATA)formatt er.Deserialize( cryptoStream);
    > > cryptoStream.Cl ose();
    > >
    > > And with that code I can not load the saved file. What's the problem?
    > >
    > > And, what's the exact meaning of CryptoStream.Cl ose()? If I replace the
    > > CryptoStream.Fl ush() with Close(), it will crash. But the encrypted[/color][/color]
    file[color=blue][color=green]
    > > size is somewhat smaller than the original data size, is that mean a[/color]
    > problem[color=green]
    > > in my code?
    > >
    > > Thank you very much
    > > weixiang
    > >
    > >[/color]
    >
    >[/color]


    Comment

    • Rob Teixeira [MVP]

      #3
      Re: CryptoStream?

      Close will close the CryptoStream and the underlying stream object the
      CryptoStream is writing to.
      In accordance to stream behavior, Close calls Flush, but in this case, you
      need to call FlushFinalBlock .

      -Rob [MVP]

      "weixiang" <weixiang@yahoo .com> wrote in message
      news:eb40ZIYUDH A.1744@TK2MSFTN GP12.phx.gbl...[color=blue]
      > Thank you. I'll test that ASAP.
      >
      > What's the CryptoStream.Cl ose() mean? It will throw a exception if I use
      > that to instead CryptoStream.Fl ush()
      >
      > "Rob Teixeira [MVP]" <RobTeixeira@@m sn.com> wrote in message
      > news:uk4BrhXUDH A.2088@TK2MSFTN GP10.phx.gbl...[color=green]
      > > I haven't run the code, but I immediately noticed something that needs[/color][/color]
      to[color=blue][color=green]
      > > get fixed.
      > > After the last write into the CrypoStream, you MUST call FlushFinalBlock
      > > (not Flush).
      > > The final block of cypher data must be properly padded according to the
      > > cypher, otherwise, you can't decrypt.
      > >
      > > -Rob [MVP]
      > >
      > > "weixiang" <weixiang@yahoo .com> wrote in message
      > > news:#CkbJwSUDH A.2316@tk2msftn gp13.phx.gbl...[color=darkred]
      > > > Hi,
      > > >
      > > > I want to use DES and CryptoStream to serialize a encrypted stream to[/color][/color][/color]
      a[color=blue][color=green]
      > > file[color=darkred]
      > > > with a header "CRYPT". And I wrote these code:
      > > >
      > > > To store:
      > > >
      > > > FileStream fileStream = new FileStream(file Name, FileMode.Create ,
      > > > FileAccess.Writ e, FileShare.None) ;
      > > > byte[] signture = AE.GetBytes("CR YPT");
      > > > fileStream.Writ e(signture, 0, 5);
      > > >
      > > > ICryptoTransfor m ct = des.CreateDecry ptor(key, iv);
      > > > CryptoStream cryptoStream = new CryptoStream(fi leStream, ct,
      > > > CryptoStreamMod e.Write);
      > > >
      > > > IFormatter formatter = new BinaryFormatter ();
      > > > formatter.Binde r = new DataSNBinder();
      > > > formatter.Seria lize(cryptoStre am, MYDATA);
      > > >
      > > > cryptoStream.Fl ush();
      > > > fileStream.Clos e();
      > > >
      > > > To load:
      > > >
      > > > FileStream fileStream = new FileStream(file Name, FileMode.Open,
      > > > FileAccess.Read );
      > > > fileStream.Seek (5, SeekOrigin.Begi n);
      > > > ICryptoTransfor m ct = des.CreateDecry ptor(key, iv);
      > > > CryptoStream cryptoStream = new CryptoStream(fi leStream, ct,
      > > > CryptoStreamMod e.Read);
      > > > formatter = new BinaryFormatter ();
      > > > formatter.Binde r = new DataSNBinder();
      > > > MYDATA = (MYDATA)formatt er.Deserialize( cryptoStream);
      > > > cryptoStream.Cl ose();
      > > >
      > > > And with that code I can not load the saved file. What's the problem?
      > > >
      > > > And, what's the exact meaning of CryptoStream.Cl ose()? If I replace[/color][/color][/color]
      the[color=blue][color=green][color=darkred]
      > > > CryptoStream.Fl ush() with Close(), it will crash. But the encrypted[/color][/color]
      > file[color=green][color=darkred]
      > > > size is somewhat smaller than the original data size, is that mean a[/color]
      > > problem[color=darkred]
      > > > in my code?
      > > >
      > > > Thank you very much
      > > > weixiang
      > > >
      > > >[/color]
      > >
      > >[/color]
      >
      >[/color]


      Comment

      • Simon Trew

        #4
        Re: CryptoStream?

        So why doesn't Close call FlushFinalBlock ? Why would you ever not want it
        to?

        S.

        "Rob Teixeira [MVP]" <RobTeixeira@@m sn.com> wrote in message
        news:uU50aNYUDH A.1680@TK2MSFTN GP11.phx.gbl...[color=blue]
        > Close will close the CryptoStream and the underlying stream object the
        > CryptoStream is writing to.
        > In accordance to stream behavior, Close calls Flush, but in this case, you
        > need to call FlushFinalBlock .
        >
        > -Rob [MVP][/color]



        Comment

        • weixiang

          #5
          Re: CryptoStream?

          I tried to call FlushFinalBlock to instead Flush, but it still throw a
          exception that said "Length of the data to decrypt is invalid". Is there
          other problem? And I believe I am going to encrypt my data, not to decrypt
          it. Is that declared in the CryptoStream constructor with CSMode.Write?

          Here is my current code:

          FileStream fileStream = new FileStream(file Name, FileMode.Create ,
          FileAccess.Writ e, FileShare.None) ;
          byte[] signture = AE.GetBytes("CR YPT");
          fileStream.Writ e(signture, 0, 5);

          ICryptoTransfor m ct = des.CreateDecry ptor(key, iv);
          CryptoStream cryptoStream = new CryptoStream(fi leStream, ct,
          CryptoStreamMod e.Write);

          IFormatter formatter = new BinaryFormatter ();
          formatter.Binde r = new DataSNBinder();
          formatter.Seria lize(cryptoStre am, MYDATA);

          cryptoStream.Fl ushFinalBlock() ; // throw exception here
          fileStream.Clos e();


          "Simon Trew" <ten.egnaro@wer ts> wrote in message
          news:%23KJbE%23 bUDHA.2164@TK2M SFTNGP10.phx.gb l...[color=blue]
          > So why doesn't Close call FlushFinalBlock ? Why would you ever not want it
          > to?
          >
          > S.
          >
          > "Rob Teixeira [MVP]" <RobTeixeira@@m sn.com> wrote in message
          > news:uU50aNYUDH A.1680@TK2MSFTN GP11.phx.gbl...[color=green]
          > > Close will close the CryptoStream and the underlying stream object the
          > > CryptoStream is writing to.
          > > In accordance to stream behavior, Close calls Flush, but in this case,[/color][/color]
          you[color=blue][color=green]
          > > need to call FlushFinalBlock .
          > >
          > > -Rob [MVP][/color]
          >
          >
          >[/color]


          Comment

          • Rob Teixeira [MVP]

            #6
            Re: CryptoStream?

            OK, instead of trying to wade through the code, I wrote my own ;-)
            This sample includes just about everything you need. I'm serializing a
            string object, but that could easily be any object.

            byte[] key = new byte[8];

            byte[] iv = new byte[8];

            FileStream fs = null;

            CryptoStream cs = null;

            BinaryFormatter bf = null;

            string myData = "This is some test data.";

            string myData2 = string.Empty;

            DES desCypher = DES.Create();

            // Encryption starts here

            try

            {

            // create some key and IV data for the sample

            RandomNumberGen erator.Create() .GetBytes(key);

            RandomNumberGen erator.Create() .GetBytes(iv);

            fs = new FileStream(@"C: \sample.dat", FileMode.OpenOr Create);

            fs.Write(Encodi ng.ASCII.GetByt es("CRYPT"), 0, 5);

            cs = new CryptoStream(fs , desCypher.Creat eEncryptor(key, iv),
            CryptoStreamMod e.Write);

            bf = new BinaryFormatter ();

            bf.Serialize(cs , myData);

            cs.FlushFinalBl ock();

            }

            catch (Exception ex)

            {

            MessageBox.Show (ex.ToString()) ;

            }

            finally

            {

            if (cs != null) cs.Close();

            }

            // decryption starts here

            try

            {

            fs = new FileStream(@"C: \sample.dat", FileMode.Open);

            fs.Position = 5;

            cs = new CryptoStream(fs , desCypher.Creat eDecryptor(key, iv),
            CryptoStreamMod e.Read);

            myData2 = bf.Deserialize( cs) as string;

            MessageBox.Show (myData2);

            }

            catch (Exception ex)

            {

            MessageBox.Show (ex.ToString()) ;

            }

            finally

            {

            if (cs != null) cs.Close();

            }

            -Rob [MVP]


            "weixiang" <weixiang@yahoo .com> wrote in message
            news:u1gr5QeUDH A.1816@TK2MSFTN GP09.phx.gbl...[color=blue]
            > I tried to call FlushFinalBlock to instead Flush, but it still throw a
            > exception that said "Length of the data to decrypt is invalid". Is there
            > other problem? And I believe I am going to encrypt my data, not to[/color]
            decrypt[color=blue]
            > it. Is that declared in the CryptoStream constructor with CSMode.Write?
            >
            > Here is my current code:
            >
            > FileStream fileStream = new FileStream(file Name, FileMode.Create ,
            > FileAccess.Writ e, FileShare.None) ;
            > byte[] signture = AE.GetBytes("CR YPT");
            > fileStream.Writ e(signture, 0, 5);
            >
            > ICryptoTransfor m ct = des.CreateDecry ptor(key, iv);
            > CryptoStream cryptoStream = new CryptoStream(fi leStream, ct,
            > CryptoStreamMod e.Write);
            >
            > IFormatter formatter = new BinaryFormatter ();
            > formatter.Binde r = new DataSNBinder();
            > formatter.Seria lize(cryptoStre am, MYDATA);
            >
            > cryptoStream.Fl ushFinalBlock() ; // throw exception here
            > fileStream.Clos e();
            >
            >
            > "Simon Trew" <ten.egnaro@wer ts> wrote in message
            > news:%23KJbE%23 bUDHA.2164@TK2M SFTNGP10.phx.gb l...[color=green]
            > > So why doesn't Close call FlushFinalBlock ? Why would you ever not want[/color][/color]
            it[color=blue][color=green]
            > > to?
            > >
            > > S.
            > >
            > > "Rob Teixeira [MVP]" <RobTeixeira@@m sn.com> wrote in message
            > > news:uU50aNYUDH A.1680@TK2MSFTN GP11.phx.gbl...[color=darkred]
            > > > Close will close the CryptoStream and the underlying stream object the
            > > > CryptoStream is writing to.
            > > > In accordance to stream behavior, Close calls Flush, but in this case,[/color][/color]
            > you[color=green][color=darkred]
            > > > need to call FlushFinalBlock .
            > > >
            > > > -Rob [MVP][/color]
            > >
            > >
            > >[/color]
            >
            >[/color]


            Comment

            Working...