gpt4 book ai didi

c# - 使用 RSACryptoServiceProvider 进行公钥加密

转载 作者:可可西里 更新时间:2023-11-01 07:52:34 25 4
gpt4 key购买 nike

一段时间以来,我一直在阅读 CodeProject 上的一篇文章,该文章解释了如何使用 RSA 提供程序进行加密和解密:

RSA Private Key Encryption

虽然 2009 年的旧版本有问题,但 2012 年的新版本(支持 System.Numerics.BigInteger)似乎更可靠。这个版本缺少的是使用公钥加密和使用私钥解密的方法。

所以,我自己尝试了,但解密时得到了垃圾。我不熟悉 RSA 提供商,所以我在这里一无所知。很难找到更多关于它应该如何工作的信息。

有人看出这有什么问题吗?以下是使用 PUBLIC key 加密:

// Add 4 byte padding to the data, and convert to BigInteger struct
BigInteger numData = GetBig( AddPadding( data ) );
RSAParameters rsaParams = rsa.ExportParameters( false );
//BigInteger D = GetBig( rsaParams.D ); //only for private key
BigInteger Exponent = GetBig( rsaParams.Exponent );
BigInteger Modulus = GetBig( rsaParams.Modulus );
BigInteger encData = BigInteger.ModPow( numData, Exponent, Modulus );
return encData.ToByteArray();

执行此操作时是否使用提供商提供的大“D”?可能不是,因为它是没有“D”的公钥。

然后对方(使用私钥解密):

BigInteger numEncData = new BigInteger( cipherData );

RSAParameters rsaParams = rsa.ExportParameters( true );
BigInteger D = GetBig( rsaParams.D );
//BigInteger Exponent = GetBig( rsaParams.Exponent );
BigInteger Modulus = GetBig( rsaParams.Modulus );

BigInteger decData = BigInteger.ModPow( numEncData, D, Modulus );

byte[] data = decData.ToByteArray();
byte[] result = new byte[ data.Length - 1 ];
Array.Copy( data, result, result.Length );
result = RemovePadding( result );

Array.Reverse( result );
return result;

这里需要“D”还是指数?

显然,我需要加密货币以私有(private)-公共(public)-公共(public)-私有(private)的方式工作。非常感谢任何帮助!

最佳答案

以这个编码/解码为例

        byte[] toEncryptData = Encoding.ASCII.GetBytes("hello world");

//Generate keys
RSACryptoServiceProvider rsaGenKeys = new RSACryptoServiceProvider();
string privateXml = rsaGenKeys.ToXmlString(true);
string publicXml = rsaGenKeys.ToXmlString(false);

//Encode with public key
RSACryptoServiceProvider rsaPublic = new RSACryptoServiceProvider();
rsaPublic.FromXmlString(publicXml);
byte[] encryptedRSA = rsaPublic.Encrypt(toEncryptData, false);
string EncryptedResult = Encoding.Default.GetString(encryptedRSA);


//Decode with private key
var rsaPrivate = new RSACryptoServiceProvider();
rsaPrivate.FromXmlString(privateXml);
byte[] decryptedRSA = rsaPrivate.Decrypt(encryptedRSA, false);
string originalResult = Encoding.Default.GetString(decryptedRSA);

关于c# - 使用 RSACryptoServiceProvider 进行公钥加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15702718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com