コード例 #1
0
ファイル: MainForm.cs プロジェクト: jnsgsbz/EnrollmentStation
        private void YubikeyStateChange()
        {
            // Piv Manager find only CCID enabled  Yubikeys
            List <string> listDevices = YubikeyPivManager.Instance.ListDevices().ToList();
            string        devName     = listDevices.FirstOrDefault();
            bool          hasDevice   = !string.IsNullOrEmpty(devName);

            YubmanUtil yu = new YubmanUtil();

            btnEnableCCID.Enabled   = false;
            btnExportCert.Enabled   = false;
            btnViewCert.Enabled     = false;
            btnResetYubiKey.Enabled = false;



            if (hasDevice)
            {
                using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    int  serialNumber    = (int)dev.GetSerialNumber(); // uint
                    bool success         = yu.GetYubikeyMode(serialNumber.ToString(), out bool HasOtp, out bool HasCcid, out bool HasFido, out string mode);
                    bool have2enableCcid = !HasCcid;
                    btnEnableCCID.Enabled   = HasCcid;
                    btnExportCert.Enabled   = !have2enableCcid;
                    btnViewCert.Enabled     = !have2enableCcid;
                    btnResetYubiKey.Enabled = !have2enableCcid;
                }
            }

            RefreshInsertedKey();
        }
コード例 #2
0
ファイル: MainForm.cs プロジェクト: jnsgsbz/EnrollmentStation
        private void btnExportCert_Click(object sender, EventArgs e) //Änderungen vorgenommen, dass beide Zertifikate, wenn vorhanden exportiert werden können
        {
            X509Certificate2 cert  = null;                           //Standard Cert
            X509Certificate2 cert2 = null;                           //Admin Cert
            int deviceSerial       = 0;

            string devName = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();

            if (!string.IsNullOrEmpty(devName))
            {
                using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    deviceSerial = (int)dev.GetSerialNumber();
                }

                using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    cert  = dev.GetCertificate9a();
                    cert2 = dev.GetCertificate9d();
                }
            }

            if (cert == null && cert2 == null)
            {
                MetroMessageBox.Show(this, "No certificate on device.", "No Certificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.FileName = deviceSerial + "-" + cert.SerialNumber + ".crt"; //TODO: GetSerialNumber() can possibly fail

            DialogResult dlgResult = saveFileDialog.ShowDialog();

            if (dlgResult != DialogResult.OK)
            {
                return;
            }

            if (cert != null)
            {
                using (Stream fs = saveFileDialog.OpenFile())
                {
                    byte[] data = cert.GetRawCertData();
                    fs.Write(data, 0, data.Length);
                }
            }

            if (cert2 != null)
            {
                using (Stream fs = saveFileDialog.OpenFile())
                {
                    byte[] data = cert2.GetRawCertData();
                    fs.Write(data, 0, data.Length);
                }
            }
        }
コード例 #3
0
        private void CheckForYubikey()
        {
            string devName = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();

            _hadDevice = !string.IsNullOrEmpty(devName);

            if (!_hadDevice)
            {
                return;
            }

            using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
            {
                _hasBeenFound = ((int)dev.GetSerialNumber()) == _key.DeviceSerial;
            }
        }
コード例 #4
0
        static void PrintPiv(string name)
        {
            Console.WriteLine($"[PIV] Device: {name}");

            if (!YubikeyPivManager.Instance.IsValidDevice(name))
            {
                Console.WriteLine("      Not a valid PIV device");
            }
            else
            {
                using (YubikeyPivDevice device = YubikeyPivManager.Instance.OpenDevice(name))
                {
                    Console.WriteLine($"      Version : {device.GetVersion()}");

                    byte[] chuid;
                    if (device.GetCHUID(out chuid))
                    {
                        Console.WriteLine($"      CHUID   : {BitConverter.ToString(chuid).Replace("-", "")}");
                    }
                    else
                    {
                        Console.WriteLine("      CHUID   : N/A");
                    }

                    Console.WriteLine($"      PinTries: {device.GetPinTriesLeft():N0}");
                    Console.WriteLine($"      SerialNumber: {device.GetSerialNumber():D0}");

                    X509Certificate2 cert = device.GetCertificate9a();

                    if (cert != null)
                    {
                        Console.WriteLine($"      Cert 9A, Subject: {cert.SubjectName}");
                        Console.WriteLine($"               Issuer : {cert.IssuerName}");
                        Console.WriteLine($"               Start  : {cert.NotBefore.ToUniversalTime():O}");
                        Console.WriteLine($"               Expiry : {cert.NotAfter.ToUniversalTime():O}");
                        Console.WriteLine($"               Serial : {cert.SerialNumber}");
                        Console.WriteLine($"               Finger : {cert.Thumbprint}");
                    }
                    else
                    {
                        Console.WriteLine("      Cert 9A : N/A");
                    }
                }
            }
            Console.WriteLine();
        }
コード例 #5
0
        private void YubikeyStateChange()
        {
            string devName   = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();
            bool   hasDevice = !string.IsNullOrEmpty(devName);

            _devicePresent   = hasDevice;
            _hasBeenEnrolled = false;

            if (hasDevice)
            {
                using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    _hasBeenEnrolled = _dataStore.Search((int)dev.GetSerialNumber()).Any();
                }
            }

            RefreshView();
        }
