Exemplo n.º 1
0
        public X509Certificate2 CreateNamedKeyCertificate(CertData data)
        {
            try
            {
                CngKeyCreationParameters keyCreationParameters
                    = new CngKeyCreationParameters
                    {
                    ExportPolicy =
                        CngExportPolicies.AllowExport |
                        CngExportPolicies.AllowPlaintextExport |
                        CngExportPolicies.AllowPlaintextArchiving |
                        CngExportPolicies.AllowArchiving,
                    KeyUsage = CngKeyUsages.AllUsages
                    };

                X509Certificate2 cert;
                X509CertificateCreationParameters configCreate
                    = new X509CertificateCreationParameters(new X500DistinguishedName(data.DistinguishedName))
                    {
                    EndTime =
                        DateTime.Parse("01/01/2020",
                                       System.Globalization.
                                       DateTimeFormatInfo.
                                       InvariantInfo),
                    StartTime =
                        DateTime.Parse("01/01/2010",
                                       System.Globalization.
                                       DateTimeFormatInfo.
                                       InvariantInfo)
                    };

                using (CngKey namedKey = CngKey.Create(CngAlgorithm2.Rsa, data.Key, keyCreationParameters))
                {
                    cert = namedKey.CreateSelfSignedCertificate(configCreate);
                    cert.FriendlyName = data.Friendlyname;
                    Assert.True(cert.HasPrivateKey);
                    Assert.True(cert.HasCngKey());
                    using (CngKey certKey = cert.GetCngPrivateKey())
                    {
                        Assert.Equal(CngAlgorithm2.Rsa, certKey.Algorithm);
                    }
                }
                return(cert);
            }
            finally
            {
                if (CngKey.Exists(data.Key))
                {
                    using (CngKey key = CngKey.Open(data.Key))
                    {
                        key.Delete();
                    }
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Connects to the SMGW using this HAN adapter instance.
        /// </summary>
        /// <param name="connectData">The connect data.</param>
        /// <param name="clientCert">The client cert.</param>
        /// <param name="manufacturerParameters">The manufacturer parameters.</param>
        /// <param name="ct">The cancellation token.</param>
        /// <param name="progressCallback">The progress callback.</param>
        /// <returns>The connect result.</returns>
        /// <exception cref="HanAdapterException">AdapterError from the HAN adapter.</exception>
        public async Task <ConnectResult> Connect(
            ConnectData connectData,
            CertData clientCert,
            Dictionary <string, string> manufacturerParameters,
            CancellationToken ct,
            Action <ProgressInfo> progressCallback)
        {
            var endpoint = new IPEndPoint(IPAddress.Parse(connectData.Address), connectData.Port);

            (ConnectResult result, AdapterError error)connectResult;

            switch (connectData.AuthMode)
            {
            case AuthMode.UserPassword:
                connectResult = await this.Adapter.Connect(
                    connectData.DeviceId,
                    endpoint,
                    connectData.Username,
                    connectData.Password,
                    manufacturerParameters,
                    TimeSpan.FromSeconds(30),
                    ct,
                    progressCallback);

                break;

            case AuthMode.ClientCertificate:
                connectResult = await this.Adapter.Connect(
                    connectData.DeviceId,
                    endpoint,
                    clientCert.Data,
                    clientCert.Password,
                    manufacturerParameters,
                    TimeSpan.FromSeconds(30),
                    ct,
                    progressCallback);

                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(connectData.AuthMode));
            }

            if (connectResult.error != null)
            {
                throw new HanAdapterException(connectResult.error);
            }

            return(connectResult.result);
        }
Exemplo n.º 3
0
        public async Task <IActionResult> UploadClientCert(List <IFormFile> files)
        {
            var file = this.Request?.Form?.Files?.FirstOrDefault();

            if (file == null)
            {
                return(this.PartialView("_CertWithoutPasswordPartial", null));
            }

            var ms = new MemoryStream();
            await file.CopyToAsync(ms);

            var certData = new CertData(file.FileName, ms.ToArray());

            this.applicationState.ClientCert = certData;

            return(this.VerifyCertPassword(this.applicationState.ClientCert.Password));
        }
Exemplo n.º 4
0
        public IActionResult Details(int id)
        {
            Certification = new CertificationsModel();
            Certification = CertData.GetById(id);
            image         = new Fileupload();
            image         = fileData.GetByCertId(id).FirstOrDefault();
            ViewBag.story = JsonConvert.SerializeObject(new String(""));

            if (Certification.CertUrl != null)
            {
                return(View(Certification));
            }

            if (Certification == null)
            {
                TempData["Error"] = $"Certification does not exist";
                return(RedirectToAction("Index", "Certifications"));
            }

            if (Certification.CertUrl == null && image != null)
            {
                System.Console.WriteLine("No Certification url");

                string imageDataBytes = Convert.ToBase64String(image.FileData);

                //IF UPLOADED IS PNG
                if (image.FileName.Contains(".pdf"))
                {
                    ViewBag.story = JsonConvert.SerializeObject(imageDataBytes);
                }
                else
                {
                    string imageUrl = string.Format("data:/image/jpeg;base64,{0}", imageDataBytes);                     //Original
                    Certification.CertUrl = imageUrl;
                }
            }
            else
            {
                TempData["Error"] = $"Certification '{Certification.CertName}' with Id: {Certification.Id} does not have a certification";
                return(RedirectToAction("Index", "Certifications"));
            }

            return(View(Certification));
        }
Exemplo n.º 5
0
        public void TestCertificateEncryption1()
        {
            POIFSFileSystem         fs   = new POIFSFileSystem();
            EncryptionInfo          info = new EncryptionInfo(EncryptionMode.Agile, CipherAlgorithm.aes128, HashAlgorithm.sha1, -1, -1, ChainingMode.cbc);
            AgileEncryptionVerifier aev  = (AgileEncryptionVerifier)info.Verifier;
            CertData certData            = loadKeystore();

            aev.AddCertificate(certData.x509);

            Encryptor enc = info.Encryptor;

            enc.ConfirmPassword("foobaa");

            FileStream file = POIDataSamples.GetDocumentInstance().GetFile("VariousPictures.docx");

            //InputStream fis = new FileInputStream(file);
            byte[] byteExpected = IOUtils.ToByteArray(file);
            //fis.Close();

            Stream os = enc.GetDataStream(fs);

            IOUtils.Copy(new MemoryStream(byteExpected), os);
            os.Close();

            MemoryStream bos = new MemoryStream();

            fs.WriteFileSystem(bos);
            bos.Close();

            fs   = new POIFSFileSystem(new MemoryStream(bos.ToArray()));
            info = new EncryptionInfo(fs);
            AgileDecryptor agDec  = (AgileDecryptor)info.Decryptor;
            bool           passed = agDec.VerifyPassword(certData.keypair, certData.x509);

            Assert.IsTrue(passed, "certificate verification failed");

            Stream fis = agDec.GetDataStream(fs);

            byte[] byteActual = IOUtils.ToByteArray(fis);
            fis.Close();

            Assert.That(byteExpected, Is.EqualTo(byteActual));
        }
Exemplo n.º 6
0
        public SearchModel SearchCertificationsAndProfiles(string search)
        {
            SearchModel model = new SearchModel();


            model.search = search;

            if (!string.IsNullOrWhiteSpace(search))
            {
                var profile = profileData.GetProfileByEmail(search);
                if (!profile.IsPrivate)
                {
                    model.profile = profile;

                    model.profile.ProfileImageUrl = GetImageUrl(model.profile);

                    model.Certifications = CertData.GetCertificationsByAuthor(search);
                }
                else if (profile.ProfileId != 0)
                {
                    model.profile        = new UserProfile();
                    model.Certifications = CertData.GetCertificationsByName(search);
                }
                else
                {
                    model.profile        = null;
                    model.Certifications = CertData.GetCertificationsByName(search);
                }
            }
            else
            {
                //If search is null
                model.Certifications = CertData.GetAll();
            }

            return(model);
        }
Exemplo n.º 7
0
        public X509Certificate2  CreateNamedKeyCertificate(CertData data)
        {
            try
            {
                CngKeyCreationParameters keyCreationParameters
                    = new CngKeyCreationParameters
                          {
                              ExportPolicy =
                                  CngExportPolicies.AllowExport |
                                  CngExportPolicies.AllowPlaintextExport |
                                  CngExportPolicies.AllowPlaintextArchiving |
                                  CngExportPolicies.AllowArchiving,
                              KeyUsage = CngKeyUsages.AllUsages
                          };

                X509Certificate2 cert;
                X509CertificateCreationParameters configCreate
                    = new X509CertificateCreationParameters(new X500DistinguishedName(data.DistinguishedName))
                          {
                              EndTime =
                                  DateTime.Parse("01/01/2020",
                                                 System.Globalization.
                                                     DateTimeFormatInfo.
                                                     InvariantInfo),
                              StartTime =
                                  DateTime.Parse("01/01/2010",
                                                 System.Globalization.
                                                     DateTimeFormatInfo.
                                                     InvariantInfo)
                          };

                using (CngKey namedKey = CngKey.Create(CngAlgorithm2.Rsa, data.Key, keyCreationParameters))
                {
                    cert = namedKey.CreateSelfSignedCertificate(configCreate);
                    cert.FriendlyName = data.Friendlyname;
                    Assert.True(cert.HasPrivateKey);
                    Assert.True(cert.HasCngKey());
                    using (CngKey certKey = cert.GetCngPrivateKey())
                    {
                        Assert.Equal(CngAlgorithm2.Rsa, certKey.Algorithm);
                    }
                }
                return cert;
            }
            finally
            {
                if (CngKey.Exists(data.Key))
                {
                    using (CngKey key = CngKey.Open(data.Key))
                    {
                        key.Delete();
                    }
                }
            }
        }