public void ParseCertificateType_ReturnsCorrectString(CertificateType certificateType, string expected)
        {
            //act
            var result = EnumFactory.ParseCertificateType(certificateType);

            //assert
            result.Should().Be(expected);
        }
        public void EnumHelper_Parse_ReturnsCorrectEnum(string value, CertificateType certificateType)
        {
            //act
            var result = EnumHelper<CertificateType>.Parse(value);

            //assert
            result.Should().Be(certificateType);
        }
 public CompanyCertificate(int comId, short certType,string certTitle, string certRemark)
     : this(comId)
 {
     companyId = comId;
     title = certTitle;
     remark = certRemark;
     imageGuid = Util.NewGuid;
     type = (CertificateType)certType;
 }
 private CompanyCertificate()
 {
     id = 0;
     companyId = 0;
     title = "";
     remark = "";
     imageGuid = Util.NewGuid;
     isChecked = true;
     type = CertificateType.Other;
 }
示例#5
0
 public static string ParseCertificateType(CertificateType certificateType)
 {
     switch (certificateType)
     {
         case CertificateType.Unknown:
             return "Unknown";
         case CertificateType.Epc:
             return "EPC";
         case CertificateType.GasSafetyCertificate:
             return "Gas Safety Certificate";
         default:
             return string.Empty;
     }
 }
示例#6
0
        public void SetCertificateType(CertificateType type)
        {
            switch (type)
            {
            case CertificateType.Default:
                info = null;
                break;

            case CertificateType.Manual:
                info = infoManual;
                break;

            case CertificateType.Profile:
                info = infoProfile;
                break;
            }
        }
示例#7
0
        public string UploadLicense()
        {
            int    memid    = CookieBLL.GetRegisterCookie();
            string memcodes = "";

            if (memid <= 0)
            {
                if (System.Web.HttpContext.Current.Session[CommonKey.MobileNoRegister] != null && System.Web.HttpContext.Current.Session[CommonKey.MobileYZCode] != null)
                {
                    memcodes = System.Web.HttpContext.Current.Session[CommonKey.MobileNoRegister].ToString();
                }
            }
            else
            {
                memcodes      = memid.ToString();
                ViewBag.MemId = memid;
            }
            if (!string.IsNullOrEmpty(memcodes))
            {
                HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
                int             aa       = files.Count;
                int             _pictype = FormString.IntSafeQ("pictype");
                HttpPostedFile  file     = System.Web.HttpContext.Current.Request.Files[0];
                CertificateType _certype = (CertificateType)_pictype;
                if (file != null)
                {
                    byte[] bytes = null;
                    using (var binaryReader = new BinaryReader(file.InputStream))
                    {
                        bytes = binaryReader.ReadBytes(file.ContentLength);
                    }
                    FtpUtil _ftp        = new FtpUtil();
                    Random  _rd         = new Random();
                    string  dicpath     = FilePath.PathCombine(ConfigCore.Instance.ConfigCommonEntity.FtpImagesSystemName, ImagesSysPathCode.Certifacate.ToString(), memcodes, DateTime.Now.ToString("yyyy"), DateTime.Now.ToString("MM"), DateTime.Now.ToString("dd"), _rd.Next(100000, 999999).ToString());
                    string  dicpathfull = dicpath + file.FileName.Substring(file.FileName.LastIndexOf("."));
                    string  certifapath = FilePath.PathCombine(ConfigCore.Instance.ConfigCommonEntity.FtpImagesRootPath, dicpathfull);
                    _ftp.UploadFile(certifapath, bytes, true);
                    //return dicpathfull;
                    return("{\"jsonrpc\" : \"2.0\", \"result\" : null, \"pic_raw\" : \"" + dicpathfull + "\"}");
                }
            }
            return("");
        }
