473,378 Members | 1,436 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

Decryption is not working..wrong text

Hi everybody,

I am not sure where to put this in this forum. So, I posted this at
several topics. I created a class library that has two public methods
Encrypt() and Decrypt(). I reference this dll to a window application. I used
DESCryptoServiceProvider Algorithm to encrypt and decrypt then with same Key
and IV. But unable to decrypt it back to original text. This project I plan
to use all algorithm and Hash. This is Phase One. There is no problem
ingenerating the Key and IV and at both encrypt and decrypt they are the
same. Can anyone spot the mistake and know how to correct this? Thanks.

Expand|Select|Wrap|Line Numbers
  1.  
  2. //Generate a Key
  3. private static void GenerateDESKey(DESCryptoServiceProvider
  4. desProv,int keySize,bool maxKeySize)
  5. {
  6. if (Key == null)
  7. {
  8. if (keySize != 0)
  9. desProv.KeySize = keySize;
  10. else
  11. {
  12. KeySizes[] keySizeSets = desProv.LegalKeySizes;
  13. int len = keySizeSets.Length;
  14.  
  15. for (int x = 0; x < len; x++)
  16. {
  17. if (maxKeySize)
  18. keySize = keySizeSets[0].MaxSize;
  19. else
  20. keySize = keySizeSets[0].MinSize;
  21. }
  22. }
  23. desProv.KeySize = keySize;
  24. desProv.GenerateKey();
  25. Key = desProv.Key;
  26. }
  27. }
  28.  
  29. //Generate a IV
  30. private static void GenerateDESIV(DESCryptoServiceProvider desProv)
  31. {
  32. if (IV == null)
  33. {
  34. desProv.GenerateIV();
  35. IV = desProv.IV;
  36. }
  37. }
  38.  
  39. //Encrypting String Data passed as parameter and returns it
  40. public string Encrypt(string strData,int keySize, bool bMaxSize)
  41. {
  42. string strEncrypt = string.Empty;
  43. try
  44. {
  45. //Variable Telling if Crypto or Managed object is selected
  46. MemoryStream memStream = new MemoryStream();
  47.  
  48. CryptoStream cryptStream;
  49. UnicodeEncoding byteConvert = new UnicodeEncoding();
  50. byte[] byteData = byteConvert.GetBytes(strData);
  51.  
  52. byte[] encryptedData = { };
  53.  
  54.  
  55. if (this.CRYPTOCLASS == Algorithm.DES.ToString())
  56. {
  57. this.CreateDESCrypto();
  58. if (des != null)
  59. {
  60. //Generate Cryptographic Key and saved it
  61. GenerateDESKey(des, keySize, bMaxSize);
  62. //Generate Cryptographic IV and saved it
  63. GenerateDESIV(des);
  64.  
  65. transform = des.CreateEncryptor((byte[])Key.Clone(),
  66. (byte[])IV.Clone());
  67. }
  68. }
  69. . . . .
  70. //Use the created algorithm object to encrypt data
  71. cryptStream = new CryptoStream(memStream, transform,
  72. CryptoStreamMode.Write);
  73.  
  74. cryptStream.Write(byteData, 0, byteData.Length);
  75. cryptStream.FlushFinalBlock();
  76.  
  77. encryptedData = memStream.ToArray();
  78.  
  79. memStream.Close();
  80. cryptStream.Close();
  81. transform.Dispose();
  82.  
  83. //Call to dispose data
  84. this.DisposeActiveObjects();
  85. //Convert encrypted bytes[] back to string
  86. strEncrypt = Convert.ToBase64String(encryptedData);
  87.  
  88. }
  89. catch (Exception ex)
  90. {
  91. this.WriteAppendLogFile(", Encrypt() " + ex.ToString());
  92. }
  93. return strEncrypt;
  94. }
  95.  
  96. //Decrypting String Data passed as parameter and returns it
  97. public string Decrypt(string strEncrypt)
  98. {
  99. string strData = string.Empty;
  100. try
  101. {
  102. //Variable Telling if Crypto or Managed object is selected
  103.  
  104. //Check if Key and IV is still has data
  105. if (Key == null || IV == null)
  106. {
  107. return "Cryptographic Key and IV cannot be null.";
  108. }
  109. MemoryStream memStream;
  110. CryptoStream cryptStream;
  111. byte[] encryptedData = Convert.FromBase64String(strEncrypt);
  112. byte[] decryptedData = new Byte[encryptedData.Length];
  113.  
  114. if (this.CRYPTOCLASS == Algorithm.DES.ToString())
  115. {
  116. this.CreateDESCrypto();
  117. transform = des.CreateDecryptor((byte[])
  118. Key.Clone(),(byte[])IV.Clone());
  119.  
  120. }
  121. ........
  122.  
  123. //Use the created algorithm object to encrypt data
  124. memStream = new MemoryStream(encryptedData);
  125. cryptStream = new CryptoStream(memStream, transform,
  126. CryptoStreamMode.Read);
  127.  
  128. cryptStream.Read(decryptedData, 0, decryptedData.Length);
  129.  
  130. memStream.Close();
  131. cryptStream.Close();
  132. transform.Dispose();
  133.  
  134. //Call to dispose data
  135. this.DisposeActiveObjects();
  136. //Convert encrypted bytes[] back to string
  137. //strEncrypt = Convert.ToBase64String(decryptedData);
  138. strData = Encoding.ASCII.GetString(decryptedData);
  139. }
  140. catch (Exception ex)
  141. {
  142. this.WriteAppendLogFile(", Decrypt() " + ex.ToString());
  143. }
  144. return strData;
  145. }
  146.  
