Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

c# - Runtime error loading certificate in Azure Functions

I want to create an Azure function (C# API Generic HTTP) method that uploads a file to an Office365 Sharepoint document library.

Because OneDrive API allows me to upload large files (using daemon process & certificate authentication), I have succeeded in achieving the goal with a C# Console Application.

The idea would be now to move the code into an Azure function. However, I receive an error during runtime of the function on the loading of the pfx-certificate.

public static async Task<bool> Run(HttpRequestMessage req, TraceWriter log)
{
   string certfile = System.IO.Path.Combine(Environment.ExpandEnvironmentVariable??s("%HOME%"), @"sitewwwroot<functionname>mykeyfile.pfx"); 

    X509Certificate2 cert = new X509Certificate2(certfile, "<myinsanepwd>");

    return true; //temporary 
}

The line X509Certificate2 cert = new X509Certificate2(certfile, ""); throws an Exception System.Security.Cryptography.CryptographicException: The system cannot find the file specified.

This is really strange because the file exists on the specified path (I checked using File.Exists() in the method :) ) Could this error have something to do with support.microsoft.com/en-us/kb/948154 ? How can I solve this?

Best regards, Jens

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Adding X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable to the constructor. This code works for me:

using System.Net;
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    string certfile = System.IO.Path.Combine(Environment.ExpandEnvironmentVariable??s("%HOME%"), @"sitewwwrootHttpTriggerCSharp4myCertFile.pfx");        
    log.Info(certfile); 
    log.Info(System.IO.File.Exists(certfile).ToString());
    X509Certificate2 cert = new X509Certificate2(certfile, "password", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);     
    log.Info(cert.Thumbprint);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...