示例#8
0
        /// <summary>
        /// <para>Initializer of the certificate object. Parsing and assigning individual fields into properties</para>
        /// </summary>
        /// <param name="certificate">The certificate to parse in string format.
        /// <param name="remainder">The remainder of the certificate.
        /// <param name="certificateType">The type (CertificateType) of the certificate.</param>
        public EmvCertificate(string certificate, string remainder, CertificateType certificateType)
        {
            _certificate     = certificate;
            _remainder       = remainder;
            _certificateType = certificateType;

            Version          = byte.Parse(certificate.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
            CType            = byte.Parse(certificate.Substring(2, 2), System.Globalization.NumberStyles.HexNumber);
            Issuer           = StringTools.HexStringToByteArray(certificate.Substring(4, 8));
            ExpDate          = StringTools.HexStringToByteArray(certificate.Substring(12, 4));
            SerialNumber     = StringTools.HexStringToByteArray(certificate.Substring(16, 6));
            HashAlgIndicator = byte.Parse(certificate.Substring(22, 2), System.Globalization.NumberStyles.HexNumber);
            pkAlg            = byte.Parse(certificate.Substring(24, 2), System.Globalization.NumberStyles.HexNumber);
            pkLength         = byte.Parse(certificate.Substring(26, 2), System.Globalization.NumberStyles.HexNumber);
            pkExponent       = byte.Parse(certificate.Substring(28, 2), System.Globalization.NumberStyles.HexNumber);


            int totalLength = pkLength + BeforeKeyLength + HashLength + TrailerLength - (remainder.Length / 2);

            HasPadding = (certificate.Length / 2) > totalLength;

            int i = 30 + (pkLength * 2) - remainder.Length;

            PublicKey = StringTools.HexStringToByteArray(certificate.Substring(30, (pkLength * 2) - remainder.Length) + remainder);

            if (HasPadding)
            {
                Padding = StringTools.HexStringToByteArray(certificate.Substring(30, certificate.Length - totalLength));
                i      += certificate.Length - totalLength;
            }


            Hash = StringTools.HexStringToByteArray(certificate.Substring(i, HashLength * 2));


            Trailer = byte.Parse(certificate.Substring(i + HashLength * 2, 2), System.Globalization.NumberStyles.HexNumber);


            if (certificateType == CertificateType.CA)
            {
                checkCA();
            }
        }
示例#9
0
        public Certificate(Stream s)
        {
            BinaryReader bR = new BinaryReader(s);

            if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "CE")
            {
                throw new InvalidCertificateException("Invalid certificate format.");
            }

            _version = bR.ReadByte();
            switch (_version)
            {
            case 1:
                _type = (CertificateType)bR.ReadByte();

                _serialNumber = Encoding.ASCII.GetString(bR.ReadBytes(bR.ReadByte()));
                _issuedTo     = new CertificateProfile(s);
                _capability   = (CertificateCapability)bR.ReadByte();

                _issuedOnUTC  = bR.ReadUInt64();
                _expiresOnUTC = bR.ReadUInt64();

                _publicKeyEncryptionAlgorithm = (AsymmetricEncryptionAlgorithm)bR.ReadByte();
                _publicKeyXML = Encoding.ASCII.GetString(bR.ReadBytes(bR.ReadUInt16()));

                byte rUriLen = bR.ReadByte();
                if (rUriLen > 0)
                {
                    _revocationUri = new Uri(Encoding.UTF8.GetString(bR.ReadBytes(rUriLen)));
                }

                if (s.ReadByte() == 1)
                {
                    _issuerSignature = new Signature(s);
                }

                break;

            default:
                throw new InvalidCertificateException("Certificate format version not supported.");
            }
        }
示例#10
0
        public static string CertificatePath(string basename, CertificateType certtype, StoreFormat format)
        {
            string filename          = "";
            string privateOutputPath = null;
            string publicOutputPath  = null;

            if (certtype == CertificateType.AuthorityCertificate)
            {
                privateOutputPath = AuthorityPrivateCertificatesPath;
                publicOutputPath  = AuthorityPublicCertificatesPath;
            }
            else if (certtype == CertificateType.ServerCertificate)
            {
                privateOutputPath = ServerPrivateCertificatesPath;
                publicOutputPath  = ServerPublicCertificatesPath;
            }
            else
            {
                privateOutputPath = UserPrivateCertificatesPath;
                publicOutputPath  = UserPublicCertificatesPath;
            }

            switch (format)
            {
            case StoreFormat.CRT:
                filename = publicOutputPath + basename + ".crt";
                break;

            case StoreFormat.P12Store:
                filename = privateOutputPath + basename + ".p12";
                break;

            case StoreFormat.PFX:
                filename = privateOutputPath + basename + ".pfx";
                break;

            default:
                throw new NotImplementedException();
            }

            return(filename);
        }
示例#11
0
 public ICertificate GetCertificate(string host, CertificateType certificateType)
 {
     for (var i = 0; i < _certificates.Count; i++)
     {
         if (host != null)
         {
             //Need to implement certificates for a specific host
             throw new NotImplementedException();
         }
         else
         {
             if (_certificates[i].CertificateType == certificateType)
             {
                 return(_certificates[i]);
             }
         }
     }
     Alerts.AlertException.ThrowAlert(Alerts.AlertLevel.Fatal, Alerts.AlertDescription.certificate_unobtainable, $"Could not find a certficate for {host} and type {certificateType}");
     return(null);
 }
示例#12
0
        public JsonResult Edit(CertificateType model)
        {
            var apiResult = new APIResult();

            try
            {
                CertificateTypeBll.AddOrUpdate(model);
            }
            catch (Exception ex)
            {
                apiResult.Ret = -1;
                apiResult.Msg = ex.Message;
                if (!(ex is OperationExceptionFacade))
                {
                    LogFactory.GetLogger().Log(LogLevel.Error, ex);
                }
            }

            return(Json(apiResult));
        }
示例#13
0
        /// <summary>
        /// Get Service Enum
        /// </summary>
        /// <param name="type">Certificate</param>
        /// <returns>Trusted Certificate Request Service Enum</returns>
        public static TrustedCertificateReq.ServiceEnum GetServiceEnum(CertificateType type)
        {
            TrustedCertificateReq.ServiceEnum serviceEnum;
            switch (type)
            {
            case CertificateType.Bootstrap:
                serviceEnum = TrustedCertificateReq.ServiceEnum.Bootstrap;
                break;

            case CertificateType.Lwm2m:
                serviceEnum = TrustedCertificateReq.ServiceEnum.Lwm2m;
                break;

            default:
                serviceEnum = TrustedCertificateReq.ServiceEnum.Bootstrap;
                break;
            }

            return(serviceEnum);
        }
