c#RSA加密字符串

2023-08-24 14:01:05 浏览数 (2)

rsa加密是非对称加密,即公钥与私钥是成对的,使用公匙加密,使用私匙解密

1.得到公匙私匙

代码语言:javascript复制
    public static void RSAGenerateKey(ref string privateKey, ref string publicKey)
    {
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        privateKey = rsa.ToXmlString(true);
        publicKey = rsa.ToXmlString(false);
    }

2.公匙加密字符串

代码语言:javascript复制
    /// <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); ;
    }

3.私匙解密字符串

代码语言:javascript复制
    /// <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);
    }

0 人点赞