CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Sep 2009
    Posts
    0

    DES converstion from Java to c#

    Hi,

    I am trying to convert DES with added salt to c# code. I am using the below code for the converstion

    public static string Encrypt(string toEncrypt, bool useHashing)
    {
    byte[] keyArray;
    byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

    System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
    // Get the key from config file
    string key = "Secret Key";

    byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
    byte[] keyBytes = new byte[0x10];
    int len = pwdBytes.Length;
    if (len > keyBytes.Length)
    {
    len = keyBytes.Length;
    }
    Array.Copy(pwdBytes, keyBytes, len);

    DESCryptoServiceProvider tdes = new DESCryptoServiceProvider();
    tdes.Key = keyBytes;
    tdes.Mode = CipherMode.ECB;
    tdes.Padding = PaddingMode.Zeros;

    ICryptoTransform cTransform = tdes.CreateEncryptor();
    byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
    tdes.Clear();
    return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }

    This code gives me following error "Specified key is not a valid size for this algorithm." Can you please let me know if I need do anything specific to convert java code to c#.

    Thanks,
    Dan

  2. #2
    Join Date
    Mar 2004
    Location
    33°11'18.10"N 96°45'20.28"W
    Posts
    1,808

    Re: DES converstion from Java to c#

    string key = "Secret K";

    just like it said. the key was too long. it needs to be 8 bytes long. Not sure whether using UTF8 encoding will prefix the resultant bytes w/ the BOM of UTF8, but if so, the above string will not work either.

    either do not use a string or use ascii encoding for your key, and keep it 8 bytes long.

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