【发布时间】:2017-07-12 09:19:59
【问题描述】:
我已经开发出从我的应用程序访问谷歌电子表格。它可以正常工作几天,但现在我遇到了一个异常
“System.Security.Cryptography.CryptographicException:提供程序无效 指定类型。”
我无法弄清楚问题是什么? 我的代码在我的本地机器上运行良好,但在服务器中“出现异常”。
这是堆栈跟踪:
at System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
at System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle)
at System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()
at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize)
at System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()
at Google.Apis.Auth.OAuth2.ServiceAccountCredential.Initializer.FromCertificate(X509Certificate2 certificate)
我已经搜索过,但我没有找到确切的解决方案。我认为我的代码没有问题。
这是我的代码:
string applicationName = "#########";
var serviceaccountemail = "********************************";
var certificate = new X509Certificate2(GetCertificateBytes(), "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceaccountemail)
{
Scopes = new[] { "https://spreadsheets.google.com/feeds" }
}.FromCertificate(certificate));
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = applicationName,
});
String spreadsheetId = "*************************";
String range = "Sheet1!A1:C";
SpreadsheetsResource.ValuesResource.GetRequest request =
service.Spreadsheets.Values.Get(spreadsheetId, range);
ValueRange response = request.Execute();
public byte[] GetCertificateBytes()
{
return secure.SecureResource.qa_automation_google_key;
}
这是一个更新:
当我调试上面的代码时,我看到一个异常为'((System.Security.Cryptography.RSACryptoServiceProvider)certificate.PrivateKey).CspKeyContainerInfo.CryptoKeySecurity' threw an exception of type 'System.Security.AccessControl.PrivilegeNotHeldException'
X509certificate2 证书。
所以,我认为由于这个异常,我指定了一个无效的提供程序类型。
这是关于我的证书的信息:
1. 文件 .p12
2. Providertype 是 1
3.使用算法是sha1rsa。
4. 我的证书版本是v1。
如果您需要任何其他信息,请发表评论,我将提供。 提前致谢。
【问题讨论】:
-
以上是难还是没看懂?为什么没有人回答或回答这个问题。实际上,我坚持这个异常。我无法找出这个异常的原因。请帮帮我。
-
这并不能直接回答你的问题;但是您可以下载 JSON 服务凭证而不是使用 p12 格式吗?使用 JSON 服务凭证,您可以使用 GoogleCredential.FromJson(...) 这将回避任何 X509 问题。
-
谢谢@chris。 JSON文件中的私钥何时到期?如果私钥过期了怎么办?
-
据我了解,私钥不包含过期信息,所以它永远不会过期。如果您不再需要它,则可以在 Google Cloud Console 中撤销/删除服务凭据,这意味着该凭据将不再提供对您项目的访问权限。
-
谢谢@chris。当我在我的机器中导出私钥时。当我看到过期期限长达 10 年时我很困惑。该到期期限是属于私钥还是项目。如果该到期期限属于项目,那么是否有任何其他解决方案可以延长到期期限。
标签: c# google-sheets cryptography x509certificate2 system.security