Пример #1
0
 /// <summary>
 /// Get the signature for the image.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void SignBtn_Click(object sender, EventArgs e)
 {
     try
     {
         OpenFileDialog dlg = new OpenFileDialog();
         dlg.Multiselect = false;
         if (SigningKeyTb.Text == "" || Path.GetFileName(SigningKeyTb.Text) == "")
         {
             dlg.InitialDirectory = Directory.GetCurrentDirectory();
             dlg.Filter           = Properties.Resources.PemFilterTxt;
             dlg.DefaultExt       = ".pem";
             dlg.ValidateNames    = true;
             if (dlg.ShowDialog(this) == DialogResult.OK)
             {
                 SigningKeyTb.Text = dlg.FileName;
             }
             else
             {
                 return;
             }
         }
         GXPkcs8 key   = GXPkcs8.Load(SigningKeyTb.Text);
         GXEcdsa ecdsa = new GXEcdsa(key.PrivateKey);
         SignatureTb.Text = GXDLMSTranslator.ToHex(ecdsa.Sign(File.ReadAllBytes(FileNameTb.Text)));
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Пример #2
0
 /// <summary>
 /// Add new key.
 /// </summary>
 private void KeyAddMnu_Click(object sender, EventArgs e)
 {
     try
     {
         OpenFileDialog dlg = new OpenFileDialog();
         dlg.Multiselect = true;
         if (string.IsNullOrEmpty(_path))
         {
             dlg.InitialDirectory = Directory.GetCurrentDirectory();
         }
         else
         {
             System.IO.FileInfo fi = new System.IO.FileInfo(_path);
             dlg.InitialDirectory = fi.DirectoryName;
             dlg.FileName         = fi.Name;
         }
         dlg.Filter        = Properties.Resources.PemFilterTxt;
         dlg.DefaultExt    = ".pem";
         dlg.ValidateNames = true;
         StringBuilder sb = new StringBuilder();
         if (dlg.ShowDialog(Parent) == DialogResult.OK)
         {
             GXPkcs8 key;
             foreach (string fileName in dlg.FileNames)
             {
                 _path = fileName;
                 try
                 {
                     key = GXPkcs8.Load(fileName);
                 }
                 catch (Exception ex)
                 {
                     sb.AppendLine(fileName);
                     continue;
                 }
                 string path = Path.Combine(KeyFolder, Path.GetFileName(fileName));
                 if (File.Exists(path))
                 {
                     DialogResult ret = MessageBox.Show(Parent, "Private key file already exists. Do you want to overwrite it?", "", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                     if (ret != DialogResult.Yes)
                     {
                         return;
                     }
                     RemoveKey(path);
                 }
                 key.Save(path);
                 KeyList.SelectedItems.Clear();
                 AddKey(key, path).Selected = true;
             }
         }
         if (sb.Length != 0)
         {
             MessageBox.Show(Parent, "Failed to load file(s)" + Environment.NewLine + sb.ToString());
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(Parent, ex.Message);
     }
 }
Пример #3
0
 private void InfoMnu_Click(object sender, EventArgs e)
 {
     try
     {
         ListViewItem it = KeyList.SelectedItems[0];
         ShowInfo(GXPkcs8.Load((string)it.Tag));
     }
     catch (Exception ex)
     {
         MessageBox.Show(Parent, ex.Message);
     }
 }
Пример #4
0
        private ListViewItem AddKey(GXPkcs8 cert, string path)
        {
            ListViewItem li = new ListViewItem(cert.PrivateKey.Scheme.ToString());

            li.SubItems.Add(cert.PrivateKey.ToHex(false));
            li.SubItems.Add(Path.GetFileNameWithoutExtension(path));
            li.SubItems.Add(cert.Description);
            li.StateImageIndex        = li.ImageIndex = 1;
            KeyList.Items.Add(li).Tag = path;
            privateKeys.Add(cert);
            return(li);
        }
Пример #5
0
        internal void ShowInfo(GXPkcs8 cert)
        {
            StringBuilder sb = new StringBuilder();

            if (!string.IsNullOrEmpty(cert.Description))
            {
                sb.AppendLine("Description:");
                sb.AppendLine(cert.Description);
                sb.AppendLine("");
            }
            sb.AppendLine("Private key:");
            sb.AppendLine(cert.PrivateKey.ToHex());
            sb.AppendLine(Environment.NewLine);
            sb.AppendLine("Public key info:");
            sb.AppendLine(cert.PublicKey.ToString());
            MessageBox.Show(Parent, sb.ToString());
        }
Пример #6
0
        /// <summary>
        /// Generate Certificate Signing Request (CSR) from private key.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CSRBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (SystemTitleTb.Text == "")
                {
                    throw new Exception("Invalid system title.");
                }
                byte[] st = GXDLMSTranslator.HexToBytes(SystemTitleTb.Text);
                if (st.Length != 8)
                {
                    throw new Exception("Invalid system title.");
                }

                OpenFileDialog dlg = new OpenFileDialog();
                dlg.Multiselect = false;
                if (string.IsNullOrEmpty(_path))
                {
                    dlg.InitialDirectory = Directory.GetCurrentDirectory();
                }
                else
                {
                    System.IO.FileInfo fi = new System.IO.FileInfo(_path);
                    dlg.InitialDirectory = fi.DirectoryName;
                    dlg.FileName         = fi.Name;
                }
                dlg.Filter        = Properties.Resources.PemFilterTxt;
                dlg.DefaultExt    = ".pem";
                dlg.ValidateNames = true;
                if (dlg.ShowDialog(Parent) == DialogResult.OK)
                {
                    string  path = dlg.FileName;
                    GXPkcs8 pk   = GXPkcs8.Load(path);
                    KeyValuePair <GXPublicKey, GXPrivateKey> kp = new KeyValuePair <GXPublicKey, GXPrivateKey>(pk.PublicKey, pk.PrivateKey);
                    //Generate certificate request and ask new x509Certificate.
                    GXPkcs10 pkc10 = GXPkcs10.CreateCertificateSigningRequest(kp, GXAsn1Converter.SystemTitleToSubject(st));
                    Pkcs10Tb.Text = pkc10.ToPem();
                    Pkcs10Tb.AppendText(Environment.NewLine);
                    Pkcs10Tb.AppendText(pkc10.ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Parent, ex.Message);
            }
        }
Пример #7
0
 public void UpdateKeys()
 {
     updateUI          = false;
     _checkSystemTitle = false;
     try
     {
         if (!string.IsNullOrEmpty(ClientSigningKey))
         {
             SelectWithPrivateKey(ClientSigningKeysCb, GXPkcs8.FromDer(ClientSigningKey));
         }
         else
         {
             ClientSigningKeysCb.SelectedItem = null;
         }
         if (!string.IsNullOrEmpty(ClientAgreementKey))
         {
             SelectWithPrivateKey(ClientAgreementKeysCb, GXPkcs8.FromDer(ClientAgreementKey));
         }
         else
         {
             ClientAgreementKeysCb.SelectedItem = null;
         }
         if (!string.IsNullOrEmpty(ServerSigningKey))
         {
             SelectWithCertificate(ServerSigningKeysCb, ServerSigningKey);
         }
         else
         {
             ServerSigningKeysCb.SelectedItem = null;
         }
         if (!string.IsNullOrEmpty(ServerAgreementKey))
         {
             SelectWithCertificate(ServerAgreementKeysCb, ServerAgreementKey);
         }
         else
         {
             ServerAgreementKeysCb.SelectedItem = null;
         }
     }
     finally
     {
         _checkSystemTitle = true;
         updateUI          = true;
     }
 }
Пример #8
0
 /// <summary>
 /// Generate new private key.
 /// </summary>
 private void GenerateBtn_Click(object sender, EventArgs e)
 {
     try
     {
         PrivateKey.Text     = "";
         GeneratedKeyTb.Text = "";
         KeyValuePair <GXPublicKey, GXPrivateKey> k = GXEcdsa.GenerateKeyPair(Key256.Checked ? Ecc.P256 : Ecc.P384);
         GXEcdsa.Validate(k.Key);
         Key = new GXPkcs8(k);
         GXEcdsa.Validate(Key.PublicKey);
         PrivateKey.Text = Key.ToPem();
         UpdateGeneratedKey();
     }
     catch (Exception ex)
     {
         Key = null;
         MessageBox.Show(this, ex.Message);
     }
 }
Пример #9
0
 private void descriptionToolStripMenuItem_Click(object sender, EventArgs e)
 {
     try
     {
         ListViewItem it  = KeyList.SelectedItems[0];
         GXTextDlg    dlg = new GXTextDlg("Certificate description.", "Certificate description:", it.SubItems[3].Text);
         if (dlg.ShowDialog(Parent) == DialogResult.OK)
         {
             string  desc = dlg.GetValue();
             GXPkcs8 cert = GXPkcs8.Load((string)it.Tag);
             cert.Description = desc;
             cert.Save((string)it.Tag);
             it.SubItems[3].Text = desc;
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(Parent, ex.Message);
     }
 }
Пример #10
0
        private static void SelectWithPrivateKey(ComboBox items, GXPkcs8 pk)
        {
            bool found = false;

            //Select default values.
            foreach (object tmp in items.Items)
            {
                if (tmp is KeyValuePair <GXPkcs8, GXx509Certificate> it)
                {
                    if (it.Key.Equals(pk))
                    {
                        items.SelectedItem = it;
                        found = true;
                        break;
                    }
                }
            }
            if (!found)
            {
                items.SelectedIndex = items.Items.Add(new KeyValuePair <GXPkcs8, GXx509Certificate>(pk, null));
            }
        }
Пример #11
0
 private void TransformBtn_Click(object sender, EventArgs e)
 {
     try
     {
         GeneratedKeyTb.Text = "";
         if (string.IsNullOrEmpty(PrivateKey.Text))
         {
             KeyValuePair <GXPublicKey, GXPrivateKey> k = GXEcdsa.GenerateKeyPair(Key256.Checked ? Ecc.P256 : Ecc.P384);
             Key = new GXPkcs8(k);
             GXEcdsa.Validate(k.Key);
         }
         else
         {
             Key = GXPkcs8.Import(PrivateKey.Text);
         }
         UpdateGeneratedKey();
     }
     catch (Exception ex)
     {
         Key = null;
         MessageBox.Show(this, ex.Message);
     }
 }
 /// <summary>
 /// Add new certificate.
 /// </summary>
 private void CertificateAddMnu_Click(object sender, EventArgs e)
 {
     try
     {
         OpenFileDialog dlg = new OpenFileDialog();
         dlg.Multiselect = false;
         if (string.IsNullOrEmpty(path))
         {
             dlg.InitialDirectory = Directory.GetCurrentDirectory();
         }
         else
         {
             System.IO.FileInfo fi = new System.IO.FileInfo(path);
             dlg.InitialDirectory = fi.DirectoryName;
             dlg.FileName         = fi.Name;
         }
         dlg.Filter        = Properties.Resources.CertificateFilterTxt;
         dlg.DefaultExt    = ".pem";
         dlg.ValidateNames = true;
         if (dlg.ShowDialog(this) == DialogResult.OK)
         {
             bool exists = false;
             if (File.Exists(dlg.FileName))
             {
                 try
                 {
                     GXx509Certificate cert = GXx509Certificate.Load(dlg.FileName);
                     foreach (ListViewItem it in CertificatesList.Items)
                     {
                         if (it.Tag is GXx509Certificate c)
                         {
                             if (c.Subject == cert.Subject)
                             {
                                 exists = true;
                                 throw new Exception("Public key already exists.");
                             }
                         }
                     }
                     ListViewItem li = new ListViewItem("Public Key");
                     li.StateImageIndex = li.ImageIndex = 0;
                     li.SubItems.Add(cert.Subject);
                     li.SubItems.Add(cert.ValidFrom + "-" + cert.ValidTo);
                     StringBuilder sb = new StringBuilder();
                     foreach (KeyUsage it in Enum.GetValues(typeof(KeyUsage)))
                     {
                         if (((int)it & (int)cert.KeyUsage) != 0)
                         {
                             sb.Append(it);
                             sb.Append(", ");
                         }
                     }
                     if (sb.Length != 0)
                     {
                         sb.Length -= 2;
                     }
                     li.SubItems.Add(sb.ToString());
                     CertificatesList.Items.Add(li).Tag = cert;
                 }
                 catch (Exception)
                 {
                     if (!exists)
                     {
                         //Check if this is private key.
                         GXPkcs8      cert = GXPkcs8.Load(dlg.FileName);
                         ListViewItem li   = new ListViewItem("Private Key");
                         li.StateImageIndex = li.ImageIndex = 1;
                         foreach (ListViewItem it in CertificatesList.Items)
                         {
                             if (it.Tag is GXPkcs8)
                             {
                                 throw new Exception("Private key already exists. There can be only one private key.");
                             }
                         }
                         CertificatesList.Items.Add(li).Tag = cert;
                     }
                 }
                 path = dlg.FileName;
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message);
     }
 }
        public DLMSTranslatorForm()
        {
            InitializeComponent();
            translator.Comments = true;
            SecurityCB.Items.AddRange(new object[] { Security.None, Security.Authentication,
                                                     Security.Encryption, Security.AuthenticationEncryption });
            SecurityCB.SelectedItem  = Enum.Parse(typeof(Security), Properties.Settings.Default.Security);
            SystemTitleTB.Text       = Properties.Settings.Default.NotifySystemTitle;
            ServerSystemTitleTB.Text = Properties.Settings.Default.ServerSystemTitle;
            BlockCipherKeyTB.Text    = Properties.Settings.Default.NotifyBlockCipherKey;
            AuthenticationKeyTB.Text = Properties.Settings.Default.AuthenticationKey;
            InvocationCounterTB.Text = Properties.Settings.Default.InvocationCounter.ToString();
            ChallengeTb.Text         = Properties.Settings.Default.Challenge;
            DedicatedKeyTb.Text      = Properties.Settings.Default.DedicatedKey;

            DataPdu.Text = Properties.Settings.Default.Data;
            tabControl1_SelectedIndexChanged(null, null);
            if (!string.IsNullOrEmpty(Properties.Settings.Default.Pdu))
            {
                PduTB.Text = Properties.Settings.Default.Pdu;
            }
            if (!string.IsNullOrEmpty(Properties.Settings.Default.Message))
            {
                MessagePduTB.Text = Properties.Settings.Default.Message;
            }

            try
            {
                string[] certificates = Properties.Settings.Default.Certificates.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string str in certificates)
                {
                    try
                    {
                        if (str[0] == '0')
                        {
                            GXx509Certificate cert = new GXx509Certificate(str.Substring(1));
                            ListViewItem      li   = new ListViewItem("Public Key");
                            li.StateImageIndex = li.ImageIndex = 0;
                            li.SubItems.Add(cert.Subject);
                            li.SubItems.Add(cert.ValidFrom + "-" + cert.ValidTo);
                            StringBuilder sb = new StringBuilder();
                            foreach (KeyUsage it in Enum.GetValues(typeof(KeyUsage)))
                            {
                                if (((int)it & (int)cert.KeyUsage) != 0)
                                {
                                    sb.Append(it);
                                    sb.Append(", ");
                                }
                            }
                            if (sb.Length != 0)
                            {
                                sb.Length -= 2;
                            }
                            li.SubItems.Add(sb.ToString());
                            CertificatesList.Items.Add(li).Tag = cert;
                        }
                        else
                        {
                            GXPkcs8      cert = new GXPkcs8(str.Substring(1));
                            ListViewItem li   = new ListViewItem("Private Key");
                            li.StateImageIndex = li.ImageIndex = 1;
                            foreach (ListViewItem it in CertificatesList.Items)
                            {
                                if (it.Tag is GXPkcs8)
                                {
                                    throw new Exception("Private key already exists. There can be only one private key.");
                                }
                            }
                            CertificatesList.Items.Add(li).Tag = cert;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Пример #14
0
        public GXKeyForm(IGXUpdater updater, string address, string keyFolder, string certificateFolder, string title, SecuritySuite securitySuite, byte[] systemTitle)
        {
            InitializeComponent();
            _updater           = updater;
            _address           = address;
            _certificateFolder = certificateFolder;
            _systemTitle       = systemTitle;
            privateKeys        = new GXPkcs8Collection();
            KeyFolder          = keyFolder;
            Title = title;

            foreach (string p in Directory.GetFiles(keyFolder))
            {
                string ext = Path.GetExtension(p);
                if (string.Compare(ext, ".pem", true) == 0 || string.Compare(ext, ".cer", true) == 0)
                {
                    try
                    {
                        GXPkcs8 cert = GXPkcs8.Load(p);
                        AddKey(cert, p);
                    }
                    catch (Exception)
                    {
                        Debug.WriteLine("Failed to open " + p);
                    }
                }
            }
            if (_systemTitle != null)
            {
                string path = Path.Combine(KeyFolder, "D" + GXDLMSTranslator.ToHex(_systemTitle, false)) + ".pem";
                //Generate private key for digital signature.
                GXPkcs8 digitalSignature = new GXPkcs8(GXEcdsa.GenerateKeyPair(securitySuite == SecuritySuite.Suite1 ? Ecc.P256 : Ecc.P384));
                digitalSignature.Save(path);
                AddKey(digitalSignature, path);
                path = Path.Combine(KeyFolder, "A" + GXDLMSTranslator.ToHex(_systemTitle, false)) + ".pem";
                //Generate private key for Key agreement.
                GXPkcs8 keyAgreement = new GXPkcs8(GXEcdsa.GenerateKeyPair(Ecc.P256));
                keyAgreement.Save(path);
                AddKey(keyAgreement, path);

                //Get CRS.
                KeyValuePair <GXPublicKey, GXPrivateKey> kp = new KeyValuePair <GXPublicKey, GXPrivateKey>(digitalSignature.PublicKey, digitalSignature.PrivateKey);
                //Generate certificate request and ask new x509Certificate.
                //Note! There is a limit how many request you can do in a day.
                List <GXCertificateRequest> certifications = new List <GXCertificateRequest>();
                GXCertificateRequest        it             = new GXCertificateRequest();
                it.Certificate     = GXPkcs10.CreateCertificateSigningRequest(kp, GXAsn1Converter.SystemTitleToSubject(_systemTitle));
                it.CertificateType = CertificateType.DigitalSignature;
                certifications.Add(it);
                it                 = new GXCertificateRequest();
                it.Certificate     = GXPkcs10.CreateCertificateSigningRequest(kp, GXAsn1Converter.SystemTitleToSubject(_systemTitle));
                it.CertificateType = CertificateType.KeyAgreement;
                certifications.Add(it);
                GXx509Certificate[] certificates = GXPkcs10.GetCertificate(address, certifications);
                foreach (GXx509Certificate cert in certificates)
                {
                    if (cert.KeyUsage == KeyUsage.DigitalSignature)
                    {
                        path = "D" + GXDLMSTranslator.ToHex(_systemTitle, false);
                    }
                    else if (cert.KeyUsage == KeyUsage.KeyAgreement)
                    {
                        path = "A" + GXDLMSTranslator.ToHex(_systemTitle, false);
                    }
                    else if (cert.KeyUsage == (KeyUsage.KeyAgreement | KeyUsage.DigitalSignature))
                    {
                        path = "T" + GXDLMSTranslator.ToHex(_systemTitle, false);
                    }
                    else
                    {
                        path = "O" + GXDLMSTranslator.ToHex(_systemTitle, false);
                    }
                    path = Path.Combine(_certificateFolder, path) + ".pem";
                    cert.Save(path);
                }
            }
        }
Пример #15
0
        /// <summary>
        /// Get certificate for the private key.
        /// </summary>
        private void GetCertificateMnu_Click(object sender, EventArgs e)
        {
            try
            {
                ListViewItem it = KeyList.SelectedItems[0];
                GXCertificateSigningRequestDlg dlg = new GXCertificateSigningRequestDlg(SystemTitle);
                if (dlg.ShowDialog(Parent) == DialogResult.OK)
                {
                    SystemTitle = dlg.SystemTitle;
                    GXPkcs8 pk = GXPkcs8.Load((string)it.Tag);
                    KeyValuePair <GXPublicKey, GXPrivateKey> kp = new KeyValuePair <GXPublicKey, GXPrivateKey>(pk.PublicKey, pk.PrivateKey);
                    List <GXCertificateRequest> certifications  = new List <GXCertificateRequest>();
                    GXCertificateRequest        it2             = new GXCertificateRequest();
                    it2.CertificateType  = dlg.CertificateType;
                    it2.ExtendedKeyUsage = dlg.ExtendedKeyUsage;
                    //Generate certificate request and ask new x509Certificate.
                    it2.Certificate = GXPkcs10.CreateCertificateSigningRequest(kp, GXAsn1Converter.SystemTitleToSubject(SystemTitle));
                    certifications.Add(it2);
                    //Note! There is a limit how many request you can do in a day.
                    GXx509Certificate[] certificates = GXPkcs10.GetCertificate(_address, certifications);
                    foreach (GXx509Certificate cert in certificates)
                    {
                        if (cert.KeyUsage == KeyUsage.DigitalSignature)
                        {
                            _path = "D" + Path.GetFileName((string)it.Tag);
                        }
                        else if (cert.KeyUsage == KeyUsage.KeyAgreement)
                        {
                            _path = "A" + Path.GetFileName((string)it.Tag);
                        }
                        else if (cert.KeyUsage == (KeyUsage.KeyAgreement | KeyUsage.DigitalSignature))
                        {
                            //TLS.
                            _path = "T" + Path.GetFileName((string)it.Tag);
                        }
                        else
                        {
                            //Other.
                            _path = "O" + Path.GetFileName((string)it.Tag);
                        }

                        if (File.Exists(_path))
                        {
                            if (cert.KeyUsage == KeyUsage.DigitalSignature)
                            {
                                _path = "D" + GXDLMSTranslator.ToHex(SystemTitle, false);
                            }
                            else if (cert.KeyUsage == KeyUsage.KeyAgreement)
                            {
                                _path = "A" + GXDLMSTranslator.ToHex(SystemTitle, false);
                            }
                            else if (cert.KeyUsage == (KeyUsage.KeyAgreement | KeyUsage.DigitalSignature))
                            {
                                //TLS.
                                _path = "T" + GXDLMSTranslator.ToHex(SystemTitle, false);
                            }
                            else
                            {
                                //Other.
                                _path = "O" + GXDLMSTranslator.ToHex(SystemTitle, false);
                            }
                            _path += ".pem";
                        }
                        _path = Path.Combine(_certificateFolder, _path);
                        cert.Save(_path);
                    }
                    _updater.UpdateUI();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Parent, ex.Message);
            }
        }
Пример #16
0
        public static int GetParameters(string[] args, Settings settings)
        {
            string[] tmp;
            List <GXCmdParameter> parameters = GXCommon.GetParameters(args, "h:p:c:s:r:i:It:a:P:g:S:C:n:v:o:T:A:B:D:d:l:F:K:k:m:");
            GXNet net = null;

            foreach (GXCmdParameter it in parameters)
            {
                switch (it.Tag)
                {
                case 'r':
                    if (string.Compare(it.Value, "sn", true) == 0)
                    {
                        settings.client.UseLogicalNameReferencing = false;
                    }
                    else if (string.Compare(it.Value, "ln", true) == 0)
                    {
                        settings.client.UseLogicalNameReferencing = true;
                    }
                    else
                    {
                        throw new ArgumentException("Invalid reference option.");
                    }
                    break;

                case 'h':
                    //Host address.
                    if (settings.media == null)
                    {
                        settings.media = new GXNet();
                    }
                    net          = settings.media as GXNet;
                    net.HostName = it.Value;
                    break;

                case 't':
                    //Trace.
                    try
                    {
                        settings.trace = (TraceLevel)Enum.Parse(typeof(TraceLevel), it.Value);
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid trace level option. (Error, Warning, Info, Verbose, Off)");
                    }
                    break;

                case 'p':
                    //Port.
                    if (settings.media == null)
                    {
                        settings.media = new GXNet();
                    }
                    net      = settings.media as GXNet;
                    net.Port = int.Parse(it.Value);
                    break;

                case 'P':    //Password
                    settings.client.Password = ASCIIEncoding.ASCII.GetBytes(it.Value);
                    break;

                case 'i':
                    try
                    {
                        settings.client.InterfaceType = (InterfaceType)Enum.Parse(typeof(InterfaceType), it.Value);
                        settings.client.Plc.Reset();
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid interface type option. (HDLC, WRAPPER, HdlcWithModeE, Plc, PlcHdlc)");
                    }
                    break;

                case 'I':
                    //AutoIncreaseInvokeID.
                    settings.client.AutoIncreaseInvokeID = true;
                    break;

                case 'v':
                    settings.invocationCounter = it.Value.Trim();
                    Objects.GXDLMSObject.ValidateLogicalName(settings.invocationCounter);
                    break;

                case 'g':
                    //Get (read) selected objects.
                    foreach (string o in it.Value.Split(new char[] { ';', ',' }))
                    {
                        tmp = o.Split(new char[] { ':' });
                        if (tmp.Length != 2)
                        {
                            throw new ArgumentOutOfRangeException("Invalid Logical name or attribute index.");
                        }
                        settings.readObjects.Add(new KeyValuePair <string, int>(tmp[0].Trim(), int.Parse(tmp[1].Trim())));
                    }
                    break;

                case 'S':    //Serial Port
                    settings.media = new GXSerial();
                    GXSerial serial = settings.media as GXSerial;
                    tmp             = it.Value.Split(':');
                    serial.PortName = tmp[0];
                    if (tmp.Length > 1)
                    {
                        serial.BaudRate = int.Parse(tmp[1]);
                        serial.DataBits = int.Parse(tmp[2].Substring(0, 1));
                        serial.Parity   = (Parity)Enum.Parse(typeof(Parity), tmp[2].Substring(1, tmp[2].Length - 2));
                        serial.StopBits = (StopBits)int.Parse(tmp[2].Substring(tmp[2].Length - 1, 1));
                    }
                    else
                    {
                        if (settings.client.InterfaceType == InterfaceType.HdlcWithModeE)
                        {
                            serial.BaudRate = 300;
                            serial.DataBits = 7;
                            serial.Parity   = Parity.Even;
                            serial.StopBits = StopBits.One;
                        }
                        else
                        {
                            serial.BaudRate = 9600;
                            serial.DataBits = 8;
                            serial.Parity   = Parity.None;
                            serial.StopBits = StopBits.One;
                        }
                    }
                    break;

                case 'a':
                    try
                    {
                        if (string.Compare("None", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.None;
                        }
                        else if (string.Compare("Low", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.Low;
                        }
                        else if (string.Compare("High", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.High;
                        }
                        else if (string.Compare("HighMd5", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighMD5;
                        }
                        else if (string.Compare("HighSha1", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighSHA1;
                        }
                        else if (string.Compare("HighSha256", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighSHA256;
                        }
                        else if (string.Compare("HighGMac", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighGMAC;
                        }
                        else if (string.Compare("HighECDSA", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighECDSA;
                        }
                        else
                        {
                            throw new ArgumentException("Invalid Authentication option: '" + it.Value + "'. (None, Low, High, HighMd5, HighSha1, HighGMac, HighSha256)");
                        }
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid Authentication option: '" + it.Value + "'. (None, Low, High, HighMd5, HighSha1, HighGMac, HighSha256)");
                    }
                    break;

                case 'C':
                    try
                    {
                        settings.client.Ciphering.Security = Convert.ToByte(Enum.Parse(typeof(Security), it.Value));
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid Ciphering option '" + it.Value + "'. (None, Authentication, Encryption, AuthenticationEncryption)");
                    }
                    break;

                case 'T':
                    settings.client.Ciphering.SystemTitle = GXCommon.HexToBytes(it.Value);
                    break;

                case 'A':
                    settings.client.Ciphering.AuthenticationKey = GXCommon.HexToBytes(it.Value);
                    break;

                case 'B':
                    settings.client.Ciphering.BlockCipherKey = GXCommon.HexToBytes(it.Value);
                    break;

                case 'D':
                    settings.client.Ciphering.DedicatedKey = GXCommon.HexToBytes(it.Value);
                    break;

                case 'F':
                    settings.client.Ciphering.InvocationCounter = UInt32.Parse(it.Value.Trim());
                    break;

                case 'K':
                    GXPkcs8 cert1 = GXPkcs8.Load(it.Value);
                    settings.client.Ciphering.SigningKeyPair = new KeyValuePair <GXPrivateKey, GXPublicKey>(cert1.PrivateKey, cert1.PublicKey);
                    Console.WriteLine("Client Private key: " + GXDLMSTranslator.ToHex(cert1.PrivateKey.RawValue));
                    Console.WriteLine("Client Public key: " + GXDLMSTranslator.ToHex(cert1.PublicKey.RawValue));
                    break;

                case 'k':
                    GXx509Certificate cert = GXx509Certificate.Load(it.Value);
                    if ((cert.KeyUsage & ASN.Enums.KeyUsage.DigitalSignature) == 0)
                    {
                        throw new Exception("This certificate is not used for digital signature.");
                    }
                    settings.client.Ciphering.PublicKeys.Add(new KeyValuePair <CertificateType, GXx509Certificate>(CertificateType.DigitalSignature, cert));
                    string[] sn = cert.Subject.Split('=');
                    if (sn.Length != 2)
                    {
                        throw new ArgumentOutOfRangeException("Invalid public key subject.");
                    }
                    settings.client.Ciphering.SystemTitle = GXDLMSTranslator.HexToBytes(sn[1]);
                    Console.WriteLine("Server Public key: " + GXDLMSTranslator.ToHex(cert.PublicKey.RawValue));
                    break;

                case 'o':
                    settings.outputFile = it.Value;
                    break;

                case 'd':
                    try
                    {
                        settings.client.Standard = (Standard)Enum.Parse(typeof(Standard), it.Value);
                        if (settings.client.Standard == Standard.Italy || settings.client.Standard == Standard.India || settings.client.Standard == Standard.SaudiArabia)
                        {
                            settings.client.UseUtc2NormalTime = true;
                        }
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid DLMS standard option '" + it.Value + "'. (DLMS, India, Italy, SaudiArabia, IDIS)");
                    }
                    break;

                case 'c':
                    settings.client.ClientAddress = int.Parse(it.Value);
                    break;

                case 's':
                    if (settings.client.ServerAddress != 1)
                    {
                        settings.client.ServerAddress = GXDLMSClient.GetServerAddress(settings.client.ServerAddress, int.Parse(it.Value));
                    }
                    else
                    {
                        settings.client.ServerAddress = int.Parse(it.Value);
                    }
                    break;

                case 'l':
                    settings.client.ServerAddress = GXDLMSClient.GetServerAddress(int.Parse(it.Value), settings.client.ServerAddress);
                    break;

                case 'n':
                    settings.client.ServerAddress = GXDLMSClient.GetServerAddress(int.Parse(it.Value));
                    break;

                case 'm':
                    settings.client.Plc.MacDestinationAddress = UInt16.Parse(it.Value);
                    break;

                case '?':
                    switch (it.Tag)
                    {
                    case 'c':
                        throw new ArgumentException("Missing mandatory client option.");

                    case 's':
                        throw new ArgumentException("Missing mandatory server option.");

                    case 'h':
                        throw new ArgumentException("Missing mandatory host name option.");

                    case 'p':
                        throw new ArgumentException("Missing mandatory port option.");

                    case 'r':
                        throw new ArgumentException("Missing mandatory reference option.");

                    case 'a':
                        throw new ArgumentException("Missing mandatory authentication option.");

                    case 'S':
                        throw new ArgumentException("Missing mandatory Serial port option.");

                    case 't':
                        throw new ArgumentException("Missing mandatory trace option.");

                    case 'g':
                        throw new ArgumentException("Missing mandatory OBIS code option.");

                    case 'C':
                        throw new ArgumentException("Missing mandatory Ciphering option.");

                    case 'v':
                        throw new ArgumentException("Missing mandatory invocation counter logical name option.");

                    case 'T':
                        throw new ArgumentException("Missing mandatory system title option.");

                    case 'A':
                        throw new ArgumentException("Missing mandatory authentication key option.");

                    case 'B':
                        throw new ArgumentException("Missing mandatory block cipher key option.");

                    case 'D':
                        throw new ArgumentException("Missing mandatory dedicated key option.");

                    case 'F':
                        throw new ArgumentException("Missing mandatory frame counter option.");

                    case 'd':
                        throw new ArgumentException("Missing mandatory DLMS standard option.");

                    case 'K':
                        throw new ArgumentException("Missing mandatory private key file option.");

                    case 'k':
                        throw new ArgumentException("Missing mandatory public key file option.");

                    case 'l':
                        throw new ArgumentException("Missing mandatory logical server address option.");

                    case 'm':
                        throw new ArgumentException("Missing mandatory MAC destination address option.");

                    default:
                        ShowHelp();
                        return(1);
                    }

                default:
                    ShowHelp();
                    return(1);
                }
            }
            if (settings.media == null)
            {
                ShowHelp();
                return(1);
            }
            return(0);
        }