コード例 #6
0
        private void DlgChangePin_Load(object sender, EventArgs e)
        {
            AcceptButton = cmdChange;

            string devName   = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();
            bool   hadDevice = !string.IsNullOrEmpty(devName);

            if (!hadDevice)
            {
                return;
            }

            using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
            {
                int yubiSerial = (int)dev.GetSerialNumber();
                lblSerialNumber.Text = yubiSerial.ToString();
            }
        }
コード例 #7
0
ファイル: MainForm.cs プロジェクト: scVENUS/EnrollmentStation
        private void btnExportCert_Click(object sender, EventArgs e)
        {
            X509Certificate2 cert = null;
            int deviceSerial      = 0;

            string devName = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();

            if (!string.IsNullOrEmpty(devName))
            {
                using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    deviceSerial = (int)dev.GetSerialNumber();
                }

                using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    cert = dev.GetCertificate9a();
                }
            }

            if (cert == null)
            {
                MessageBox.Show("No certificate on device.", "No Certificate", MessageBoxButtons.OK);
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.FileName = deviceSerial + "-" + cert.SerialNumber + ".crt"; //TODO: GetSerialNumber() can possibly fail

            DialogResult dlgResult = saveFileDialog.ShowDialog();

            if (dlgResult != DialogResult.OK)
            {
                return;
            }

            using (Stream fs = saveFileDialog.OpenFile())
            {
                byte[] data = cert.GetRawCertData();
                fs.Write(data, 0, data.Length);
            }
        }
コード例 #8
0
        private void cmdChange_Click(object sender, EventArgs e)
        {
            SetStatus(Color.Orange, "DO NOT REMOVE THE YUBIKEY");

            string devName   = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();
            bool   hasDevice = !string.IsNullOrEmpty(devName);

            if (!hasDevice)
            {
                SetStatus(Color.Yellow, "Insert a Yubikey");
                return;
            }

            YubmanUtil yu = new YubmanUtil();

            using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
            {
                try
                {
                    string serialNumber = dev.GetSerialNumber().ToString();  // uint
                    bool   success      = yu.SetYubikeyMode(serialNumber, _currentModeHasOTP, _currentModeHasCCID, _currentModeHasFIDO);
                    if (success)
                    {
                        SetStatus(Color.GreenYellow, "The mode was set. Please remove the Yubikey from the system.");
                    }
                    else
                    {
                        SetStatus(Color.Red, "Was unable to set the mode, please remove the Yubikey.");
                    }
                }
                catch (Exception ex)
                {
                    SetStatus(Color.Red, "Was unable to set the mode, please remove the Yubikey. Details: " + ex.Message);
                }

                _stateWaitingToRemove = true;
                foreach (Control control in grpChangeMode.Controls)
                {
                    control.Enabled = false;
                }
            }
        }
