Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# rsa

作者:蛋蛋的憂傷   发布日期:2026-04-13   浏览:77

using System;
using System.Security.Cryptography;
using System.Text;

public class RsaExample
{
    public static void Main()
    {
        // 创建 RSA 加密服务提供程序实例
        using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
        {
            // 生成公钥和私钥
            string publicKey = rsa.ToXmlString(false); // 只导出公钥
            string privateKey = rsa.ToXmlString(true); // 导出公钥和私钥

            Console.WriteLine("Public Key: " + publicKey);
            Console.WriteLine("Private Key: " + privateKey);

            // 要加密的字符串
            string originalData = "Hello, World!";
            Console.WriteLine("Original Data: " + originalData);

            // 将字符串转换为字节数组
            byte[] dataToEncrypt = Encoding.UTF8.GetBytes(originalData);

            // 使用公钥加密数据
            byte[] encryptedData = rsa.Encrypt(dataToEncrypt, false);
            Console.WriteLine("Encrypted Data: " + Convert.ToBase64String(encryptedData));

            // 使用私钥解密数据
            byte[] decryptedData = rsa.Decrypt(encryptedData, false);
            string decryptedString = Encoding.UTF8.GetString(decryptedData);
            Console.WriteLine("Decrypted Data: " + decryptedString);
        }
    }
}

解释说明:

  1. 创建 RSA 实例:使用 RSACryptoServiceProvider 类创建一个 RSA 加密服务提供程序实例。
  2. 生成公钥和私钥:通过 ToXmlString 方法生成公钥和私钥。false 参数表示只导出公钥,true 表示导出公钥和私钥。
  3. 加密数据:将要加密的字符串转换为字节数组,然后使用公钥对其进行加密。
  4. 解密数据:使用私钥对加密后的数据进行解密,并将其转换回原始字符串。

这个示例展示了如何在 C# 中使用 RSA 算法进行简单的加密和解密操作。

上一篇:c# post请求

下一篇:c# dictionary 遍历

大家都在看

c# 二进制

c# 创建目录

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站