示例#14
0
        public Certificate(CertificateType type, string serialNumber, CertificateProfile issuedTo, CertificateCapability capability, DateTime issuedOnUTC, DateTime expiresOnUTC, AsymmetricEncryptionAlgorithm publicKeyEncryptionAlgorithm, string publicKeyXML)
        {
            if (issuedOnUTC > expiresOnUTC)
            {
                throw new CryptoException("Invalid issue or expiry date. Issue date is greater than expiry date.");
            }

            _version = 1;
            _type    = type;

            _serialNumber = serialNumber;
            _issuedTo     = issuedTo;
            _capability   = capability;

            _issuedOnUTC  = Convert.ToUInt64((issuedOnUTC - _epoch).TotalSeconds);
            _expiresOnUTC = Convert.ToUInt64((expiresOnUTC - _epoch).TotalSeconds);

            _publicKeyEncryptionAlgorithm = publicKeyEncryptionAlgorithm;
            _publicKeyXML = publicKeyXML;
        }
        public async Task <ActionResult> Shipments(Guid notificationId, CertificateType certificate)
        {
            var notificationType = await mediator.SendAsync(new GetNotificationType(notificationId));

            if (certificate == CertificateType.Receipt || certificate == CertificateType.ReceiptRecovery)
            {
                var receivedResult = await mediator.SendAsync(new GetSubmittedMovementsByNotificationId(notificationId));

                return(View(new ShipmentViewModel(notificationId, notificationType, certificate, receivedResult)));
            }

            if (certificate == CertificateType.Recovery)
            {
                var recoveryResult = await mediator.SendAsync(new GetReceivedMovements(notificationId));

                return(View(new ShipmentViewModel(notificationId, notificationType, certificate, recoveryResult)));
            }

            return(View());
        }
        public async Task <byte[]> RetrieveAsync(CertificateType persistenceType)
        {
            var certificate = await GetExistingCertificateAsync(persistenceType);

            if (certificate == null)
            {
                logger.LogInformation("Certificate of type {0} not found.", persistenceType);
                return(null);
            }

            var pfxBlob = certificate?.GetRawCertData();

            if (pfxBlob == null || pfxBlob.Length == 0)
            {
                logger.LogError("Certificate was found (thumbprint {0}), but PfxBlob was null or 0 length.", certificate.Thumbprint);
                return(null);
            }

            return(pfxBlob);
        }
示例#17
0
        /// <inheritdoc/>
        public string ToDelimitedString()
        {
            CultureInfo culture = CultureInfo.CurrentCulture;

            return(string.Format(
                       culture,
                       StringHelper.StringFormatSequence(0, 32, Configuration.FieldSeparator),
                       Id,
                       SetIdCer.HasValue ? SetIdCer.Value.ToString(culture) : null,
                       SerialNumber,
                       Version,
                       GrantingAuthority?.ToDelimitedString(),
                       IssuingAuthority?.ToDelimitedString(),
                       Signature?.ToDelimitedString(),
                       GrantingCountry,
                       GrantingStateProvince?.ToDelimitedString(),
                       GrantingCountyParish?.ToDelimitedString(),
                       CertificateType?.ToDelimitedString(),
                       CertificateDomain?.ToDelimitedString(),
                       SubjectId?.ToDelimitedString(),
                       SubjectName,
                       SubjectDirectoryAttributeExtension != null ? string.Join(Configuration.FieldRepeatSeparator, SubjectDirectoryAttributeExtension.Select(x => x.ToDelimitedString())) : null,
                       SubjectPublicKeyInfo?.ToDelimitedString(),
                       AuthorityKeyIdentifier?.ToDelimitedString(),
                       BasicConstraint,
                       CrlDistributionPoint != null ? string.Join(Configuration.FieldRepeatSeparator, CrlDistributionPoint.Select(x => x.ToDelimitedString())) : null,
                       JurisdictionCountry,
                       JurisdictionStateProvince?.ToDelimitedString(),
                       JurisdictionCountyParish?.ToDelimitedString(),
                       JurisdictionBreadth != null ? string.Join(Configuration.FieldRepeatSeparator, JurisdictionBreadth.Select(x => x.ToDelimitedString())) : null,
                       GrantingDate.HasValue ? GrantingDate.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null,
                       IssuingDate.HasValue ? IssuingDate.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null,
                       ActivationDate.HasValue ? ActivationDate.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null,
                       InactivationDate.HasValue ? InactivationDate.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null,
                       ExpirationDate.HasValue ? ExpirationDate.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null,
                       RenewalDate.HasValue ? RenewalDate.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null,
                       RevocationDate.HasValue ? RevocationDate.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null,
                       RevocationReasonCode?.ToDelimitedString(),
                       CertificateStatusCode?.ToDelimitedString()
                       ).TrimEnd(Configuration.FieldSeparator.ToCharArray()));
        }
