TripleDESCryptoServiceProvider bad data error

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

    TripleDESCryptoServiceProvider bad data error

    Hi all,

    I have seem few messages posted regaring this but as yet have been
    able to get this code to work. The plan was to encrypt some string
    then pass the result to another function that woudl decrypt it -
    please see below. Anyway i keep getting a 'bad data' exception. I'm
    totally at a loss, so any help woudl be greatly appreciated.

    public Byte[] myEncrypt()
    {
    UTF8Encoding utf8encoder = new UTF8Encoding();
    Byte[] inputBytes = utf8encoder.Get Bytes(txtToDb.T ext);
    //Console.WriteLi ne(inputBytes.T oString());

    TripleDESCrypto ServiceProvider tdesProvider = new
    TripleDESCrypto ServiceProvider ();
    ICryptoTransfor m cryptoTransform =
    tdesProvider.Cr eateEncryptor(t ripleDes.Key,tr ipleDes.IV);

    MemoryStream encryptedStream = new MemoryStream();
    CryptoStream cryptStream = new
    CryptoStream(en cryptedStream,c ryptoTransform, CryptoStreamMod e.Write);

    cryptStream.Wri te(inputBytes,0 ,inputBytes.Len gth);
    cryptStream.Flu shFinalBlock();
    encryptedStream .Position = 0;

    Byte[] bResult = new Byte[encryptedStream .Length-1];
    encryptedStream .Read(bResult,0 ,int.Parse(encr yptedStream.Len gth.ToString())-1);
    cryptStream.Clo se();
    myDecrypt(bResu lt);
    return bResult;
    }


    static string myDecrypt(Byte[] inputInBytes)
    {
    //UTF8Encoding utf8encoder = new UTF8Encoding();
    TripleDESCrypto ServiceProvider tdesProvider = new
    TripleDESCrypto ServiceProvider ();

    ICryptoTransfor m cryptoTranform =
    tdesProvider.Cr eateDecryptor(t ripleDes.Key,tr ipleDes.IV);

    MemoryStream decryptedStream = new MemoryStream();
    CryptoStream cryptStream = new
    CryptoStream(de cryptedStream,c ryptoTranform,C ryptoStreamMode .Write);
    cryptStream.Wri te(inputInBytes ,0,inputInBytes .Length);
    cryptStream.Flu shFinalBlock();
    decryptedStream .Position=0;

    Byte[] result = new Byte[decryptedStream .Length-1];
    decryptedStream .Read(result,0, int.Parse(decry ptedStream.Leng th.ToString())) ;
    cryptStream.Clo se();

    UTF8Encoding myutf = new UTF8Encoding();
    return myutf.GetString (result).ToStri ng();
    }
  • Jon Skeet [C# MVP]

    #2
    Re: TripleDESCrypto ServiceProvider bad data error

    JC <james_crane@bt internet.com> wrote:[color=blue]
    > I have seem few messages posted regaring this but as yet have been
    > able to get this code to work. The plan was to encrypt some string
    > then pass the result to another function that woudl decrypt it -
    > please see below. Anyway i keep getting a 'bad data' exception. I'm
    > totally at a loss, so any help woudl be greatly appreciated.[/color]

    Firstly, you're converting a MemoryStream to a byte array in a
    roundabout way: the best way is to use MemoryStream.To Array, which you
    can even call after it's closed.

    Secondly, there's no need to instantiate the UTF8Encoding - just use
    Encoding.UTF8 which returns a singleton instance reference.

    Having said that, I can't immediately see why it's likely to be
    failing. Could you post a short but complete program which demonstrates
    the problem?

    See http://www.pobox.com/~skeet/csharp/complete.html for what I mean by
    that.

    I've looked at a few problems like this recently - I think it may be
    time to write a page about it...

    --
    Jon Skeet - <skeet@pobox.co m>
    Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

    If replying to the group, please do not mail me too

    Comment

    • James Crane

      #3
      Re: TripleDESCrypto ServiceProvider bad data error

      Hi John,

      Thanks for your reply. I have recreated a bare bones version to run and
      show the error in a console app.

      here's the code.

      using System;
      using System.Security ;
      using System.Security .Cryptography;
      using System.Runtime. InteropServices ;
      using System.Text;
      using System.IO;

      namespace demoEncrtptionF orNewsGroup
      {
      /// <summary>
      /// Summary description for Class1.
      /// </summary>
      class Class1
      {
      /// <summary>
      /// The main entry point for the application.
      /// </summary>
      [STAThread]
      static void Main(string[] args)
      {
      //
      // TODO: Add code to start application here
      //
      myEncrypt();
      }
      public class tripleDes
      {
      public static byte[] Key = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
      0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};
      public static byte[] IV = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
      0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};

      }
      static void myEncrypt()
      {
      UTF8Encoding utf8encoder = new UTF8Encoding();
      Byte[] inputBytes = utf8encoder.Get Bytes("please encrypt me!");

      TripleDESCrypto ServiceProvider tdesProvider = new
      TripleDESCrypto ServiceProvider ();
      ICryptoTransfor m cryptoTransform =
      tdesProvider.Cr eateEncryptor(t ripleDes.Key,tr ipleDes.IV);

      MemoryStream encryptedStream = new MemoryStream();
      CryptoStream cryptStream = new
      CryptoStream(en cryptedStream,c ryptoTransform, CryptoStreamMod e.Write);

      cryptStream.Wri te(inputBytes,0 ,inputBytes.Len gth);
      cryptStream.Flu shFinalBlock();
      encryptedStream .Position = 0;

      Byte[] bResult = new Byte[encryptedStream .Length-1];
      encryptedStream .Read(bResult,0 ,int.Parse(encr yptedStream.Len gth.ToStr
      ing())-1);
      cryptStream.Clo se();
      myDecrypt(bResu lt);
      }
      static void myDecrypt(Byte[] inputInBytes)
      {
      TripleDESCrypto ServiceProvider tdesProvider = new
      TripleDESCrypto ServiceProvider ();

      ICryptoTransfor m cryptoTranform =
      tdesProvider.Cr eateDecryptor(t ripleDes.Key,tr ipleDes.IV);

      MemoryStream decryptedStream = new MemoryStream();
      CryptoStream cryptStream = new
      CryptoStream(de cryptedStream,c ryptoTranform,C ryptoStreamMode .Write);
      cryptStream.Wri te(inputInBytes ,0,inputInBytes .Length);
      cryptStream.Flu shFinalBlock();
      decryptedStream .Position=0;

      Byte[] result = new Byte[decryptedStream .Length-1];
      decryptedStream .Read(result,0, int.Parse(decry ptedStream.Leng th.ToStri
      ng()));
      cryptStream.Clo se();

      UTF8Encoding myutf = new UTF8Encoding();
      Console.WriteLi ne(myutf.GetStr ing(result).ToS tring());
      }
      }
      }

      I hope this is what you were after, and thanks for you help.


      *** Sent via Developersdex http://www.developersdex.com ***
      Don't just participate in USENET...get rewarded for it!

      Comment

      • Jon Skeet [C# MVP]

        #4
        Re: TripleDESCrypto ServiceProvider bad data error

        James Crane <james_crane@bt internet.com> wrote:[color=blue]
        > Thanks for your reply. I have recreated a bare bones version to run and
        > show the error in a console app.[/color]

        Right. The problem is really simple - sorry I didn't spot it before.

        For some reason, you've decided to miss off the last byte of each of
        the encrypted and decrypted data:
        [color=blue]
        > Byte[] bResult = new Byte[encryptedStream .Length-1];
        > encryptedStream .Read(bResult,0 ,int.Parse
        > (encryptedStrea m.Length.ToStri ng())-1);[/color]

        If you just use MemoryStream.To Array instead, all is well.

        I have to ask though - why were you converting the length into a string
        and then parsing it? Why not just cast the long to an int?

        --
        Jon Skeet - <skeet@pobox.co m>
        Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

        If replying to the group, please do not mail me too

        Comment

        • James Crane

          #5
          Re: TripleDESCrypto ServiceProvider bad data error



          Hi Jon,

          I have taken your advice and and now using MemoryStream.To Array instead
          and have removed the -1 and it works fine.

          To be totally honest, the reason why I didnt cast the orinigal values is
          because I'm still quite new to c# and wasnt thinking - I'll know for
          next time.

          Thanks for you help.

          I've including the full working listing below for anyone else who needs
          a reference.


          using System;
          using System.Security ;
          using System.Security .Cryptography;
          using System.Runtime. InteropServices ;
          using System.Text;
          using System.IO;

          namespace demoEncrtptionF orNewsGroup
          {
          /// <summary>
          /// Summary description for Class1.
          /// </summary>
          class Class1
          {
          /// <summary>
          /// The main entry point for the application.
          /// </summary>
          [STAThread]
          static void Main(string[] args)
          {
          //
          // TODO: Add code to start application here
          //
          myEncrypt();
          }
          public class tripleDes
          {
          public static byte[] Key = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
          0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};
          public static byte[] IV = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
          0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};

          }
          static void myEncrypt()
          {
          UTF8Encoding utf8encoder = new UTF8Encoding();
          Byte[] inputBytes = utf8encoder.Get Bytes("please encrypt me!");

          TripleDESCrypto ServiceProvider tdesProvider = new
          TripleDESCrypto ServiceProvider ();
          ICryptoTransfor m cryptoTransform =
          tdesProvider.Cr eateEncryptor(t ripleDes.Key,tr ipleDes.IV);

          MemoryStream encryptedStream = new MemoryStream();
          CryptoStream cryptStream = new
          CryptoStream(en cryptedStream,c ryptoTransform, CryptoStreamMod e.Write);

          cryptStream.Wri te(inputBytes,0 ,inputBytes.Len gth);
          cryptStream.Flu shFinalBlock();
          encryptedStream .Position = 0;

          Byte[] bResult = new Byte[encryptedStream .Length];
          encryptedStream .Read(bResult,0 ,encryptedStrea m.ToArray().Len gth);
          cryptStream.Clo se();
          myDecrypt(bResu lt);
          }
          static void myDecrypt(Byte[] inputInBytes)
          {
          TripleDESCrypto ServiceProvider tdesProvider = new
          TripleDESCrypto ServiceProvider ();

          ICryptoTransfor m cryptoTranform =
          tdesProvider.Cr eateDecryptor(t ripleDes.Key,tr ipleDes.IV);

          MemoryStream decryptedStream = new MemoryStream();
          CryptoStream cryptStream = new
          CryptoStream(de cryptedStream,c ryptoTranform,C ryptoStreamMode .Write);
          cryptStream.Wri te(inputInBytes ,0,inputInBytes .Length);
          cryptStream.Flu shFinalBlock();
          decryptedStream .Position=0;

          Byte[] result = new Byte[decryptedStream .Length];
          decryptedStream .Read(result,0, decryptedStream .ToArray().Leng th);
          cryptStream.Clo se();

          UTF8Encoding myutf = new UTF8Encoding();
          Console.WriteLi ne(myutf.GetStr ing(result).ToS tring());
          while(Console.R ead()!='q');

          }
          }
          }


          *** Sent via Developersdex http://www.developersdex.com ***
          Don't just participate in USENET...get rewarded for it!

          Comment

          Working...