den2005


--
MCP Year 2005, Philippines
--
MCP Year 2005, Philippines
Jul 19 '06 #1
8 5025
den 2005 <de*****@discussions.microsoft.comwrote:
I am not sure where to put this in this forum. So, I posted this at
several topics. I created a class library that has two public methods
Encrypt() and Decrypt(). I reference this dll to a window application. I used
DESCryptoServiceProvider Algorithm to encrypt and decrypt then with same Key
and IV. But unable to decrypt it back to original text. This project I plan
to use all algorithm and Hash. This is Phase One. There is no problem
ingenerating the Key and IV and at both encrypt and decrypt they are the
same. Can anyone spot the mistake and know how to correct this? Thanks.
Well, you've provided quite a lot of code, but not enough for us to
just compile and run.

Could you post a short but complete program which demonstrates the
problem?

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

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jul 19 '06 #2
On Wed, 19 Jul 2006 01:54:01 -0700, den 2005
<de*****@discussions.microsoft.comwrote:
>Hi everybody,

I am not sure where to put this in this forum. So, I posted this at
several topics. I created a class library that has two public methods
Encrypt() and Decrypt(). I reference this dll to a window application. I used
DESCryptoServiceProvider Algorithm to encrypt and decrypt then with same Key
and IV. But unable to decrypt it back to original text. This project I plan
to use all algorithm and Hash. This is Phase One. There is no problem
ingenerating the Key and IV and at both encrypt and decrypt they are the
same. Can anyone spot the mistake and know how to correct this? Thanks.

Expand|Select|Wrap|Line Numbers
  1. [snip]
  2.         
  3.                 >
  4.  
  5.  
1 Why are you using DES rather than AES? DES is now obsolete.
Triple-DES is acceptable if you have to link with an existing
application. Use AES for anything else.

2 Your application returns strData even if it finds an exception, this
is a potential security leak. Whenever an exception is thrown you
need to destroy all information for the current message, both
cyphertext and plaintext. Dispose as much as you can, set every
element of encryptedData[] and decryptedData[] to zero. Set strData
to string.Empty. Ideally you should wipe the previous contents of
strData first:

unsafe void OverwriteString(string text) {
const char overwriteChar = 'X';
fixed (char* cp = text) {
for (int i = 0; i < text.Length; ++i) {
cp[i] = overwriteChar;
} // end for
} // end fixed
} // end OverwriteString()

3 Your code is very complex, to me at least it looks more complex then
it needs to be. For security stuff keeeping it simple with very few
options is better; if your users do not have to option to select
keySize then they cannot make the mistake of selecting one that is too
small - keySize = 1? Take out as much of the complexity as you can.

3 To find the problem simplify and see if the problem persists,
something like:

[pseudocode]
byte[] Key = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}
byte[] IV = {0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}
string plaintext1 = "Hello World!"

byte[] cyphertext = Encrypt(plaintext1, Key, IV)

string plaintext2 = Decrypt(cyphertext, Key, IV).ToString()

if (plaintext != plaintext2) {
WriteLine("Failed")
} else {
WriteLine("OK")
}
[/pseudocode]

It will be much easier for you to see problems in the simpler code.
Once the simple code is working you can add back the required
complications one at a time, retesting after each new complication.

