C#RSA加密解密

首先是密钥对的生成

    /// <summary>  
    /// 生成公钥、私钥  
    /// </summary>  
    /// <returns>公钥、私钥,公钥键"PUBLIC",私钥键"PRIVATE"</returns>  
       public Dictionary<string, string> createKeyPair()  
       {  
           Dictionary<string, string> keyPair = new Dictionary<string, string>();  
           RSACryptoServiceProvider provider = new RSACryptoServiceProvider(1024);  
           keyPair.Add("PUBLIC", provider.ToXmlString(false));  
           keyPair.Add("PRIVATE", provider.ToXmlString(true));  
           return keyPair;  
       }  

记住私钥和公钥一定是一对,楼主曾经分两次生成公钥和私钥。把公钥提供给java端进行与c#端的互通RSA互通。因为这个低级的小错误,使调试失败。

然后是c#的加密

    /// <summary>
    /// 加密数据
    /// </summary>
    /// <param name="toEncryptString">要解密的数据</param>
    /// <returns></returns>
    static public string Encrypt(string toEncryptString, string PrivateKey)
    {
        try
        {
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

           byte[] decrypteData = new UnicodeEncoding().GetBytes(toEncryptString);              
           RSA.FromXmlString(PrivateKey);
           byte[] encrypteData = RSA.Encrypt(decrypteData, false);
           return Convert.ToBase64String(encrypteData);
       }
       catch (Exception e)
       {
           Console.WriteLine(e);
           return null;
       }
  }

再然后就是最后的解密了

    /// <summary>
    /// 解密数据
    /// </summary>
    /// <param name="base64code">传入加密数据</param>
    /// <returns>返回解密数据</returns>
    static public string Decrypt(string base64code,string PrivateKey)
    {
        try
        {

            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

            RSA.FromXmlString(PrivateKey);

            byte[] encryptedData = Convert.FromBase64String(base64code);
            byte[] decryptedData = RSA.Decrypt(encryptedData, false);
            return new UnicodeEncoding().GetString(decryptedData);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            return null;
        }

    }

输出样例
这里写图片描述


posted @ 2015-07-21 16:59  阿尔伯特  阅读(367)  评论(1编辑  收藏  举报