The goal:
0)RSAObject:
- Encrypt : takes a plain text string and returns an encrypted string.
- Decrypt: takes an encrypted string and returns a plain text string.
- Generate a RSA public and private key.
- Pass the public key in plain text to the client
- Pass a plain string to RSAObject
- Pass encrypted string from RSAObject to Server.
- Pass encrypted string to RSAObject
- Use decrypted string from RSAObject.
PROBLEMS:
My origional code for encrypting and decrypting data:
public string Encrypt(string plainText)
{
try
{
byte[] plainData = Encoding.UTF32.GetBytes(plainText);
byte[] encryptedData = crypto.Encrypt(plainData, true);
return Encoding.UTF32.GetString(encryptedData);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return "";
}
}
public string Decrypt(string encryptedText)
{
try
{
byte[] encryptedData = Encoding.UTF32.GetString(encryptedText);
byte[] plainData = crypto.Decrypt(encryptedData, true);
return Encoding.UTF32.GetString(plainData);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return "";
}
}
All I would get during decryption from crypto, a RSACryptoServiceProvider object, was one of two exceptions:
- Bad Length
- Error occurred while decoding OAEP padding.
SOLUTION:
Encrypt method needs to convert to a 64bit string.
Decrypt method needs to convert from a 64bit string.
fixed and working source code:
public string Encrypt(string plainText)
{
try
{
byte[] plainData = Encoding.UTF32.GetBytes(plainText);
byte[] encryptedData = crypto.Encrypt(plainData, true);
return Convert.ToBase64String(encryptedData);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return "";
}
}
public string Decrypt(string encryptedText)
{
try
{
byte[] encryptedData = Convert.FromBase64String(encryptedText);
byte[] plainData = crypto.Decrypt(encryptedData, true);
return Encoding.UTF32.GetString(plainData);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return "";
}
}
cheers,
-bb
No comments:
Post a Comment