我们具有从.p12文件导入的证书,并且出于安全原因未将其标记为可导出。
我想从存储中读取证书,并从中为Google Cloud创建GoogleCredential。
我正在将证书读为
public X509Certificate2 GetCetificate(StoreName store, StoreLocation location, string thumbprint)
{
try
{
X509Store x509Store = new X509Store(store, location);
x509Store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection collection = x509Store.Certificates;
collection = (X509Certificate2Collection)x509Store.Certificates.Find(X509FindType.FindByThumbprint,
thumbprint, false);
if (collection.Count > 0)
{
return collection[0];
}
else
{
throw new CryptographicException(string.Format(
"Certificate not found, Please install the certficate @ {0}",
location.ToString()));
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
当尝试通过以下证书创建Google服务帐户凭据时,收到错误消息System.Security.Cryptography.CryptographicException: 'Key not valid for use in specified state.
var certificate = GetCetificate(StoreName.My, toreLocation.LocalMachine, _thubmprint);
var credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(
_serviceAccountName
)
{
Scopes = scopes
}.FromCertificate(certificate));
var googleCredential =
GoogleCredential.FromAccessToken(credential.GetAccessTokenForRequestAsync().Result);
有关更多信息,我检查了Google SDK的ServiceAccountCredential.FromCertificate方法,如下所示:
/// <summary>Extracts a <see cref="Key"/> from the given certificate.</summary>
public Initializer FromCertificate(X509Certificate2 certificate)
{
#if NETSTANDARD1_3 || NETSTANDARD2_0
Key = certificate.GetRSAPrivateKey();
#elif NET45
// Workaround to correctly cast the private key as a RSACryptoServiceProvider type 24.
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)certificate.PrivateKey;
byte[] privateKeyBlob = rsa.ExportCspBlob(true);
Key = new RSACryptoServiceProvider();
Key.ImportCspBlob(privateKeyBlob);
#else
#error Unsupported target
#endif
return this;
}
}
简而言之,我有问题
System.Security.Cryptography.CryptographicException: 'Key not valid for use in specified state.
错误)