示例#18
0
        /// <summary>
        /// Displays the certificate.
        /// </summary>
        /// <param name="certificate">The certificate.</param>
        public void DisplayCertificate(CertificateType certificate)
        {
            if (reader != null)
            {
                NativeMethods.SelectReader(reader.Index);
            }

            bool           result = false;
            EIDCertificate cert   = new EIDCertificate();

            switch (certificate)
            {
            case CertificateType.CaCertificate:
                result = NativeMethods.ReadCaCertificate(cert);
                break;

            case CertificateType.RootCaCertificate:
                result = NativeMethods.ReadRootCaCertificate(cert);
                break;

            case CertificateType.RrnCertificate:
                result = NativeMethods.ReadRrnCertificate(cert);
                break;

            case CertificateType.AuthenticationCertificate:
                result = NativeMethods.ReadAuthenticationCertificate(cert);
                break;

            case CertificateType.NonRepudiationCertificate:
                result = NativeMethods.ReadNonRepudiationCertificate(cert);
                break;

            default:
                break;
            }

            if (result)
            {
                NativeMethods.DisplayCertificate(cert);
            }
        }
        private static void GetChainStatusFlags(
            X509Certificate2 certificate,
            CertificateType certificateType,
            out X509ChainStatusFlags errorStatusFlags,
            out X509ChainStatusFlags warningStatusFlags)
        {
            if (certificate == null)
            {
                throw new ArgumentNullException(nameof(certificate));
            }

            warningStatusFlags = X509ChainStatusFlags.RevocationStatusUnknown | X509ChainStatusFlags.OfflineRevocation;

            if (certificateType == CertificateType.Signature && CertificateUtility.IsSelfIssued(certificate))
            {
                warningStatusFlags |= X509ChainStatusFlags.UntrustedRoot;
            }

            // Every status flag that isn't a warning is an error.
            errorStatusFlags = (~(X509ChainStatusFlags)0) & ~warningStatusFlags;
        }
示例#20
0
        public IActionResult UpdateEntry([FromBody] CertificateType objupd)
        {
            var targetObject = _context.CertificateType.FirstOrDefault(t => t.CertificateTypeID == objupd.CertificateTypeID);

            if (targetObject == null)
            {
                return(NotFound());
            }

            _context.Entry(targetObject).CurrentValues.SetValues(objupd);
            ReturnData ret;

            ret = _context.SaveData();

            if (ret.Message == "Success")
            {
                return(Ok());
            }

            return(NotFound(ret));
        }
示例#21
0
        private void OpenCertificateView(CertificateType type)
        {
            var listOfTableRow = CertificateList.FindElements(By.CssSelector("tr[data-id]"));

            foreach (var tableRow in listOfTableRow)
            {
                var td     = tableRow.FindElement(By.CssSelector("td[data-label='Code:'"));
                var a      = td.FindElement(By.TagName("a"));
                var imgSrc = a.GetAttribute("data-prefix");

                if (imgSrc.Contains(type.ToString()))
                {
                    a.Click();
                    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
                    wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(CreateNewCertificateButton));

                    CreateNewCertificateButton.Click();
                    break;
                }
            }
        }
示例#22
0
        public EcdsaCertificate(X509Certificate2 certificate, X509Certificate2Collection chain)
        {
            _certificate = certificate;
            _privateKey  = _certificate.GetECDsaPrivateKey();
            var curve = _privateKey.ExportParameters(false);

            if (curve.Curve.CurveType != System.Security.Cryptography.ECCurve.ECCurveType.Named)
            {
                ExceptionHelper.ThrowException(new InvalidOperationException());
            }
            switch (curve.Curve.Oid.FriendlyName)
            {
            case "nistP256":
                _certificateType          = CertificateType.Ecdsa_secp256r1;
                _supportedSignatureScheme = SignatureScheme.ecdsa_secp256r1_sha256;
                _hashType = HashType.SHA256;
                break;

            case "nistP384":
                _certificateType          = CertificateType.Ecdsa_secp384r1;
                _supportedSignatureScheme = SignatureScheme.ecdsa_secp384r1_sha384;
                _hashType = HashType.SHA384;
                break;

            case "nistP521":
                _certificateType          = CertificateType.Ecdsa_secp521r1;
                _supportedSignatureScheme = SignatureScheme.ecdsa_secp521r1_sha512;
                _hashType = HashType.SHA512;
                break;

            default:
                ExceptionHelper.ThrowException(new InvalidOperationException());
                break;
            }
            _certificateChain = new byte[chain.Count][];
            for (var i = 0; i < chain.Count; i++)
            {
                _certificateChain[i] = chain[i].RawData;
            }
        }