コード例 #9
0
        private void RefreshInsertedKeyInfo()
        {
            string devName   = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();
            bool   hasDevice = !string.IsNullOrEmpty(devName);

            foreach (Control control in gbInsertedYubikey.Controls)
            {
                if (control.Name.StartsWith("lbl"))
                {
                    control.Visible = hasDevice;
                }
            }

            if (!hasDevice)
            {
                return;
            }

            lblAlreadyEnrolled.Visible = _hasBeenEnrolled;

            using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
            {
                string serial = dev.GetSerialNumber().ToString();

                var  yi      = new YubikeyInfo();
                bool success = yi.GetYubikeyInfo(serial);

                /* Get currently only CCID enabled Yubikeys
                 * if (HasCcid)
                 *  lblInsertedMode.ForeColor = Color.Black;
                 * else
                 *  lblInsertedMode.ForeColor = Color.Red;
                 */
                lblInsertedTyp.Text      = yi.devicetype;
                lblInsertedSerial.Text   = yi.serial;
                lblInsertedMode.Text     = yi.usbinterface;
                lblInsertedFirmware.Text = yi.firmware;
            }
        }
コード例 #10
0
        private void UpdateCurrentView()
        {
            if (_stateWaitingToRemove)
            {
                // Don't update the UI - wait for the user to remove the current Yubikey
                return;
            }

            // using (YubikeyDetector.Instance.GetExclusiveLock())
            {
                string devName   = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();
                bool   hasDevice = !string.IsNullOrEmpty(devName);

                foreach (Control control in grpChangeMode.Controls)
                {
                    control.Enabled = hasDevice;
                }

                if (!hasDevice)
                {
                    SetStatus(Color.Yellow, "Insert a Yubikey");
                    return;
                }
                YubmanUtil yu = new YubmanUtil();
                using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    int  serialNumber = (int)dev.GetSerialNumber(); // uint
                    bool success      = yu.GetYubikeyMode(serialNumber.ToString(), out _currentModeHasOTP, out _currentModeHasCCID, out _currentModeHasFIDO, out _currentMode);

                    _deferCheckboxEvents = true;
                    chkOTP.Checked       = _currentModeHasOTP;
                    chkCCID.Checked      = _currentModeHasCCID;
                    chkU2f.Checked       = _currentModeHasFIDO;
                    _deferCheckboxEvents = false;
                    SetStatus(Color.GreenYellow, "Currently set to " + _currentMode);
                }
            }
        }
コード例 #11
0
ファイル: MainForm.cs プロジェクト: scVENUS/EnrollmentStation
        private void RefreshInsertedKey()
        {
            List <string> listDevices = YubikeyPivManager.Instance.ListDevices().ToList();
            string        devName     = listDevices.FirstOrDefault();
            bool          hasDevice   = !string.IsNullOrEmpty(devName);

            foreach (Control control in gbInsertedKey.Controls)
            {
                if (control.Name.StartsWith("lbl"))
                {
                    control.Visible = (hasDevice);
                }
            }

            if (hasDevice)
            {
                using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    int serialNumber = (int)dev.GetSerialNumber();   // uint
                    var yi           = new YubikeyInfo();
                    yi.GetYubikeyInfo(serialNumber.ToString());
                    lblDevType.Text                 = yi.devicetype;
                    lblInsertedSerial.Text          = yi.serial;
                    lblInsertedFirmware.Text        = yi.firmware;
                    lblInsertedMode.Text            = yi.usbinterface;
                    lblInsertedHasBeenEnrolled.Text = _dataStore.Search(serialNumber).Any().ToString();
                }
            }

            if (listDevices.Count > 1)
            {
                lblMultipleKeys.Text = $"{listDevices.Count:N0} keys inserted";
            }
            else
            {
                lblMultipleKeys.Text = "";
            }
        }
