Click here to Skip to main content
15,868,164 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The below code is not running to encrypy a string using a public key which is stored in .xml file
C#
public string EncryptData(string data2Encrypt,string publicPath)
    {
            string publicpath = System.Web.HttpContext.Current.Server.MapPath(publicPath);
        StreamReader reader = new StreamReader(publicpath);
        string publicOnlyKeyXML = reader.ReadToEnd();
        rsa.FromXmlString(publicOnlyKeyXML);
        reader.Close();
        try
        {  //encrypt
            byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt);
          /* #1*/ byte[] cipherbytes = rsa.Encrypt(plainbytes, false);
            return Convert.ToBase64String(cipherbytes);
        }
        catch (Exception ex)
        {
            
        }
      
    }


Tha above code is giving error called " not all code paths return a value" and the error is at line #1...
is this code not enough to encrypt a string?
Please Help
Posted

1 solution

Fix your code:

C#
public string EncryptData(string data2Encrypt,string publicPath)
{
    string retVal = null;
    string publicpath = System.Web.HttpContext.Current.Server.MapPath(publicPath);
    StreamReader reader = new StreamReader(publicpath);
    string publicOnlyKeyXML = reader.ReadToEnd();
    rsa.FromXmlString(publicOnlyKeyXML);
    reader.Close();
    try
    {  //encrypt
        byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt);
      /* #1*/ byte[] cipherbytes = rsa.Encrypt(plainbytes, false);
        retVal = Convert.ToBase64String(cipherbytes);
    }
    catch (Exception ex)
    {
        // Do something appropriate here
    }
    return retVal;
}


A method that returns a string must return a string. In your case if an exception would have occurred there would have been no appropriate return statement.

It's good practice to have only one point of exit in a non void method and it should be the last statement in the method to avoid unreachable code warnings.

Cheers!
 
Share this answer
 
v3
Comments
Sergey Alexandrovich Kryukov 11-Feb-11 16:46pm    
Good catch, a 5,
--SA
Supratik sadhuka 11-Feb-11 16:51pm    
Thanks a lot..the error gets removed ..but the string is not encrypted...nything wrong with d logic?
Manfred Rudolf Bihy 11-Feb-11 17:47pm    
Why don't you debug your application and see at each step what the current state is?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900