示例#23
0
        public void CertificateType()
        {
            IQueryable <CertificateType> CertificateTypeCollection = Enumerable.Empty <CertificateType>().AsQueryable();
            CertificateType ct = new CertificateType {
                CertificateTypeID = 1, CertificateTypeName = "Test CT"
            };

            Mock <ICertificateTypeRepository> CertificateTypeService = new Mock <ICertificateTypeRepository>();

            object obj = new object();

            try
            {
                CertificateTypeService.Setup(x => x.GetAll()).Returns(CertificateTypeCollection);
                CertificateTypeService.Setup(x => x.Get(It.IsAny <int>())).Returns(ct);
                CertificateTypeService.Setup(x => x.Add(It.IsAny <CertificateType>())).Returns(ct);
                CertificateTypeService.Setup(x => x.Delete(It.IsAny <CertificateType>())).Verifiable();
                CertificateTypeService.Setup(x => x.Update(It.IsAny <CertificateType>(), It.IsAny <object>())).Returns(ct);

                var CertificateTypeObject = CertificateTypeService.Object;
                var p1 = CertificateTypeObject.GetAll();
                var p2 = CertificateTypeObject.Get(1);
                var p3 = CertificateTypeObject.Update(ct, obj);
                var p4 = CertificateTypeObject.Add(ct);
                CertificateTypeObject.Delete(ct);

                Assert.IsAssignableFrom <IQueryable <CertificateType> >(p1);
                Assert.IsAssignableFrom <CertificateType>(p2);
                Assert.Equal("Test CT", p2.CertificateTypeName);
                Assert.Equal("Test CT", p3.CertificateTypeName);

                CertificateTypeService.VerifyAll();

                CertificateTypeObject.Dispose();
            }
            finally
            {
                CertificateTypeService = null;
            }
        }
示例#24
0
        public string UploadImageFileForBit()
        {
            int    _pictype = QueryString.IntSafeQ("pictype");
            string filename = QueryString.SafeQ("name");

            using (Stream filesStream = System.Web.HttpContext.Current.Request.InputStream)
            {
                CertificateType _certype = (CertificateType)_pictype;
                byte[]          bytes    = new byte[filesStream.Length];
                filesStream.Read(bytes, 0, bytes.Length);
                // 设置当前流的位置为流的开始
                filesStream.Seek(0, SeekOrigin.Begin);
                FtpUtil _ftp        = new FtpUtil();
                Random  _rd         = new Random();
                string  dicpath     = FilePath.PathCombine(ConfigCore.Instance.ConfigCommonEntity.FtpImagesSystemName, _certype.ToString(), memid.ToString(), DateTime.Now.ToString("yyyy"), DateTime.Now.ToString("MM"), DateTime.Now.ToString("dd"), _rd.Next(100000, 999999).ToString());
                string  dicpathfull = dicpath + filename.Substring(filename.LastIndexOf("."));
                string  certifapath = FilePath.PathCombine(ConfigCore.Instance.ConfigCommonEntity.FtpImagesRootPath, dicpathfull);
                _ftp.UploadFile(certifapath, bytes, true);
                return("{\"jsonrpc\" : \"2.0\", \"result\" : null, \"pic_raw\" : \"" + dicpathfull + "\"}");
            }

            return("");
        }
示例#25
0
 public GXCertifigateGenerationForm(string address, GXPkcs10 pkc10, CertificateType type, byte[] systemTitle)
 {
     InitializeComponent();
     _address           = address;
     SystemTitleTb.Text = GXDLMSTranslator.ToHex(systemTitle, false);
     LoadBtn.Enabled    = CSRBtn.Enabled = false;
     Pkcs10Tb.Text      = pkc10.ToPem();
     Pkcs10Tb.AppendText(Environment.NewLine);
     Pkcs10Tb.AppendText(pkc10.ToString());
     if (type == CertificateType.DigitalSignature)
     {
         DigitalSignatureCb.Checked = true;
     }
     else if (type == CertificateType.KeyAgreement)
     {
         KeyAgreementCb.Checked = true;
     }
     else
     {
         ServerTlsCb.Checked = true;
     }
     ServerTlsCb.Enabled = KeyAgreementCb.Enabled = DigitalSignatureCb.Enabled = false;
 }
示例#26
0
        private ExistingCertListPage SelectTypeFromDropdownListOfTypes(CertificateType dPN18C)
        {
            CertificateTypeDropdown.Click();
            var  listOfOptions      = CertificateTypeDropdown.FindElements(By.TagName("option"));
            bool isCertificateFound = false;

            foreach (var option in listOfOptions)
            {
                if (option.Text.Contains(dPN18C.ToString()))
                {
                    isCertificateFound = true;
                    option.Click();
                    break;
                }
            }

            if (!isCertificateFound)
            {
                throw new Exception("Certificate type now found.");
            }

            return(this);
        }
        private async Task <X509Certificate2> GetExistingCertificateAsync(CertificateType persistenceType)
        {
            var azureCert = await GetExistingAzureCertificateAsync(persistenceType);

            if (azureCert == null)
            {
                return(null);
            }

            var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            certStore.Open(OpenFlags.ReadOnly);

            try
            {
                var certCollection = certStore.Certificates.Find(
                    X509FindType.FindByThumbprint,
                    // Replace below with your certificate's thumbprint
                    azureCert.Thumbprint,
                    false);

                // Get the first cert with the thumbprint
                if (certCollection.Count > 0)
                {
                    var cert = certCollection[0];
                    return(cert);
                }
            }
            finally
            {
                certStore.Close();
            }

            logger.LogInformation("Could not find existing Azure certificate.");

            return(null);
        }