コード例 #12
0
ファイル: MainForm.cs プロジェクト: jnsgsbz/EnrollmentStation
        private void RefreshInsertedKey()
        {
            List <string> listDevices = YubikeyPivManager.Instance.ListDevices().ToList();
            string        devName     = listDevices.FirstOrDefault();
            bool          hasDevice   = !string.IsNullOrEmpty(devName);

            foreach (Control control in gbInsertedKey.Controls)
            {
                if (control.Name.StartsWith("lbl"))
                {
                    control.Visible = (hasDevice);
                }
            }

            if (hasDevice)
            {
                using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    int serialNumber = (int)dev.GetSerialNumber();   // uint
                    var yi           = new YubikeyInfo();
                    yi.GetYubikeyInfo(serialNumber.ToString());
                    lblDevType.Text          = yi.devicetype;
                    lblInsertedSerial.Text   = yi.serial;
                    lblInsertedFirmware.Text = yi.firmware;
                    lblInsertedMode.Text     = yi.usbinterface;

                    X509Certificate2 cert  = null;  //Standard Cert
                    X509Certificate2 cert2 = null;  //Admin Cert



                    _hasBeenEnrolled = _dataStore.Search((int)dev.GetSerialNumber()).Any();


                    cert  = dev.GetCertificate9a();
                    cert2 = dev.GetCertificate9d();

                    if ((cert != null || cert2 != null) && _hasBeenEnrolled == true)
                    {
                        lblInsertedHasBeenEnrolled.Text      = "Enrolled!";
                        lblInsertedHasBeenEnrolled.ForeColor = Color.Green;
                    }
                    else if ((cert != null || cert2 != null) && _hasBeenEnrolled == false)
                    {
                        lblInsertedHasBeenEnrolled.Text      = "YubiKey is not empty!";
                        lblInsertedHasBeenEnrolled.ForeColor = Color.Red;
                    }
                    else if ((cert == null || cert2 == null) && _hasBeenEnrolled == true)
                    {
                        lblInsertedHasBeenEnrolled.Text      = "YubiKey is empty! Please revoke Certificate!";
                        lblInsertedHasBeenEnrolled.ForeColor = Color.Red;
                    }
                    else if ((cert == null || cert2 == null) && _hasBeenEnrolled == false)
                    {
                        lblInsertedHasBeenEnrolled.Text      = "YubiKey can be enrolled!";
                        lblInsertedHasBeenEnrolled.ForeColor = Color.DarkOrange;
                    }
                }
            }

            if (listDevices.Count > 1)
            {
                lblMultipleKeys.Text    = $"{listDevices.Count:N0} keys inserted";
                btnResetYubiKey.Enabled = false;
                btnViewCert.Enabled     = false;
                btnEnableCCID.Enabled   = false;
                btnExportCert.Enabled   = false;
                tsbEnroll.Enabled       = false;
                tsbAbout.Enabled        = false;
                tsbSettings.Enabled     = false;
            }
            else
            {
                lblMultipleKeys.Text = "";
            }
        }
