尝试使用 .net 中的 bouncycastle 使用 public 密钥(非私有)解密字符串

Trying to decrypt a string with public key(not private) using bouncycastle in .net

作为示例应用程序,我使用 .NET 中的 BouncyCastle 库使用 rsa public 密钥(由第 3 方 api 提供)加密了一个字符串。当我将此加密字符串发送到所述第 3 方 api 端点时,它能够对其进行解密(使用其私钥)。我没有他们的私钥,但是,是否可以仅使用我拥有的 public 密钥来解密我这边的字符串?

根据我对RSA public/private密钥对的理解,解密时,你使用随身携带的私钥解密一个字符串,并使用public密钥确认你正在接收来自所述来源。

public string RsaEncryptWithPublic(string clearText
            , string publicKey)
        {
            var bytesToEncrypt = Encoding.UTF8.GetBytes(clearText);

            var encryptEngine = new Pkcs1Encoding(new RsaEngine());

            using (var txtreader = new StringReader(publicKey))
            {
                var keyParameter = (AsymmetricKeyParameter)new PemReader(txtreader).ReadObject();

                encryptEngine.Init(true, keyParameter);
            }

            var encrypted = Convert.ToBase64String(encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length));
            return encrypted;

        }

public string RsaDecrypt(string base64Input
            , string privateKey)
        {
            var bytesToDecrypt = Convert.FromBase64String(base64Input);

            //get a stream from the string
            AsymmetricCipherKeyPair keyPair;
            var decryptEngine = new Pkcs1Encoding(new RsaEngine());

            using (var txtreader = new StringReader(privateKey))
            {
                keyPair = (AsymmetricCipherKeyPair)new PemReader(txtreader).ReadObject();

                //decryptEngine.Init(false, keyPair.Private);
                decryptEngine.Init(false, keyPair.Public);
            }

            var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));
            return decrypted;
        }


static void Main(string[] args)
        {
string _creditCardNumber = "5454545454545454";
string publicKey = System.IO.File.ReadAllText(@"C:\ThirdPartyKeys\RSAPublicKey_01.txt");

            var enc = new EncryptionClass();
            var encryptedWithPublic = enc.RsaEncryptWithPublic(_creditCardNumber, publicKey);
            Console.WriteLine("String: " + _creditCardNumber);
            Console.WriteLine("Encrypted String: " + encryptedWithPublic);

// Decrypt
            var outputWithPublic = enc.RsaDecrypt(encryptedWithPublic, publicKey);            

            //var outputWithPrivate = enc.RsaDecrypt(encryptedWithPrivate, _privateKey);

            Console.WriteLine("Decrypted String: " + outputWithPublic);
}

加密有效,但当我尝试使用相同的 public 密钥解密时,它会提示

Invalid Cast Exception:
Unable to cast object of type 'Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters' to type 'Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair'.

at line in RsaDecrypt function:
keyPair = (AsymmetricCipherKeyPair)new PemReader(txtreader).ReadObject();

没有。它是非对称加密,这意味着您无法使用 public 密钥对其进行解密。如果可以的话,这将破坏目的,任何拥有 public 密钥的人都能够解密您的秘密消息