示例#28
0
 public static async void AddCertificates(string fileName, int TokenIndex)
 {
     //InitializeAddCertificateOperation();
     try
     {
         CertificateType certType           = GetCertificateType(fileName);
         byte[]          certificateRawData = GetCertificateRawData(fileName);
         await AddCertificatesToToken(certType, certificateRawData, TokenIndex);
     }
     catch (ManagedCertificateInvalidKeySizeException)
     {
         //SetExceptionMessage(GetResourceString("Text_Exception_CertificateKeysInvalid"));
     }
     catch (ManagedModuleInactiveException)
     {
         //SetExceptionMessage(GetResourceString("Text_Exception_ModuleInactive"));
     }
     catch (ManagedModuleMemoryFullException mex)
     {
         Console.WriteLine(mex);
         //SetExceptionMessage(GetResourceString("Text_Exception_MemoryFull"));
     }
     catch (ManagedModuleDeviceProblemException)
     {
         //SetExceptionMessage(GetResourceString("Text_Exception_DeviceError"));
     }
     catch (ManagedModuleException ex5)
     {
         //SetExceptionMessage(string.Format(GetResourceString("Format_Exception_ErrorCode"), ex5.ErrorCode));
     }
     catch (CryptographicException e)
     {
         //SetExceptionMessage(ParseAddCertificateError(e));
     }
     //FinalizeAddCertificateOperation();
     //await ShowErrorMessageBox(GetResourceString("Text_Error_Certificate_Import_Failed"));
 }
示例#29
0
        public async Task <ActionResult <CertificateTypeViewModel> > RemoveCertificateTypeAsync(
            Guid id)
        {
            if (id == Guid.Empty)
            {
                return(BadRequest("No valid id."));
            }

            try
            {
                CertificateType oldCertificateType = (await certificateService.GetCertificateTypeAsync(id)).Data;
                if (oldCertificateType == null)
                {
                    return(NotFound("CertificateType not found"));
                }

                TaskResult <CertificateType>
                result = await certificateService.RemoveCertificateTypeAsync(oldCertificateType);

                if (!result.Succeeded)
                {
                    return(UnprocessableEntity(new ErrorViewModel {
                        Type = Type.Error, Message = result.Message
                    }));
                }
                return(Ok(CertificateTypeViewModel.CreateVm(result.Data)));
            }
            catch (Exception ex)
            {
                string message = GetType().Name + "Error in " + nameof(RemoveCertificateTypeAsync);
                logger.LogError(ex, message);
                return(UnprocessableEntity(new ErrorViewModel {
                    Type = Type.Error, Message = message
                }));
            }
        }
        internal static void SetCertBuildChainPolicy(
            X509ChainPolicy policy,
            X509Certificate2Collection additionalCertificates,
            DateTime verificationTime,
            CertificateType certificateType)
        {
            if (certificateType == CertificateType.Timestamp)
            {
                policy.ApplicationPolicy.Add(new Oid(Oids.TimeStampingEku));
            }
            else
            {
                policy.ApplicationPolicy.Add(new Oid(Oids.CodeSigningEku));
            }

            policy.ExtraStore.AddRange(additionalCertificates);

            policy.RevocationFlag = X509RevocationFlag.ExcludeRoot;

            if (certificateType != CertificateType.Timestamp)
            {
                policy.VerificationTime = verificationTime;
            }
        }
示例#31
0
        internal static Pkcs12Store LoadPkcs12Store(string basename, string password, CertificateType certtype)
        {
            string privateOutputPath = null;

            if (certtype == CertificateType.AuthorityCertificate)
            {
                privateOutputPath = AuthorityPrivateCertificatesPath;
            }
            else if (certtype == CertificateType.ServerCertificate)
            {
                privateOutputPath = ServerPrivateCertificatesPath;
            }
            else
            {
                privateOutputPath = UserPrivateCertificatesPath;
            }

            var store = new Pkcs12Store();

            using (Stream stream = new FileStream(
                       privateOutputPath + basename + ".p12",
                       FileMode.Open,
                       FileAccess.Read)) {
                try
                {
                    store.Load(stream, password.ToCharArray());
                }
                catch (System.Exception)
                {
                    store = null;
                }

                stream.Close();
            }

            return(store);
        }
示例#32
0
 public bool IsOfType(CertificateType type)
 {
     return type.IsOfType(this.certificate);
 }
示例#33
0
 public static bool CertificateAvailable(string basename, CertificateType certtype, StoreFormat format)
 {
     return(File.Exists(CertificatePath(basename, certtype, format)));
 }
