无法将类型 'Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair' 的对象转换为类型 'Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters'

Unable to cast object of type 'Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair' to type 'Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters'

这是从 txt 读取文件时工作正常的代码,但是当我从字符串读取它时,我在这里收到错误

        public string encrypt(string plainText,string PrivateKey)
        {

            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
           
            string filepath = path + "\rsakeys\pem_public.pem";
            string localPath = new Uri(filepath).LocalPath;
            PemReader pr = new PemReader(
                (StreamReader)File.OpenText(localPath)
            );

            var reader = new StringReader(PrivateKey);
            var pre = new PemReader(reader);
            var o = pr.ReadObject();

            var os = pre.ReadObject();
           
            RsaKeyParameters keys = (RsaKeyParameters)os;   >>> Here i am getting the error where os is the object readed from the string 

这解决了我的问题

            var o = pr.ReadObject();
            AsymmetricCipherKeyPair keyPair=(AsymmetricCipherKeyPair)o;

            //As Keypair.public is RsaParamterKey

            Pkcs1Encoding eng = new Pkcs1Encoding(new RsaEngine());
            eng.Init(true, keyPair.Public);