Mimekit - 访问被拒绝尝试解密

Mimekit - Access is denied trying to decrypt

我在尝试解密 MIME 邮件时遇到此错误:

当我在本地机器上解密时,我可以毫无问题地解密邮件,但是部署在服务器上的应用程序无法解密并导致此错误。这是我用来解密的代码

GraphServiceClient graphClient = new GraphServiceClient(clientSecretCredential, new string[] { _laCaixaSettings.GraphApiSettings.Scope });
var streamMessage = await graphClient.GetMessage(_laCaixaSettings.GraphApiSettings.UserId, pasarelaSettings.FicheroId);
using var message = await MimeMessage.LoadAsync(streamMessage);
var decryptedStream = await MimeMailUtils.Decrypt(message, _laCaixaSettings.GraphApiSettings.PrivateCertificate);
    
public static async Task<Stream> GetMessage(this GraphServiceClient graphServiceClient, string userId, string messageId)
{
    var request = graphServiceClient.Users[userId].Messages[messageId].Request().GetHttpRequestMessage();
    request.RequestUri = new Uri(request.RequestUri.OriginalString + "/$value");
    var response = await graphServiceClient.HttpProvider.SendAsync(request);
    response.EnsureSuccessStatusCode();
    var content = await response.Content.ReadAsStreamAsync();
    content.Position = 0;
    return content;
}

public static async Task<MimeEntity> Decrypt(MimeMessage message, X509Certificate2 certificate)
{
    var encryptedContent = (ApplicationPkcs7Mime)message.Body;
    using var context = new WindowsSecureMimeContext(StoreLocation.CurrentUser);
    context.Import(StoreName.CertificateAuthority, certificate);
    return await encryptedContent.DecryptAsync(context);
}

这就是我获得证书的方式

public void SetSecrets()
{
    using KeyVaultClient client = VaultClientExtensions.GetKeyVaultClient(AzureVaultManagerSettings.ClientId, AzureVaultManagerSettings.ClientSecret);
    var secret = AsyncUtil.RunSync(() => client.GetSecret<string>(AzureVaultManagerSettings.SecretUrl));
    GraphApiSettings.PrivateCertificate = new X509Certificate2(
        Convert.FromBase64String(secret),
        string.Empty,
        X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.UserKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
}

我认为问题可能出在服务器中未安装此证书。谁能帮我解决这个问题?提前致谢!

您无权访问 StoreName.CertificateAuthority。

如果您查看异常中的堆栈跟踪,它在 System.Security.Cryptography.X509Certificates.X509Store.Open()

中失败

一般来说,StoreName.CertificateAuthority 只对管理员用户开放。