Search code examples
c#x509certificateazure-keyvault

AppleCommonCryptoCryptographicException - MAC verification failed - wrong password when downloading X.509 cert from keyvault


I have a .NET 5.0 application that requires a certificate be downloaded from the Azure keyvault:

static X509Certificate2 DownloadCertificate(Secret secret) {
    KeyVaultSecret key = new Provider(secret.KeyVaultName).GetSecretAsync(secret.SecretName).Result;
    return new X509Certificate2(Convert.FromBase64String(key.Value), 
        string.Empty, X509KeyStorageFlags.UserKeySet);
}

This works fine on my Windows machine, but when I attempt to run it on an Apple machine, I get the following error:

Interop.AppleCrypto.AppleCommonCryptoCryptographicException : MAC verification failed during PKCS12 import (wrong password?)
at Interop.AppleCrypto.X509ImportCertificate(Byte[] bytes, X509ContentType contentType, SafePasswordHandle importPassword, SafeKeychainHandle keychain, Boolean exportable, SafeSecIdentityHandle& identityHandle)
at Internal.Cryptography.Pal.CertificatePal.FromBlob(Byte[] rawData, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
at System.Security.Cryptography.X509Certificates.X509Certificate..ctor(Byte[] data)
at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(Byte[] rawData)

I read here that this is because there's a difference between how Apple and Windows handle X.509 certificates such that, on an Apple computer, certificates without a password will cause an error to be thrown, but on a Windows machine no error will be thrown. This appears to be my issue but I don't want to use the solution suggested by this source. Is there a way to make this work without modifying the certificate such that it requires a password?


Solution

  • macOS cannot load a PFX which is MACd with the NULL password or wrong password.

    If you have a PKCS#12 file which is not protected with a password, and which does have a MAC entry, opening the file will work on Windows and Linux but fails on Mac.

    So, while this is a bug, it's probably not something that we would work around in .NET without a very compelling argument (like it being a key distribution model by a government CA, or something like that); but rather something which ideally would be resolved by Apple. you can report the same using this link (https://bugreport.apple.com/, for SecItemImport).

    There is also a workaround available i.e. code that may act as a workaround based on BouncyCastle

    Please refer this link : X509Certificate2/CommonCrypto: Unable to open PKCS#12 files with no password and valid MAC · Issue #23635 · dotnet/runtime · GitHub