oauth2.0 无法将型别'RSACng'的对象转换为型别'System.Security.Cryptography.RSACryptoServiceProvider'

zlwx9yxi  于 2022-11-28  发布在  其他
关注(0)|答案(5)|浏览(305)

我得到了这个异常:
无法将型别'RSACng'的对象转换为型别'System.Security.Cryptography.RSACryptoServiceProvider'
调用此方法:

GoogleCredential cred = GoogleCredential.FromFile(path);

完整异常:

Unable to cast object of type 'RSACng' to type 'System.Security.Cryptography.RSACryptoServiceProvider'
   at Google.Apis.Auth.OAuth2.ServiceAccountCredential.Initializer.FromPrivateKey(String privateKey) in C:\Apiary\2019-09-11.10-11-15\Src\Support\Google.Apis.Auth\OAuth2\ServiceAccountCredential.cs:line 110
   at Google.Apis.Auth.OAuth2.DefaultCredentialProvider.CreateServiceAccountCredentialFromParameters(JsonCredentialParameters credentialParameters) in C:\Apiary\2019-09-11.10-11-15\Src\Support\Google.Apis.Auth\OAuth2\DefaultCredentialProvider.cs:line 243
   at Google.Apis.Auth.OAuth2.DefaultCredentialProvider.CreateDefaultCredentialFromParameters(JsonCredentialParameters credentialParameters) in C:\Apiary\2019-09-11.10-11-15\Src\Support\Google.Apis.Auth\OAuth2\DefaultCredentialProvider.cs:line 197
   at Google.Apis.Auth.OAuth2.GoogleCredential.FromFile(String path) in C:\Apiary\2019-09-11.10-11-15\Src\Support\Google.Apis.Auth\OAuth2\GoogleCredential.cs:line 114
   at ServerUtil.GCloudReporter..ctor(String version, String deployEnv)

使用.NET框架4.5.1
谷歌应用程序接口库1.41.1版

ht4b089n

ht4b089n1#

我得到了完全相同的异常。
在我的例子中,我使用的是Sustainsys.Saml2.AspNetCore2版本(2.8.0)的nuget包。
我已经更新到2.9.0并删除了所有与身份验证相关的cookie。
它解决了我的问题。

8yparm6h

8yparm6h2#

问题是应用程序在.NET Core环境中运行,但此特定代码位于.NET Framework项目设置中将代码移动到具有.NET Core设置项目中可修复此问题

ogq8wdun

ogq8wdun3#

在我的例子中,当我想从服务层到我的.NetCore项目中使用我的通知服务时,我遇到了这个错误。
无法将型别'RSACng'的对象转换为型别'System.Security.Cryptography.RSACryptoServiceProvider'
我只使用包管理器将“FirebaseAdmin”包添加到我的.NetCore项目中。
这对我来说很困惑,因为我在不需要这个包的.Net框架项目上没有得到这个错误。
相当愚蠢的错误,但我希望这能为其他人节省宝贵的时间

cetgtptt

cetgtptt4#

.NET核心步骤1:步骤2:创建一个类“X509 Certificate 2Signature”

using iTextSharp.text.pdf.security;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace DigiSignNETCORE
{
    public class X509Certificate2Signature : IExternalSignature
    {
        private String hashAlgorithm;
        private String encryptionAlgorithm;
        private X509Certificate2 certificate;

        public X509Certificate2Signature(X509Certificate2 certificate, String hashAlgorithm)
        {
            if (!certificate.HasPrivateKey)
                throw new ArgumentException("No private key.");
            this.certificate = certificate;
            this.hashAlgorithm = DigestAlgorithms.GetDigest(DigestAlgorithms.GetAllowedDigests(hashAlgorithm));
            if (certificate.PrivateKey is RSACryptoServiceProvider)
                encryptionAlgorithm = "RSA";
            else if (certificate.PrivateKey is DSACryptoServiceProvider)
                encryptionAlgorithm = "DSA";
            
            else if (certificate.PrivateKey is System.Security.Cryptography.RSACng)
                encryptionAlgorithm = "RSA";
        }

        public virtual byte[] Sign(byte[] message)
        {
            if (certificate.PrivateKey is RSACryptoServiceProvider)
            {
                RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)certificate.PrivateKey;
                return rsa.SignData(message, hashAlgorithm);
            }
           else if (certificate.PrivateKey is System.Security.Cryptography.RSACng)
            {
                System.Security.Cryptography.RSACng rSACng = (System.Security.Cryptography.RSACng)certificate.PrivateKey;
                return rSACng.SignData(message,HashAlgorithmName.SHA1,RSASignaturePadding.Pkcs1);
            }

            else
            {
                DSACryptoServiceProvider dsa = (DSACryptoServiceProvider)certificate.PrivateKey;
                return dsa.SignData(message);
            }
        }

        public virtual String GetHashAlgorithm()
        {
            return hashAlgorithm;
        }

        public virtual String GetEncryptionAlgorithm()
        {
            return encryptionAlgorithm;
        }
    }
}