4 You are using Unicode and ASCII encodings at different places. It
might be worth checking that the mixed character codings are not
causing the problem rather than the encryption/decryption.
rossum
Jul 19 '06 #3
Thanks for the reply, Jon. I got idea reply from another post and reply of
rossum in this forum.

Thanks for long reply, rossum. Thanks for tip of cleaning all variable for
security reasons. AES? I would try using fixed key and init vector(IV).
I am new in cryptography, so don't know what is working. I would like to use
the best byte[] conversion to allow all possibilities of keys entered to be
encrypted including special keys and to be used to encrypt web configuration
sections (web.config).
What exactly Padding does? It adds remaining bits if encrypted data is only
40 and allowed is 64 bits, how about if encrypted data is over 64 bits what
happen to rest of encrypted data?

Dennis

--
MCP Year 2005, Philippines
"rossum" wrote:
On Wed, 19 Jul 2006 01:54:01 -0700, den 2005
<de*****@discussions.microsoft.comwrote:
Hi everybody,

I am not sure where to put this in this forum. So, I posted this at
several topics. I created a class library that has two public methods
Encrypt() and Decrypt(). I reference this dll to a window application. I used
DESCryptoServiceProvider Algorithm to encrypt and decrypt then with same Key
and IV. But unable to decrypt it back to original text. This project I plan
to use all algorithm and Hash. This is Phase One. There is no problem
ingenerating the Key and IV and at both encrypt and decrypt they are the
same. Can anyone spot the mistake and know how to correct this? Thanks.
Expand|Select|Wrap|Line Numbers
  1. [snip]
  2.         
  3.  
  •  
  •  

  • 1 Why are you using DES rather than AES? DES is now obsolete.
    Triple-DES is acceptable if you have to link with an existing
    application. Use AES for anything else.

    2 Your application returns strData even if it finds an exception, this
    is a potential security leak. Whenever an exception is thrown you
    need to destroy all information for the current message, both
    cyphertext and plaintext. Dispose as much as you can, set every
    element of encryptedData[] and decryptedData[] to zero. Set strData
    to string.Empty. Ideally you should wipe the previous contents of
    strData first:

    unsafe void OverwriteString(string text) {
    const char overwriteChar = 'X';
    fixed (char* cp = text) {
    for (int i = 0; i < text.Length; ++i) {
    cp[i] = overwriteChar;
    } // end for
    } // end fixed
    } // end OverwriteString()

    3 Your code is very complex, to me at least it looks more complex then
    it needs to be. For security stuff keeeping it simple with very few
    options is better; if your users do not have to option to select
    keySize then they cannot make the mistake of selecting one that is too
    small - keySize = 1? Take out as much of the complexity as you can.

    3 To find the problem simplify and see if the problem persists,
    something like:

    [pseudocode]
    byte[] Key = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}
    byte[] IV = {0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}
    string plaintext1 = "Hello World!"

    byte[] cyphertext = Encrypt(plaintext1, Key, IV)

    string plaintext2 = Decrypt(cyphertext, Key, IV).ToString()

    if (plaintext != plaintext2) {
    WriteLine("Failed")
    } else {
    WriteLine("OK")
    }
    [/pseudocode]

    It will be much easier for you to see problems in the simpler code.
    Once the simple code is working you can add back the required
    complications one at a time, retesting after each new complication.

    4 You are using Unicode and ASCII encodings at different places. It
    might be worth checking that the mixed character codings are not
    causing the problem rather than the encryption/decryption.
    rossum
    Jul 20 '06 #4
    On Wed, 19 Jul 2006 19:46:01 -0700, den 2005
    <de*****@discussions.microsoft.comwrote:
    >Thanks for the reply, Jon. I got idea reply from another post and reply of
    rossum in this forum.

    Thanks for long reply, rossum. Thanks for tip of cleaning all variable for
    security reasons. AES? I would try using fixed key and init vector(IV).
    I am new in cryptography, so don't know what is working. I would like to use
    the best byte[] conversion to allow all possibilities of keys entered to be
    encrypted including special keys and to be used to encrypt web configuration
    sections (web.config).
    What exactly Padding does? It adds remaining bits if encrypted data is only
    40 and allowed is 64 bits, how about if encrypted data is over 64 bits what
    happen to rest of encrypted data?

    Dennis
    If you want to learn about cryptography, the best place to start is
    "Practical Cryptography" by Ferguson and Schneier.

    For web resources, Wikipedia is very good and also the "Handbook of
    Applied Cryptography" at www.cacr.math.uwaterloo.ca/hac. On usenet
    sci.crypt can be useful for answers from experts, though discussion
    can get a bit fierce at times.

    There are many free cypher libraries around if you want to look at
    other people's code, though most of them will be in C, C++ or Java
    rather than C#.

    As to your specific questions. Padding is used when the data size may
    not be an exact multiple of the block size so the last block has to be
    padded. See Wikipedia: Padding (cryptography).

    For dealing with data more than a block size you need to look at mode
    of operation - Wikipedia: Block cipher modes of operation. These are
    the CBC, CTR and other mysterious letters you might see sometimes.
    The formal definitions are in NIST at
    http://csrc.nist.gov/publications/ni.../sp800-38a.pdf

    The basic advice to beginners is not to try to do anything real (i.e.
    on a commercial basis) yourself but to get in an expert. It is fine
    to play for yourself but this is a field where tiny errors can have
    big consequences so newbies need to stay from real work until they
    have developed enough background.

    rossum

    Jul 20 '06 #5
    Thanks for advise, rossum.

    I have a Question, i am using rsacryptoserviceprovider to encrypt and
    decrypt, I tried several approach, one approach produces error "Bad Data",
    another tells me "Invalid length for a Base 64 Char Array", another says "The
    data to be decrypted exceeds the maximum for this modulus of 128 bytes".

    How exactly would be proper to convert string to bytes, encrypt it using rsa
    algorithm, then convert the bytes data back to string for display, and then
    used this string data as input to be converted back to bytes for decryption
    and the resulting bytes data converted back to string (which should be same
    as original text before encryption)? I will look at those links you
    mentioned. Thanks.

    Here are part of codes I used to do this:

    Expand|Select|Wrap|Line Numbers
    1. public string Encrypt(string strData)
    2. {
    3. string strData = string.Empty;
    4. try
    5. {
    6. . .. .
    7. UnicodeEncoding byteConvert = new UnicodeEncoding();
    8. byte[] byteData = byteConvert.GetBytes(strData);
    9. //byte[] byteData = Encoding.Unicode.GetBytes(strData);
    10.  
    11. .......
    12. encryptedData = rsa.Encrypt(byteData, false);
    13. return Convert.ToBase64String(encryptedData);
    14. . . . .
    15. }
    16. catch (Exception ex)
    17. {
    18. . . . .
    19. }
    20. return strData;
    21. }
    22.  
    23. public string Decrypt(string strEncrypt)
    24. {
    25. .....
    26. UnicodeEncoding byteConvert = new UnicodeEncoding();
    27. byte[] encryptedData = byteConvert.GetBytes(strEncrypt);
    28. //byte[] byteData = Encoding.Unicode.GetBytes(strEncrypt);
    29.  
    30. .......
    31. decryptedData = rsa.Decrypt(encryptedData, false);
    32. return Convert.ToBase64String(decryptedData);
    33. ......
    34. }
    35.  
    den2005

    --
    MCP Year 2005, Philippines
    "rossum" wrote:
    On Wed, 19 Jul 2006 19:46:01 -0700, den 2005
    <de*****@discussions.microsoft.comwrote:
    Thanks for the reply, Jon. I got idea reply from another post and reply of
    rossum in this forum.

    Thanks for long reply, rossum. Thanks for tip of cleaning all variable for
    security reasons. AES? I would try using fixed key and init vector(IV).
    I am new in cryptography, so don't know what is working. I would like to use
    the best byte[] conversion to allow all possibilities of keys entered to be
    encrypted including special keys and to be used to encrypt web configuration
    sections (web.config).
    What exactly Padding does? It adds remaining bits if encrypted data is only
    40 and allowed is 64 bits, how about if encrypted data is over 64 bits what
    happen to rest of encrypted data?

    Dennis

    If you want to learn about cryptography, the best place to start is
    "Practical Cryptography" by Ferguson and Schneier.

    For web resources, Wikipedia is very good and also the "Handbook of
    Applied Cryptography" at www.cacr.math.uwaterloo.ca/hac. On usenet
    sci.crypt can be useful for answers from experts, though discussion
    can get a bit fierce at times.

    There are many free cypher libraries around if you want to look at
    other people's code, though most of them will be in C, C++ or Java
    rather than C#.

    As to your specific questions. Padding is used when the data size may
    not be an exact multiple of the block size so the last block has to be
    padded. See Wikipedia: Padding (cryptography).

    For dealing with data more than a block size you need to look at mode
    of operation - Wikipedia: Block cipher modes of operation. These are
    the CBC, CTR and other mysterious letters you might see sometimes.
    The formal definitions are in NIST at
    http://csrc.nist.gov/publications/ni.../sp800-38a.pdf

    The basic advice to beginners is not to try to do anything real (i.e.
    on a commercial basis) yourself but to get in an expert. It is fine
    to play for yourself but this is a field where tiny errors can have
    big consequences so newbies need to stay from real work until they
    have developed enough background.

    rossum

    Jul 20 '06 #6
    On Thu, 20 Jul 2006 17:01:02 -0700, den 2005
    <de*****@discussions.microsoft.comwrote:
    >Thanks for advise, rossum.

    I have a Question, i am using rsacryptoserviceprovider to encrypt and
    decrypt, I tried several approach, one approach produces error "Bad Data",
    another tells me "Invalid length for a Base 64 Char Array", another says "The
    data to be decrypted exceeds the maximum for this modulus of 128 bytes".

    How exactly would be proper to convert string to bytes, encrypt it using rsa
    algorithm, then convert the bytes data back to string for display, and then
    used this string data as input to be converted back to bytes for decryption
    and the resulting bytes data converted back to string (which should be same
    as original text before encryption)? I will look at those links you
    mentioned. Thanks.

    Here are part of codes I used to do this:

    Expand|Select|Wrap|Line Numbers
    1. public string Encrypt(string strData)
    2. {
    3.    string strData = string.Empty;
    Expand|Select|Wrap|Line Numbers
    1. strData is your original parameter.  Perhaps you meant to declare
    2. encryptedData here.
    3.  
    4.         
    5.                   try
    6.   {
    7.       . .. .
    8.      UnicodeEncoding byteConvert = new UnicodeEncoding();
    9.      byte[] byteData = byteConvert.GetBytes(strData);
    10.      //byte[] byteData = Encoding.Unicode.GetBytes(strData);
    11.      .......
    12.      encryptedData = rsa.Encrypt(byteData, false);
    13.  
    14. rsa is undeclared - you need to post enough code that I can compile
    15. it.
    16.         
    17.                      return Convert.ToBase64String(encryptedData);
    18.     . . . .
    19.   }
    20.   catch (Exception ex)
    21.   {
    22.      . . . .
    23.   }
    24.   return strData;
    25.  
    26. I suspect that you want to return encryptedData here, not merely
    27. returning the original input parameter.
    28.  
    29.         
    30.                 >}
    31. public string Decrypt(string strEncrypt)
    32. {
    33.    .....
    34.    UnicodeEncoding byteConvert = new UnicodeEncoding();
    35.    byte[] encryptedData = byteConvert.GetBytes(strEncrypt);
    36.  
    37. encryptedData is undeclared here, I suspect you meant decryptedData
    38. which you use below.
    39.  
    40.         
    41.                   //byte[] byteData = Encoding.Unicode.GetBytes(strEncrypt);
    42.    .......
    43.    decryptedData = rsa.Decrypt(encryptedData, false);
    44.  
    45. decryptedData is undeclared here.
    46.         
    47.                    return Convert.ToBase64String(decryptedData);
    48.  
    49. Why are you returning a Base-64 string here?  The original data was a
    50. string, not a Base-64 string.
    51.         
    52.                    ......
    53. }
    54.  
    55.  
    >
    den2005
    When posting code cut and paste the code from your code editor, do not
    attempt to retype it.

    Post enough code to compile immediately without any changes.

    Post the minimum of code needed to show the problem. In this case
    take out all the try/catch parts, and remove the various conversions,
    work everything as byte arrays. It is easy enough to write a simple
    functions to test two arrays for equality.

    rossum

    Jul 21 '06 #7
    Hi rossum,

    I think I solved using rsacryptoserviceprovider, right now testing
    rng...it seems similar to random class. Is there?

    Thanks for reply..

    Dennis
    --
    MCP Year 2005, Philippines
    "rossum" wrote:
    On Thu, 20 Jul 2006 17:01:02 -0700, den 2005
    <de*****@discussions.microsoft.comwrote:
    Thanks for advise, rossum.

    I have a Question, i am using rsacryptoserviceprovider to encrypt and
    decrypt, I tried several approach, one approach produces error "Bad Data",
    another tells me "Invalid length for a Base 64 Char Array", another says "The
    data to be decrypted exceeds the maximum for this modulus of 128 bytes".

    How exactly would be proper to convert string to bytes, encrypt it using rsa
    algorithm, then convert the bytes data back to string for display, and then
    used this string data as input to be converted back to bytes for decryption
    and the resulting bytes data converted back to string (which should be same
    as original text before encryption)? I will look at those links you
    mentioned. Thanks.

    Here are part of codes I used to do this:

    Expand|Select|Wrap|Line Numbers
    1. public string Encrypt(string strData)
    2. {
    3.     string strData = string.Empty;
    Expand|Select|Wrap|Line Numbers
    1. strData is your original parameter.  Perhaps you meant to declare
    2. encryptedData here.
    3.         
    4.                    try
    5.    {
    6.        . .. .
    7.       UnicodeEncoding byteConvert = new UnicodeEncoding();
    8.       byte[] byteData = byteConvert.GetBytes(strData);
    9.       //byte[] byteData = Encoding.Unicode.GetBytes(strData);
    10.  
    11.       .......
    12.       encryptedData = rsa.Encrypt(byteData, false);
  •  
  • rsa is undeclared - you need to post enough code that I can compile
  • it.
  •         
  •                       return Convert.ToBase64String(encryptedData);
  •      . . . .
  •    }
  •    catch (Exception ex)
  •    {
  •       . . . .
  •    }
  •    return strData;
  •  
  • I suspect that you want to return encryptedData here, not merely
  • returning the original input parameter.
  •         
  •                 }
  •  
  • public string Decrypt(string strEncrypt)
  • {
  •     .....
  •     UnicodeEncoding byteConvert = new UnicodeEncoding();
  •     byte[] encryptedData = byteConvert.GetBytes(strEncrypt);
  •  
  • encryptedData is undeclared here, I suspect you meant decryptedData
  • which you use below.
  •         
  •                    //byte[] byteData = Encoding.Unicode.GetBytes(strEncrypt);
  •  
  •     .......
  •     decryptedData = rsa.Decrypt(encryptedData, false);
  •  
  • decryptedData is undeclared here.
  •         
  •                     return Convert.ToBase64String(decryptedData);
  •  
  • Why are you returning a Base-64 string here?  The original data was a
  • string, not a Base-64 string.
  •         
  •                     ......
  • }
  •  
  •  

  • den2005

    When posting code cut and paste the code from your code editor, do not
    attempt to retype it.

    Post enough code to compile immediately without any changes.

    Post the minimum of code needed to show the problem. In this case
    take out all the try/catch parts, and remove the various conversions,
    work everything as byte arrays. It is easy enough to write a simple
    functions to test two arrays for equality.

    rossum

    Jul 24 '06 #8
    Sorry for that..I try next time to post more complete codes without exposing
    unnecessary connections...Right now, using cryptography on web.config. Thanks
    again.

    Dennis

    --
    MCP Year 2005, Philippines
    "rossum" wrote:
    On Thu, 20 Jul 2006 17:01:02 -0700, den 2005
    <de*****@discussions.microsoft.comwrote:
    Thanks for advise, rossum.

    I have a Question, i am using rsacryptoserviceprovider to encrypt and
    decrypt, I tried several approach, one approach produces error "Bad Data",
    another tells me "Invalid length for a Base 64 Char Array", another says "The
    data to be decrypted exceeds the maximum for this modulus of 128 bytes".

    How exactly would be proper to convert string to bytes, encrypt it using rsa
    algorithm, then convert the bytes data back to string for display, and then
    used this string data as input to be converted back to bytes for decryption
    and the resulting bytes data converted back to string (which should be same
    as original text before encryption)? I will look at those links you
    mentioned. Thanks.

    Here are part of codes I used to do this:

    Expand|Select|Wrap|Line Numbers
    1. public string Encrypt(string strData)
    2. {
    3.     string strData = string.Empty;
    Expand|Select|Wrap|Line Numbers
    1. strData is your original parameter.  Perhaps you meant to declare
    2. encryptedData here.
    3.         
    4.                    try
    5.    {
    6.        . .. .
    7.       UnicodeEncoding byteConvert = new UnicodeEncoding();
    8.       byte[] byteData = byteConvert.GetBytes(strData);
    9.       //byte[] byteData = Encoding.Unicode.GetBytes(strData);
    10.  
    11.       .......
    12.       encryptedData = rsa.Encrypt(byteData, false);
  •  
  • rsa is undeclared - you need to post enough code that I can compile
  • it.
  •         
  •                       return Convert.ToBase64String(encryptedData);
  •      . . . .
  •    }
  •    catch (Exception ex)
  •    {
  •       . . . .
  •    }
  •    return strData;
  •  
  • I suspect that you want to return encryptedData here, not merely
  • returning the original input parameter.
  •         
  •                 }
  •  
  • public string Decrypt(string strEncrypt)
  • {
  •     .....
  •     UnicodeEncoding byteConvert = new UnicodeEncoding();
  •     byte[] encryptedData = byteConvert.GetBytes(strEncrypt);
  •  
  • encryptedData is undeclared here, I suspect you meant decryptedData
  • which you use below.
  •         
  •                    //byte[] byteData = Encoding.Unicode.GetBytes(strEncrypt);
  •  
  •     .......
  •     decryptedData = rsa.Decrypt(encryptedData, false);
  •  
  • decryptedData is undeclared here.
  •         
  •                     return Convert.ToBase64String(decryptedData);
  •  
  • Why are you returning a Base-64 string here?  The original data was a
  • string, not a Base-64 string.
  •         
  •                     ......
  • }
  •  
  •  

  • den2005

    When posting code cut and paste the code from your code editor, do not
    attempt to retype it.

    Post enough code to compile immediately without any changes.

    Post the minimum of code needed to show the problem. In this case
    take out all the try/catch parts, and remove the various conversions,
    work everything as byte arrays. It is easy enough to write a simple
    functions to test two arrays for equality.

    rossum

    Jul 25 '06 #9

    This thread has been closed and replies have been disabled. Please start a new discussion.

    Similar topics

    2
    by: sushant.bhatia | last post by:
    Hi All. I'm using the NCrypto dll for RSA Encryption/Decryption (http://sourceforge.net/projects/ncrypto/). My encryption code in .Net is pretty simple. The dataToEncrypt length is 1024. The...
    2
    by: almurph | last post by:
    Hi everyone, Can you help me please? I am having a problem with the encryption/decryption of words with the Irish fada in them. The Irish fada is like this: αινσϊ/ΑΙΝΣΪ. It's kind of like the...
    20
    by: vermarajeev | last post by:
    Hi guys, I have some text files. I need to encrypt the files and then decrypt it again. This is my first experience in encryption and decryption. I want some suggestions about how this can be...
    8
    by: manmit.walia | last post by:
    Hello Everyone, Long time ago, I posted a small problem I had about converting a VB6 program to C#. Well with the help with everyone I got it converted. But I overlooked something and don't...
    0
    by: Dipanwita | last post by:
    I have written a RSA encryption/decryption function in c using the formula a = b^c %n. For solving the equation I have used Squaring and multiplying method for modulo exponentiation . These...
    3
    by: KBS Developer | last post by:
    Hi, I can encrypt without any problem but while decrypting I got junk. I've read the other thread about getting junk but that is not my case. Here is the sample code: private Rijndael...
    13
    by: Tom Andrecht | last post by:
    I'm trying to get some encryption/decryption routines going to take care of my data, and while the encryption is working great, I keep running into the message "Padding is invalid and cannot be...
    5
    by: Netwatcher | last post by:
    well, i started messing around with dictionaries, yet, most of the pages i found about them always talk about getting only one word out of it and turning it vice versa, i've been playing with that...
    9
    by: Betikci Boris | last post by:
    I get bored last night and wrote a script that uses xor for encrypt- decrypt, however it woks fine under linux 2.6.25, text and documents are ok, but fails on compressed files *.jpg, *.pdf , etc ....
    0
    by: ryjfgjl | last post by:
    In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
    0
    by: taylorcarr | last post by:
    A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
    0
    by: Charles Arthur | last post by:
    How do i turn on java script on a villaon, callus and itel keypad mobile phone
    0
    by: ryjfgjl | last post by:
    If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
    0
    by: ryjfgjl | last post by:
    In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
    0
    BarryA
    by: BarryA | last post by:
    What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
    1
    by: nemocccc | last post by:
    hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
    1
    by: Sonnysonu | last post by:
    This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
    0
    by: Hystou | last post by:
    There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

    By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

    To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.