示例#34
0
        public static X509Certificate2 IssueCertificate(
            string basename,
            string password,
            DistinguishedName dn,
            CertificateType certtype,
            DateTime notBefore,
            DateTime notAfter)
        {
            var certificateGenerator = new X509V3CertificateGenerator();
            var privateOutputPath    = "";
            var publicOutputPath     = "";

            /* Prepare output directories  */
            if (certtype == CertificateType.AuthorityCertificate)
            {
                privateOutputPath = AuthorityPrivateCertificatesPath;
                publicOutputPath  = AuthorityPublicCertificatesPath;
            }
            else if (certtype == CertificateType.ServerCertificate)
            {
                privateOutputPath = ServerPrivateCertificatesPath;
                publicOutputPath  = ServerPublicCertificatesPath;
            }
            else
            {
                privateOutputPath = UserPrivateCertificatesPath;
                publicOutputPath  = UserPublicCertificatesPath;
            }

            /* Certificate Asymmetric Keys */
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);

            AsymmetricCipherKeyPair subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            /* Certificate Serial Number */
            BigInteger serialNumber =
                BigIntegers.CreateRandomInRange(
                    BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            /* Certificate Date Constrains */
            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            /* Certificate Issuer and Subject DN */
            string issuerName = IssuerDN.ToString();

            if (certtype == CertificateType.AuthorityCertificate)
            {
                /* A Certification Authority is a self signed certificate */
                issuerName = dn.ToString();
            }

            certificateGenerator.SetSubjectDN(new X509Name(dn.ToString()));
            certificateGenerator.SetIssuerDN(new X509Name(issuerName));

            /* Certificate Alternative Names */
            if (dn.AlternativeNames != null && dn.AlternativeNames.Any())
            {
                var subjectAlternativeNamesExtension =
                    new DerSequence(
                        dn.AlternativeNames.Select(name => new GeneralName(GeneralName.DnsName, name))
                        .ToArray <Asn1Encodable> ());

                certificateGenerator.AddExtension(
                    X509Extensions.SubjectAlternativeName.Id, false, subjectAlternativeNamesExtension);
            }

            /* Certificate Keys Usage  */
            var keyUsageFlags = KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment |
                                KeyUsage.DataEncipherment | KeyUsage.DigitalSignature;

            if (certtype == CertificateType.AuthorityCertificate || certtype == CertificateType.ServerCertificate)
            {
                keyUsageFlags |= KeyUsage.CrlSign | KeyUsage.NonRepudiation;
            }

            certificateGenerator.AddExtension(
                X509Extensions.KeyUsage.Id, false, new KeyUsage(keyUsageFlags));

            /* Certificate Extended Key Usages */
            if (certtype != CertificateType.AuthorityCertificate)
            {
                KeyPurposeID[] extendedUsages = null;

                if (certtype == CertificateType.ServerCertificate)
                {
                    extendedUsages = new KeyPurposeID[] {
                        KeyPurposeID.IdKPServerAuth,
                    };
                }
                else
                {
                    extendedUsages = new KeyPurposeID[] {
                        KeyPurposeID.IdKPClientAuth,
                        KeyPurposeID.IdKPEmailProtection,
                    };
                }

                certificateGenerator.AddExtension(
                    X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(extendedUsages));
            }

            /* Certificate Authority Key Identifier */
            /* A Certification Authority is a self signed certificate */
            AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;;

            if (certtype != CertificateType.AuthorityCertificate)
            {
                issuerKeyPair = DotNetUtilities.GetKeyPair(IssuerCertificate.PrivateKey);
            }

            var issuerPKIFactory = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKeyPair.Public);
            var generalNames     = new GeneralNames(
                new GeneralName(new X509Name(issuerName)));

            /* A Certification Authority is a self signed certificate */
            BigInteger issuerSerialNumber = serialNumber;

            if (certtype != CertificateType.AuthorityCertificate)
            {
                issuerSerialNumber = new BigInteger(IssuerCertificate.GetSerialNumber());
            }

            var authorityKIExtension =
                new AuthorityKeyIdentifier(
                    issuerPKIFactory, generalNames, issuerSerialNumber);

            certificateGenerator.AddExtension(
                X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKIExtension);

            /* Certificate Subject Key Identifier */
            var subjectPKIFactory  = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public);
            var subjectKIExtension = new SubjectKeyIdentifier(subjectPKIFactory);

            certificateGenerator.AddExtension(
                X509Extensions.SubjectKeyIdentifier.Id, false, subjectKIExtension);

            /* Certificate Basic constrains */
            bool isCertificateAuthority = false;

            if (certtype == CertificateType.AuthorityCertificate)
            {
                isCertificateAuthority = true;
            }

            var basicConstrains = new BasicConstraints(isCertificateAuthority);

            certificateGenerator.AddExtension(
                X509Extensions.BasicConstraints.Id, true, basicConstrains);

            /* Generate BouncyCastle Certificate */
            ISignatureFactory signatureFactory = new Asn1SignatureFactory(
                "SHA512WITHRSA",
                issuerKeyPair.Private,
                random
                );

            /* Generate P12 Certificate Store and write to disk*/
            var store = new Pkcs12Store();

            var certificate      = certificateGenerator.Generate(signatureFactory);
            var certificateEntry = new X509CertificateEntry(certificate);
            var stream           = new MemoryStream();

            store.SetCertificateEntry(dn.ToString(), certificateEntry);
            store.SetKeyEntry(dn.ToString(), new AsymmetricKeyEntry(subjectKeyPair.Private), new [] { certificateEntry });
            store.Save(stream, password.ToCharArray(), random);

            File.WriteAllBytes(privateOutputPath + basename + ".p12", stream.ToArray());

            /* Convert to Microsoft X509Certificate2 and write to disk pfx and der files */
            var convertedCertificate =
                new X509Certificate2(stream.ToArray(),
                                     password,
                                     X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            File.WriteAllBytes(privateOutputPath + basename + ".pfx", convertedCertificate.Export(X509ContentType.Pfx, password));
            File.WriteAllBytes(publicOutputPath + basename + ".crt", convertedCertificate.Export(X509ContentType.Cert, password));

            return(convertedCertificate);
        }