コード例 #13
0
ファイル: MainForm.cs プロジェクト: scVENUS/EnrollmentStation
        private void terminateToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (lstItems.SelectedItems.Count <= 0)
            {
                return;
            }

            EnrolledYubikey item = lstItems.SelectedItems[0].Tag as EnrolledYubikey;

            if (item == null)
            {
                return;
            }

            X509Certificate2 currentCert = new X509Certificate2(item.Certificate.RawCertificate);

            DialogResult dlgResult = MessageBox.Show("This will terminate the Yubikey, wiping the PIN, PUK, Management Key and Certificates. " +
                                                     "This will also revoke the certificate. Proceeed?" + Environment.NewLine + Environment.NewLine +
                                                     "Will revoke: " + currentCert.Subject + Environment.NewLine +
                                                     "By: " + currentCert.Issuer, "Terminate (WILL revoke)",
                                                     MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);

            if (dlgResult != DialogResult.Yes)
            {
                return;
            }

            DlgPleaseInsertYubikey yubiWaiter = new DlgPleaseInsertYubikey(item);
            DialogResult           result     = yubiWaiter.ShowDialog();

            if (result != DialogResult.OK)
            {
                return;
            }

            DlgProgress prg = new DlgProgress("Terminating certificate");

            prg.WorkerAction = worker =>
            {
                worker.ReportProgress(20, "Revoking certificate ...");

                // Begin
                try
                {
                    CertificateUtilities.RevokeCertificate(item.CA, item.Certificate.Serial);

                    // Revoked
                    _dataStore.Remove(item);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(
                        "Unable to revoke certificate " + item.Certificate.Serial + " of " + item.CA +
                        " enrolled on " + item.EnrolledAt + ". There was an error." + Environment.NewLine +
                        Environment.NewLine + ex.Message, "An error occurred.", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    return;
                }

                // Wipe the Yubikey
                worker.ReportProgress(50, "Wiping Yubikey ...");

                string devName   = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();
                bool   hasDevice = !string.IsNullOrEmpty(devName);

                if (hasDevice)
                {
                    using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
                    {
                        int serial = (int)dev.GetSerialNumber();
                        if (item.DeviceSerial != serial)
                        {
                            // Something went seriously wrong - perhaps the user switched keys?
                            MessageBox.Show("Unable to reset the yubikey. The inserted key did not match the key you wanted to wipe.", "An error occurred.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                    }

                    using (YubikeyPivDevice piv = YubikeyPivManager.Instance.OpenDevice(devName))
                    {
                        piv.BlockPin();
                        worker.ReportProgress(70);

                        piv.BlockPuk();
                        worker.ReportProgress(90);

                        bool reset = piv.ResetDevice();
                        if (!reset)
                        {
                            MessageBox.Show("Unable to reset the yubikey. Try resetting it manually.", "An error occurred.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }

                        worker.ReportProgress(100);
                    }
                }

                // Write to disk
                _dataStore.Save(FileStore);
            };

            prg.ShowDialog();

            RefreshUserStore();

            RefreshInsertedKey();
        }
コード例 #14
0
        private void RefreshInsertedKeyInfo()
        {
            string devName   = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();
            bool   hasDevice = !string.IsNullOrEmpty(devName);

            foreach (Control control in gbInsertedYubikey.Controls)
            {
                if (control.Name.StartsWith("lbl"))
                {
                    control.Visible = hasDevice;
                }
            }

            if (!hasDevice)
            {
                return;
            }

            using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
            {
                X509Certificate2 cert  = null;  //Standard Cert
                X509Certificate2 cert2 = null;  //Admin Cert

                cert  = dev.GetCertificate9a();
                cert2 = dev.GetCertificate9d();

                if ((cert != null || cert2 != null) && _hasBeenEnrolled == true)
                {
                    lblAlreadyEnrolled.Text      = "Enrolled!";
                    lblAlreadyEnrolled.ForeColor = Color.Green;
                }
                else if ((cert != null || cert2 != null) && _hasBeenEnrolled == false)
                {
                    lblAlreadyEnrolled.Text      = "YubiKey is not empty!";
                    lblAlreadyEnrolled.ForeColor = Color.Red;
                }
                else if ((cert == null || cert2 == null) && _hasBeenEnrolled == true)
                {
                    lblAlreadyEnrolled.Text      = "YubiKey is empty! Please revoke Certificate!";
                    lblAlreadyEnrolled.ForeColor = Color.Red;
                }
                else if ((cert == null || cert2 == null) && _hasBeenEnrolled == false)
                {
                    lblAlreadyEnrolled.Text      = "YubiKey can be enrolled!";
                    lblAlreadyEnrolled.ForeColor = Color.DarkOrange;
                }
            }

            using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
            {
                string serial = dev.GetSerialNumber().ToString();

                var  yi      = new YubikeyInfo();
                bool success = yi.GetYubikeyInfo(serial);

                /* Get currently only CCID enabled Yubikeys
                 * if (HasCcid)
                 *  lblInsertedMode.ForeColor = Color.Black;
                 * else
                 *  lblInsertedMode.ForeColor = Color.Red;
                 */
                lblInsertedTyp.Text      = yi.devicetype;
                lblInsertedSerial.Text   = yi.serial;
                lblInsertedMode.Text     = yi.usbinterface;
                lblInsertedFirmware.Text = yi.firmware;
            }
        }
コード例 #15
0
        private void EnrollWorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            string devName   = YubikeyPivManager.Instance.ListDevices().FirstOrDefault();
            bool   hasDevice = !string.IsNullOrEmpty(devName);

            if (!hasDevice)
            {
                throw new InvalidOperationException("No yubikey");
            }

            // 0. Get lock on yubikey
            using (YubikeyPivDevice dev = YubikeyPivManager.Instance.OpenDevice(devName))
            {
                // 1. Prep device info
                int     deviceId    = (int)dev.GetSerialNumber();
                string  neoFirmware = dev.GetVersion().ToString();
                Version pivFirmware;

                using (YubikeyPivDevice piv = YubikeyPivManager.Instance.OpenDevice(devName))
                    pivFirmware = piv.GetVersion();

                _enrollWorker.ReportProgress(1);

                // 2 - Generate PUK, prep PIN
                byte[] randomKey = Utilities.GenerateRandomKey();
                string puk       = Utilities.MapBytesToString(randomKey.Take(8).ToArray());

                string pin = txtPin.Text;

                _enrollWorker.ReportProgress(2);

                // 3 - Prep CA
                WindowsCertificate enrollmentAgent_std = WindowsCertStoreUtilities.FindCertificate(_settings.EnrollmentAgentCertificate);
                WindowsCertificate enrollmentAgent_adm = WindowsCertStoreUtilities.FindCertificate(_settings.EnrollmentAgentCertificate);
                string             ca         = _settings.CSREndpoint;
                string             caTemplate = _settings.EnrollmentCaTemplate;
                string             std_user   = txtStdUser.Text; //std
                string             adm_user   = txtAdmUser.Text; //adm

                if (enrollmentAgent_std == null)
                {
                    doWorkEventArgs.Cancel = true;
                    _enrollWorkerMessage   = "Unable to find the certificate with thumbprint: " + _settings.EnrollmentAgentCertificate;
                    return;
                }

                _enrollWorker.ReportProgress(3);

                // 4 - Prep Management Key
                // TODO: Consider a new key every time?
                byte[] mgmKey = _settings.EnrollmentManagementKey;

                _enrollWorker.ReportProgress(4);

                RSAParameters    publicKey_std = new RSAParameters();
                RSAParameters    publicKey_adm = new RSAParameters();
                X509Certificate2 std_cert;
                X509Certificate2 adm_cert;
                byte[]           chuid;

                using (YubikeyPivDevice pivTool = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    // 5 - Yubico: Reset device
                    pivTool.BlockPin();
                    pivTool.BlockPuk();
                    bool reset = pivTool.ResetDevice();

                    if (!reset)
                    {
                        doWorkEventArgs.Cancel = true;
                        _enrollWorkerMessage   = "Unable to reset the YubiKey";
                        return;
                    }

                    _enrollWorker.ReportProgress(5);

                    // 6 - Yubico: Management Key
                    bool authenticated = pivTool.Authenticate(YubikeyPivDevice.DefaultManagementKey);

                    if (!authenticated)
                    {
                        doWorkEventArgs.Cancel = true;
                        _enrollWorkerMessage   = "Unable to authenticate with the YubiKey";
                        return;
                    }

                    bool setMgmKey = pivTool.SetManagementKey(mgmKey);

                    if (!setMgmKey)
                    {
                        doWorkEventArgs.Cancel = true;
                        _enrollWorkerMessage   = "Unable to set the management key";
                        return;
                    }

                    _enrollWorker.ReportProgress(6);

                    // 7 - Yubico: Set CHUID
                    bool setChuid = pivTool.SetCHUID(Guid.NewGuid(), out chuid);

                    if (!setChuid)
                    {
                        doWorkEventArgs.Cancel = true;
                        _enrollWorkerMessage   = "Unable to set CHUID";
                        return;
                    }

                    _enrollWorker.ReportProgress(7);

                    // 8 - Yubico: PIN
                    int  tmp;
                    bool setPin = pivTool.ChangePin(YubikeyPivDevice.DefaultPin, pin, out tmp);

                    if (!setPin)
                    {
                        doWorkEventArgs.Cancel = true;
                        _enrollWorkerMessage   = "Unable to set the PIN code";
                        return;
                    }

                    _enrollWorker.ReportProgress(8);

                    // 9 - Yubico: PUK
                    bool setPuk = pivTool.ChangePuk(YubikeyPivDevice.DefaultPuk, puk, out tmp);

                    if (!setPuk)
                    {
                        doWorkEventArgs.Cancel = true;
                        _enrollWorkerMessage   = "Unable to set the PUK code";
                        return;
                    }

                    _enrollWorker.ReportProgress(9);

                    // 10 - Yubico: Generate Key
                    YubikeyAlgorithm algorithm = (YubikeyAlgorithm)drpAlgorithm.SelectedItem;


                    if (std_user != "")
                    {
                        try
                        {
                            pivTool.GenerateKey9a(algorithm.Value, out publicKey_std);
                        }
                        catch
                        {
                            doWorkEventArgs.Cancel = true;
                            _enrollWorkerMessage   = "Unable to generate a keypair for Standard User";
                            return;
                        }
                    }
                    if (adm_user != "")
                    {
                        try
                        {
                            pivTool.GenerateKey9d(algorithm.Value, out publicKey_adm);
                        }
                        catch
                        {
                            doWorkEventArgs.Cancel = true;
                            _enrollWorkerMessage   = "Unable to generate a keypair for Admin User";
                            return;
                        }
                    }

                    _enrollWorker.ReportProgress(10);
                }

                // 11 - Yubico: Make CSR
                string csr_std  = null;
                string csr_adm  = null;
                string csrError = null;

                if (std_user != "")
                {
                    try
                    {
                        MakeCsr_std(Utilities.ExportPublicKeyToPEMFormat(publicKey_std), pin, out csrError, out csr_std);
                    }
                    catch
                    {
                        doWorkEventArgs.Cancel = true;
                        _enrollWorkerMessage   = "Unable to generate a CSR for Standard User" + Environment.NewLine + csrError;
                        return;
                    }
                }

                if (adm_user != "")
                {
                    try
                    {
                        MakeCsr_adm(Utilities.ExportPublicKeyToPEMFormat(publicKey_adm), pin, out csrError, out csr_adm);
                    }
                    catch
                    {
                        doWorkEventArgs.Cancel = true;
                        _enrollWorkerMessage   = "Unable to generate a CSR for Admin User" + Environment.NewLine + csrError;
                        return;
                    }
                }

                _enrollWorker.ReportProgress(11);

                // 12 - Enroll
                string std_enrollError = null;
                string adm_enrollError = null;
                bool   std_enrolled    = true;
                bool   adm_enrolled    = true;

                if (std_user != "")
                {
                    std_enrolled = CertificateUtilities.Enroll(std_user, enrollmentAgent_std, ca, caTemplate, csr_std, out std_enrollError, out std_cert);
                }
                else
                {
                    std_cert = null;
                }

                if (adm_user != "")
                {
                    adm_enrolled = CertificateUtilities.Enroll(adm_user, enrollmentAgent_adm, ca, caTemplate, csr_adm, out adm_enrollError, out adm_cert);
                }
                else
                {
                    adm_cert = null;
                }

                if (!std_enrolled)
                {
                    doWorkEventArgs.Cancel = true;
                    _enrollWorkerMessage   = "Unable to enroll a certificate for Standard User." + Environment.NewLine + std_enrollError;
                    return;
                }
                if (!adm_enrolled)
                {
                    doWorkEventArgs.Cancel = true;
                    _enrollWorkerMessage   = "Unable to enroll a certificate for Admin User." + Environment.NewLine + adm_enrollError;
                    return;
                }

                _enrollWorker.ReportProgress(12);

                using (YubikeyPivDevice pivTool = YubikeyPivManager.Instance.OpenDevice(devName))
                {
                    // 13 - Yubico: Import Cert
                    bool authenticatedForCert = pivTool.Authenticate(mgmKey);

                    if (!authenticatedForCert)
                    {
                        doWorkEventArgs.Cancel = true;
                        _enrollWorkerMessage   = "Unable to authenticate prior to importing a certificate";
                        return;
                    }

                    if (std_user != "")
                    {
                        try
                        {
                            pivTool.SetCertificate9a(std_cert);
                        }
                        catch
                        {
                            doWorkEventArgs.Cancel = true;
                            _enrollWorkerMessage   = $"Unable to import a certificate";
                            return;
                        }
                    }

                    if (adm_user != "")
                    {
                        try
                        {
                            pivTool.SetCertificate9d(adm_cert);
                        }
                        catch
                        {
                            doWorkEventArgs.Cancel = true;
                            _enrollWorkerMessage   = $"Unable to import a certificate";
                            return;
                        }
                    }

                    _enrollWorker.ReportProgress(13);
                }

                // 14 - Create enrolled item for Standard User
                if (std_user != "")
                {
                    EnrolledYubikey newEnrollment_std = new EnrolledYubikey();
                    newEnrollment_std.DeviceSerial = deviceId;

                    newEnrollment_std.Certificate.Serial         = std_cert.SerialNumber;
                    newEnrollment_std.Certificate.Thumbprint     = std_cert.Thumbprint;
                    newEnrollment_std.Certificate.Subject        = std_cert.Subject;
                    newEnrollment_std.Certificate.Issuer         = std_cert.Issuer;
                    newEnrollment_std.Certificate.StartDate      = std_cert.NotBefore;
                    newEnrollment_std.Certificate.ExpireDate     = std_cert.NotAfter;
                    newEnrollment_std.Certificate.RawCertificate = std_cert.RawData;

                    newEnrollment_std.CA            = ca;
                    newEnrollment_std.Username      = std_user;
                    newEnrollment_std.Slot          = "Standard User";
                    newEnrollment_std.ManagementKey = mgmKey;
                    newEnrollment_std.PukKey        = puk;
                    newEnrollment_std.Chuid         = BitConverter.ToString(chuid).Replace("-", "");

                    newEnrollment_std.EnrolledAt = DateTime.UtcNow;

                    newEnrollment_std.YubikeyVersions.NeoFirmware = neoFirmware;
                    newEnrollment_std.YubikeyVersions.PivApplet   = pivFirmware.ToString();

                    _dataStore.Add(newEnrollment_std);
                }

                // 14 - Create enrolled item for Admin User
                if (adm_user != "")
                {
                    EnrolledYubikey newEnrollment_adm = new EnrolledYubikey();
                    newEnrollment_adm.DeviceSerial = deviceId;

                    newEnrollment_adm.Certificate.Serial         = adm_cert.SerialNumber;
                    newEnrollment_adm.Certificate.Thumbprint     = adm_cert.Thumbprint;
                    newEnrollment_adm.Certificate.Subject        = adm_cert.Subject;
                    newEnrollment_adm.Certificate.Issuer         = adm_cert.Issuer;
                    newEnrollment_adm.Certificate.StartDate      = adm_cert.NotBefore;
                    newEnrollment_adm.Certificate.ExpireDate     = adm_cert.NotAfter;
                    newEnrollment_adm.Certificate.RawCertificate = adm_cert.RawData;

                    newEnrollment_adm.CA            = ca;
                    newEnrollment_adm.Username      = adm_user;
                    newEnrollment_adm.Slot          = "Admin User";
                    newEnrollment_adm.ManagementKey = mgmKey;
                    newEnrollment_adm.PukKey        = puk;
                    newEnrollment_adm.Chuid         = BitConverter.ToString(chuid).Replace("-", "");

                    newEnrollment_adm.EnrolledAt = DateTime.UtcNow;

                    newEnrollment_adm.YubikeyVersions.NeoFirmware = neoFirmware;
                    newEnrollment_adm.YubikeyVersions.PivApplet   = pivFirmware.ToString();

                    _dataStore.Add(newEnrollment_adm);
                }

                _enrollWorker.ReportProgress(14);

                // 15 - Save store
                _dataStore.Save(MainForm.FileStore);

                _enrollWorker.ReportProgress(15);

                // Report
                doWorkEventArgs.Cancel = false;
                _enrollWorkerMessage   = "Success";
            }
        }