步骤3:在此行中,IExternalSignature外部签名=新X509证书2签名(证书,“SHA1”);指向您最近创建的类“X509 Certificate 2Signature”。

tuwxkamq

tuwxkamq5#

This example uses variables for a specific certificate in the local computer store and the string that should be encrypted/decrypted using Cryptography API: Next Generation (CNG).    
    
using System;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace X509CertEncrypt
{
    class Program
    {
        // Variables 
        public static string certificateName = "localhost";
        public static string sSecret = "TextToEncrypt";

        static void Main(string[] args)
        {
            Program p = new Program();

            // Get the certificate 
            p.getCertificate(certificateName);

            // Encryption 
            string sEncryptedSecret = string.Empty;
            sEncryptedSecret = p.EncryptRsa(sSecret);

            // Decryption 
            string sDecryptedSecret = string.Empty;
            sDecryptedSecret = p.decryptRsa(sEncryptedSecret);

            ////Display the original data and the decrypted data.
            Console.WriteLine("Original:   {0}", sSecret);
            Console.WriteLine("Encypted Value:   {0}", sEncryptedSecret);
            Console.WriteLine("Round Trip: {0}", sDecryptedSecret);
            Console.WriteLine("Press the Enter key to exit.");
        }

        private X509Certificate2 getCertificate(string certificateName)
        {
            X509Store my = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            my.Open(OpenFlags.ReadOnly);

            X509Certificate2Collection collection = my.Certificates.Find(X509FindType.FindBySubjectName, certificateName, false);
            if (collection.Count == 1)
            {
                return collection[0];
            }
            else if (collection.Count > 1)
            {
                throw new Exception(string.Format("More than one certificate with name '{0}' found in store LocalMachine/My.", certificateName));
            }
            else
            {
                throw new Exception(string.Format("Certificate '{0}' not found in store LocalMachine/My.", certificateName));
            }
        }

        private string EncryptRsa(string input)
        {
            string output = string.Empty;
            X509Certificate2 cert = getCertificate(certificateName);

            // Changed from 
            //      using (RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PublicKey.Key)
            // to
            //      using (System.Security.Cryptography.RSACng csp = (System.Security.Cryptography.RSACng)cert.PublicKey.Key)
            // because of 'Unable to cast object of type 'System.Security.Cryptography.RSACng' to type 'System.Security.Cryptography.RSACryptoServiceProvider'.'

            // Changed from 
            //      byte[] bytesEncrypted = csp.Encrypt(bytesData, false);
            // To            
            //      byte[] bytesEncrypted = csp.Encrypt(bytesData, System.Security.Cryptography.RSAEncryptionPadding.OaepSHA512);

            using (System.Security.Cryptography.RSACng csp = (System.Security.Cryptography.RSACng)cert.PublicKey.Key)
            {
                byte[] bytesData = Encoding.UTF8.GetBytes(input);
                //byte[] bytesEncrypted = csp.Encrypt(bytesData, false);
                byte[] bytesEncrypted = csp.Encrypt(bytesData, System.Security.Cryptography.RSAEncryptionPadding.OaepSHA512);
                output = Convert.ToBase64String(bytesEncrypted);
            }
            return output;
        }

        private string decryptRsa(string encrypted)
        {
            string text = string.Empty;
            X509Certificate2 cert = getCertificate(certificateName);
            // using (RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PrivateKey)
            using (System.Security.Cryptography.RSACng csp = (System.Security.Cryptography.RSACng)cert.PrivateKey)
            {
                byte[] bytesEncrypted = Convert.FromBase64String(encrypted);
                byte[] bytesDecrypted = csp.Decrypt(bytesEncrypted, System.Security.Cryptography.RSAEncryptionPadding.OaepSHA512);
                text = Encoding.UTF8.GetString(bytesDecrypted);
            }
            return text;
        }
    }
}

相关问题