473,651 Members | 2,787 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
DESCryptoServic eProvider 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 5043
den 2005 <de*****@discus sions.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
DESCryptoServic eProvider 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.co m>
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*****@discus sions.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
DESCryptoServi ceProvider 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(plainte xt1, Key, IV)

string plaintext2 = Decrypt(cyphert ext, Key, IV).ToString()

if (plaintext != plaintext2) {
WriteLine("Fail ed")
} 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*****@discus sions.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
DESCryptoServic eProvider 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(plainte xt1, Key, IV)

    string plaintext2 = Decrypt(cyphert ext, Key, IV).ToString()

    if (plaintext != plaintext2) {
    WriteLine("Fail ed")
    } 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*****@discus sions.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 rsacryptoservic eprovider 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*****@discus sions.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*****@discus sions.microsoft .comwrote:
    >Thanks for advise, rossum.

    I have a Question, i am using rsacryptoservic eprovider 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 rsacryptoservic eprovider, 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*****@discus sions.microsoft .comwrote:
    Thanks for advise, rossum.

    I have a Question, i am using rsacryptoservic eprovider 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...R ight 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*****@discus sions.microsoft .comwrote:
    Thanks for advise, rossum.

    I have a Question, i am using rsacryptoservic eprovider 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
    2577
    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 returned data is 1161 in length. public static byte EncryptRSA(string certFilePublic, byte dataToEncrypt) { RSAParameters rsaParams = GetRSAPubKey(certFilePublic);
    2
    7142
    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 French grave... Anyway when I run encryption on a plaintext word like:
    20
    16604
    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 achieved in best way. I need it for my project. The encryption and decryption solution should be perfect such that nobody others should be able to break the key unless he/she know it( security measures) thanks in advance
    8
    2736
    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 understand why it is doing this. Below is my code, I would be greatfull if someone can guide me through the right path or even help me solve this issue. Problem: The old tool which was written in VB6 works perfect. But I needed to convert this to C#...
    0
    2366
    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 functions work fine when Two random prime numbers (required to generate public n private key) are within certain range but fails afterwords.All the variables are of datatype ULONGLONG. I m unable to fix up the problem. Is these really a storage problem...
    3
    2564
    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 GetKBSAlgorithm() { Rijndael rijndaelAlgorithm = Rijndael.Create(); rijndaelAlgorithm.IV = Convert.FromBase64String(tbIV.Text);
    13
    3579
    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 removed" on the decryption piece. From everything I can see, I am doing things correctly here My code is as follows: private const string PassStr = "MyPrivateKey"; private static readonly byte PassSalt = new byte { Byte Byte Byte Byte Byte};...
    5
    9506
    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 code for a few hours: #dics Encryption={',':'hy{;',' ':'h4x0r2','':'zomg','?':'bko','a':'ika','b':'d0v','c':'ino', 'd':'maw', 'e':'aon', 'f':'que', 'g':'kip', 'h':'an', 'n':'ko print lol except KeyError: print 'These...
    9
    4811
    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 . I didn't test script on windows. Here is the code, please send me your views. <?php /* Mother Eye Chipper with PHP :), Licence:GPL,
    0
    8352
    marktang
    by: marktang | last post by:
    ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
    0
    8275
    by: Hystou | last post by:
    Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
    0
    8802
    Oralloy
    by: Oralloy | last post by:
    Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
    1
    8465
    by: Hystou | last post by:
    Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
    0
    5612
    by: conductexam | last post by:
    I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
    0
    4144
    by: TSSRALBI | last post by:
    Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
    0
    4283
    by: adsilva | last post by:
    A Windows Forms form does not have the event Unload, like VB6. What one acts like?
    1
    2699
    by: 6302768590 | last post by:
    Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
    1
    1909
    muto222
    by: muto222 | last post by:
    How can i add a mobile payment intergratation into php mysql website.

    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.