Keyset Does Not Exist Error When Connecting to Exchange Online via PowerShell
7 min
Issue Summary
When attempting to connect to Exchange Online using PowerShell, users may encounter the following error:
Keyset does not exist
This error typically occurs when the certificate used for authentication is missing its private key or is improperly configured.
Reproduction
The error can be reproduced using a C# script that attempts to access the private key of a certificate stored in the LocalMachine\My store. Here's a simplified version of the script:
using System;
using System.Security.Cryptography.X509Certificates;
class Script
{
public void Main()
{
string thumbprint = "YOUR_THUMBPRINT"; // Replace with actual thumbprint
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
try
{
store.Open(OpenFlags.ReadOnly);
var certCollection = store.Certificates.Find(
X509FindType.FindByThumbprint,
thumbprint,
validOnly: false
);
if (certCollection.Count > 0)
{
var cert = certCollection[0];
Console.WriteLine($"Certificate found: {cert.Subject}, Has Private Key: {cert.HasPrivateKey}");
var privateKey = cert.PrivateKey; // Error occurs here
}
else
{
Console.WriteLine("Certificate not found in LocalMachine\My store.");
}
}
finally
{
store.Close();
}
}
}
Root Cause
The error is triggered when the certificate does not have an accessible private key. This can happen due to:
- The certificate being imported without its private key.
- Incorrect permissions on the private key.
- The certificate being corrupted or improperly generated.
Suggested Resolution Steps
- Reimport the Certificate with Private Key
- Ensure the certificate is imported into the LocalMachine\My store with its private key.
- Use the .pfx file format which includes the private key.
- Generate a New Certificate
- If reimporting fails, generate a new certificate.
- Import it into the LocalMachine\My store.
- Upload the new certificate to the Azure application associated with Exchange Online.
Stack Trace Overview
The error manifests during the execution of the Connect-ExchangeOnline command:
Connect-ExchangeOnline -SkipLoadingFormatData $true -AppId '<AppId>' -Organization '<Org>.onmicrosoft.com' -CertificateThumbPrint '<Thumbprint>'
Exception Details:
- System.Security.Cryptography.CryptographicException: Keyset does not exist
- Occurs during certificate private key access and token signing operations.
Resolution
We ended up resolving this by granting rights to manage the private key in the certificate console.
References
- Microsoft Docs: Connect to Exchange Online PowerShell
- Certificate Management in Windows