【问题标题】:RSACryptoServiceProvider encrypt and decrypt using own public and private keyRSACryptoServiceProvider 使用自己的公钥和私钥进行加密和解密
【发布时间】:2023-03-24 07:44:01
【问题描述】:

有人告诉我,对于非对称加密,您使用公钥加密明文,然后使用私钥解密。所以我尝试了以下方法:

    static void Main(string[] args)
    {
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        string pubkey = rsa.ToXmlString(false);
        string prikey = rsa.ToXmlString(true);

        byte[] someThing = RSAEncrypt(Encoding.Unicode.GetBytes("Hello World"), pubkey);
        byte[] anotherThing = RSADecrypt(someThing, prikey);

        Console.WriteLine(Convert.ToBase64String(anotherThing));
    }

以及加密和解密函数

    public static byte[] RSAEncrypt(byte[] plaintext, string destKey)
    {
        byte[] encryptedData;
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        rsa.FromXmlString(destKey);
        encryptedData = rsa.Encrypt(plaintext, true);
        rsa.Dispose();
        return encryptedData;
    }

    public static byte[] RSADecrypt(byte[] ciphertext, string srcKey)
    {
        byte[] decryptedData;
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        rsa.FromXmlString(srcKey);
        decryptedData = rsa.Decrypt(ciphertext, true);
        rsa.Dispose();
        return decryptedData;
    }

我希望控制台显示Hello World,但它显示的是SABlAGwAbABvACAAVwBvAHIAbABkAA==。我是否错误地使用了 RSACryptoServiceProvider?

【问题讨论】:

  • 您正在将解密后的字符串转换为 Base64 编码

标签: c# encryption cryptography rsa


【解决方案1】:

它是base 64,解码字符串,你会得到“Hello world”。

【讨论】:

    【解决方案2】:

    你的最后一行应该是:

     Console.WriteLine(Encoding.Unicode.GetString(anotherThing));
    

    目前您正在将解密后的字符串转换为 Base64 编码

    【讨论】:

      猜你喜欢
      • 2013-03-20
      • 1970-01-01
      • 2017-11-25
      • 2012-11-19
      • 2015-01-25
      • 2019-12-29
      • 2012-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多