Opc.Ua.CertificateFactory.CreateCertificateFromPKCS12 C# (CSharp) Method

CreateCertificateFromPKCS12() public static method

Creates a certificate from a PKCS #12 store with a private key.
public static CreateCertificateFromPKCS12 ( byte rawData, string password ) : X509Certificate2
rawData byte The raw PKCS #12 store data.
password string The password to use to access the store.
return X509Certificate2
        public static X509Certificate2 CreateCertificateFromPKCS12(
            byte[] rawData, 
            string password
            )
        {
            Exception ex = null;
            int flagsRetryCounter = 0;
            X509Certificate2 certificate = null;
            X509KeyStorageFlags[] storageFlags = {
                X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet,
                X509KeyStorageFlags.Exportable | X509KeyStorageFlags.DefaultKeySet
            };

            // try some combinations of storage flags, support is platform dependent
            while (certificate == null &&
                flagsRetryCounter < storageFlags.Length)
            {
                try
                {
                    // merge first cert with private key into X509Certificate2
                    certificate = new X509Certificate2(
                        rawData, 
                        (password == null) ? String.Empty : password, 
                        storageFlags[flagsRetryCounter]);
                    // can we really access the private key?
                    using (RSA rsa = certificate.GetRSAPrivateKey()) { }
                }
                catch (Exception e)
                {
                    ex = e;
                    certificate = null;
                }
                flagsRetryCounter++;
            }

            if (certificate == null)
            {
                throw new NotSupportedException("Creating X509Certificate from PKCS #12 store failed", ex);
            }

            return certificate;
        }
        #endregion