天天看點

c#RSA加密字元串

rsa加密是非對稱加密,即公鑰與私鑰是成對的,使用公匙加密,使用私匙解密

1.得到公匙私匙

public static void RSAGenerateKey(ref string privateKey, ref string publicKey)
    {
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        privateKey = rsa.ToXmlString(true);
        publicKey = rsa.ToXmlString(false);
    }      
/// <summary>  
    /// 加密  
    /// </summary>  
    /// <param name="publickey">公鑰</param>  
    /// <param name="content">所加密的内容</param>  
    /// <returns>加密後的内容</returns>  
    static public string RSAEncrypt(string publickey, string content)
    {
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        byte[] cipherbytes;
        rsa.FromXmlString(publickey);
        cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);
        return Convert.ToBase64String(cipherbytes); ;
    }      
/// <summary>  
    /// 解密  
    /// </summary>  
    /// <param name="privatekey">私鑰</param>  
    /// <param name="content">加密後的内容</param>  
    /// <returns>解密後的内容</returns>  
    static public string RSADecrypt(string privatekey, string content)
    {
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        byte[] cipherbytes;
        rsa.FromXmlString(privatekey);
        cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false);
        return Encoding.UTF8.GetString(cipherbytes);
    }