使用加密功能的RSA加密问题 [英] RSA encryption problem using Encrypt function

查看:61
本文介绍了使用加密功能的RSA加密问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码无法运行以使用存储在.xml文件中的公共密钥来加密字符串

The below code is not running to encrypy a string using a public key which is stored in .xml file

<pre lang="cs">public string EncryptData(string data2Encrypt,string publicPath)<br />
    {<br />
            string publicpath = System.Web.HttpContext.Current.Server.MapPath(publicPath);<br />
        StreamReader reader = new StreamReader(publicpath);<br />
        string publicOnlyKeyXML = reader.ReadToEnd();<br />
        rsa.FromXmlString(publicOnlyKeyXML);<br />
        reader.Close();<br />
        try<br />
        {  //encrypt<br />
            byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt);<br />
          /* #1*/ byte[] cipherbytes = rsa.Encrypt(plainbytes, false);<br />
            return Convert.ToBase64String(cipherbytes);<br />
        }<br />
        catch (Exception ex)<br />
        {<br />
            <br />
        }<br />
      <br />
    }</pre><br />



上面的代码给出了一个错误,即并非所有代码路径都返回一个值",并且错误在第1行...
这段代码不足以加密字符串吗?
请帮助



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

推荐答案

修复您的代码:

Fix your code:

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;
}



返回字符串的方法必须返回字符串.在您的情况下,如果将发生异常,将没有适当的return语句.

优良作法是在非void方法中只有一个退出点,并且应该是该方法中的最后一条语句,以避免出现无法到达的代码警告.

干杯!



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!


这篇关于使用加密功能的RSA加密问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