示例#35
0
        public static X509Certificate2 LoadCertificate(string basename, string password, CertificateType certtype, StoreFormat format)
        {
            string filename          = "";
            string privateOutputPath = null;
            string publicOutputPath  = null;

            if (certtype == CertificateType.AuthorityCertificate)
            {
                privateOutputPath = AuthorityPrivateCertificatesPath;
                publicOutputPath  = AuthorityPublicCertificatesPath;
            }
            else if (certtype == CertificateType.ServerCertificate)
            {
                privateOutputPath = ServerPrivateCertificatesPath;
                publicOutputPath  = ServerPublicCertificatesPath;
            }
            else
            {
                privateOutputPath = UserPrivateCertificatesPath;
                publicOutputPath  = UserPublicCertificatesPath;
            }

            switch (format)
            {
            case StoreFormat.CRT:
                filename = publicOutputPath + basename + ".crt";
                break;

            case StoreFormat.P12Store:
                filename = privateOutputPath + basename + ".p12";
                break;

            case StoreFormat.PFX:
                filename = privateOutputPath + basename + ".pfx";
                break;

            default:
                throw new NotImplementedException();
            }

            return(new X509Certificate2(filename, password, X509KeyStorageFlags.Exportable));
        }
示例#36
0
 /// <summary>
 /// Reads data into this RR from the DNS wire format data in <paramref name="reader"/>
 /// </summary>
 /// <param name="reader">Reader in which wire format data for this RR is already buffered.</param>
 protected override void DeserializeRecordData(ref DnsBufferReader reader)
 {
     ushort certType = reader.ReadUShort();
     if (certType > (ushort) CertificateType.IACPKIK)
     {
         throw new DnsProtocolException(DnsProtocolError.InvalidCertRecord);
     } 
     m_certType = (CertificateType) certType;
     m_keyTag = reader.ReadUShort();
     m_algorithm = reader.ReadByte();
     m_certData = reader.ReadBytes(this.RecordDataLength - 5); // 5 == # of bytes we've already read (certType, keytag etc)
     
     this.EnsureDnsCert();            
 }
示例#37
0
 private string GetCertificatePath(CertificateType persistenceType)
 {
     return(relativeFilePath + "_" + persistenceType.ToString());
 }
示例#38
0
 /// <summary>
 ///  Ask Server sends the Certificate Signing Request (CSR) data.
 /// </summary>
 /// <param name="client">DLMS client that is used to generate action.</param>
 /// <param name="type">identifies the key pair for which the certificate will be requested.</param>
 /// <returns>Generated action.</returns>
 public byte[][] GenerateCertificate(GXDLMSClient client, CertificateType type)
 {
     return client.Method(this, 5, type, DataType.Enum);
 }
示例#39
0
 /// <summary>
 /// Removes X.509 v3 certificate from the server using entity.
 /// </summary>
 /// <param name="client">DLMS client that is used to generate action.</param>
 /// <param name="entity">Certificate entity type.</param>
 /// <param name="type">Certificate type.</param>
 /// <param name="systemTitle">System title.</param>
 /// <returns>Generated action.</returns>
 public byte[][] RemoveCertificateByEntity(GXDLMSClient client, CertificateEntity entity, CertificateType type, byte[] systemTitle)
 {
     GXByteBuffer bb = new GXByteBuffer();
     bb.SetUInt8(DataType.Structure);
     bb.SetUInt8(2);
     //Add enum
     bb.SetUInt8(DataType.Enum);
     bb.SetUInt8(0);
     //Add certificate_identification_by_entity
     bb.SetUInt8(DataType.Structure);
     bb.SetUInt8(3);
     //Add certificate_entity
     bb.SetUInt8(DataType.Enum);
     bb.SetUInt8(entity);
     //Add certificate_type
     bb.SetUInt8(DataType.Enum);
     bb.SetUInt8(type);
     //system_title
     GXCommon.SetData(client.Settings, bb, DataType.OctetString, systemTitle);
     return client.Method(this, 8, bb.Array(), DataType.OctetString);
 }
示例#40
0
 public GenericCertificate(byte[] pkc)
 {
   if (pkc == null)
     throw new ArgumentNullException("GenericCert: pkc null!");
   type = CertificateType.X509; // the default in RELOAD
   certificate = (byte[])pkc.Clone();
 }