C#手动实现的RSA加密算法示例



using System;
using System.Linq;
using System.Numerics;

class Program
{
    static void Main(string[] args)
    {
        // 选择一个小于100的质数作为p和q,以及自然数e和d使得ed ≡ 1 (mod (p-1) * (q-1))
        int p = 17;
        int q = 19;
        int n = p * q;
        int phi = (p - 1) * (q - 1);
        int e = 7;
        int d = FindModInverse(e, phi);

        Console.WriteLine("公钥:(n={0}, e={1})", n, e);
        Console.WriteLine("私钥:(n={0}, d={1})", n, d);

        string plainText = "Hello, world!"; // 待加密的明文
        BigInteger cipherText; // 存放加密后的密文
        string decryptedText; // 存放解密后的明文

        // 加密
        cipherText = Encrypt(plainText, n, e);

        // 解密
        decryptedText = Decrypt(cipherText, n, d);

        Console.WriteLine("明文:" + plainText);
        Console.WriteLine("密文:" + cipherText);
        Console.WriteLine("解密后的明文:" + decryptedText);
    }

    // RSA加密函数
    static BigInteger Encrypt(string message, int n, int e)
    {
        return BigInteger.ModPow(IntFromString(message), e, n);
    }

    // RSA解密函数
    static string Decrypt(BigInteger encryptedMessage, int n, int d)
    {
        return StringFromInt(BigInteger.ModPow(encryptedMessage, d, n));
    }

    // 将字符串转化为整数
    static BigInteger IntFromString(string s)
    {
        return new BigInteger(s.Select(c => (int)c).ToArray());
    }

    // 将整数转化为字符串
    static string StringFromInt(BigInteger n)
    {
        return new string(n.ToByteArray()
            .Where(b => b != 0)
            .Select(b => (char)b)
            .ToArray());
    }

    // 扩展欧几里得算法求模反元素(即逆元)
    static int FindModInverse(int a, int m)
    {
        int m0 = m, t, q;
        int x0 = 0, x1 = 1;

        if (m == 1)
            return 0;

        while (a > 1)
        {
            // q是商,t是余数,只用到了t。计算q和t。
            q = a / m;             
            t = m;

            // 更新m和a,同步更新x0和x1。
            m = a % m;
            a = t;
            t = x0;
            x0 = x1 - q * x0;
            x1 = t;
        }

        // 当循环结束后,a和m的最大公约数为1。此时x1即为所求。
        if (x1 < 0)
            x1 += m0;

        return x1;
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值