Example #1
0
        public static bool IsValidated(out string errorMessage)
        {
            Company currentCompany = ((EInvoiceContext)FXContext.Current).CurrentCompany;

            errorMessage = null;
            try
            {
                ICertificateService _certSrv  = IoC.Resolve <ICertificateService>();
                KeyStores           _keyStore = KeyStoresManagement.GetKeyStore(currentCompany.id);
                if (_keyStore == null)
                {
                    errorMessage = "Chưa đăng ký chữ ký số, liên hệ nhà cung cấp để được hỗ trợ.";
                    return(false);
                }
                if (_keyStore.KeyStoresOf == 1)
                {
                    return(true);
                }
                System.Security.Cryptography.X509Certificates.X509Certificate2 cert = _keyStore.OpenSession();
                if (DateTime.Parse(cert.GetExpirationDateString()) <= DateTime.Today.AddDays(7))
                {
                    errorMessage = "Chữ ký số sắp hết hạn, liên hệ nhà cung cấp để được hỗ trợ.";
                    return(false);
                }
                return(true);
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return(true);
            }
        }
Example #2
0
        public ActionResult Details(string id)
        {
            Guid publicKey;

            if (!Guid.TryParse(id, out publicKey))
            {
                return(new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest));
            }

            var certificado = DBContext.Certificados.Where(e => e.PublicKey == publicKey).SingleOrDefault();

            if (certificado == null)
            {
                return(HttpNotFound());
            }


            System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            //System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificado.PFXArchivo,
            //     certificado.PFXContrasena, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.MachineKeySet);
            //// System.Security.Cryptography.RSACryptoServiceProvider rsaCryptoIPT = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey;
            System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificado.PFXArchivo,
                                                                                                                                                     certificado.PFXContrasena, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.MachineKeySet);
            System.Security.Cryptography.RSACryptoServiceProvider rsaCryptoIPT = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey;



            //System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
            //byte[] binData = encoder.GetBytes(cadenaOriginal);
            //byte[] binSignature = rsaCryptoIPT.SignData(binData, sha1);
            //string sello = Convert.ToBase64String(binSignature);
            //return sello;


            var model = new CertificadoDetailsViewModel(certificado);

            //model.Issuer = cert.Issuer;
            model.Issuer  = cert.IssuerName.Name;
            model.Subject = cert.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, false);



            model.Issuer = cert.GetEffectiveDateString();
            model.Issuer = cert.GetExpirationDateString();
            model.Issuer = cert.Subject;
            model.Issuer = certificado.GetNumeroSerie(); //  cert.SerialNumber; // cert.GetSerialNumberString();
            model.Issuer = cert.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, true);
            //model.Issuer = cert.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, false);
            return(View(model));
        }
        public ActionResult Create(CertificadoCreateViewModel model) {
            //var model = new CertificadoCreateViewModel();
           if (ModelState.IsValid) {
               if (model.CertificadoArchivo == null || model.CertificadoArchivo.ContentLength == 0) {
                    return View();
                }
                try {
                    // var user = UserManager.FindById(this.GetUserId());
                    Guid publicKey = Guid.NewGuid();
                    Certificado certificado = new Certificado();
                    //certificado.NumSerie = model.NumSerie;
                    //certificado.RFC = model.RFC;
                    //certificado.Inicia = model.Inicia; // DateTime.Parse(post["inicia"].ToString(), new System.Globalization.CultureInfo("es-MX"));
                    //certificado.Finaliza = model.Finaliza;
                    ////certificado.CertificadoBase64 = model.CertificadoArchivo;
                    ////certificado.PFXArchivo = model.PFXArchivo;

                    certificado.PFXContrasena = model.PFXContrasena;
                    certificado.Estado = model.Estado;

                    if (model.CertificadoArchivo != null) {
                        MemoryStream target = new MemoryStream();
                        model.CertificadoArchivo.InputStream.CopyTo(target);
                        Byte[] data = target.ToArray();
                        certificado.CertificadoDER = data;
                        //certificado.PFXArchivo = data;
                        certificado.CertificadoBase64 = Convert.ToBase64String(data);

                        System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
                        //System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(data, certificado.PFXContrasena);
                        System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(data);
                        // cert.FriendlyName.ToString();

                        certificado.NumSerie = Certificado.GetSerialNumberString(cert);
                        
                        //certificado.RFC = cert.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, false);
                        string[] subject = cert.Subject.Split(',');
                        foreach (string strVal in subject) {
                            string value = strVal.Trim();
                            if (value.StartsWith("OID.2.5.4.45=")) {
                                string value2 = value.Replace("OID.2.5.4.45=", "");
                                certificado.RFC = value2.Substring(0, value2.IndexOf('/') >= 0 ? value2.IndexOf('/') : value2.Length).Trim();
                            }
                        }

                        certificado.Inicia = DateTime.Parse(cert.GetEffectiveDateString());
                        certificado.Finaliza = DateTime.Parse(cert.GetExpirationDateString());
                        //certificado.CertificadoBase64 = model.CertificadoArchivo;
                        //certificado.PFXArchivo = model.PFXArchivo;

                    }

                    if (model.PFXArchivo != null) {
                        MemoryStream target2 = new MemoryStream();
                        model.PFXArchivo.InputStream.CopyTo(target2);
                        Byte[] dataPFX = target2.ToArray();
                        certificado.PFXArchivo = dataPFX;



                    //    MemoryStream target3 = new MemoryStream();
                    //    model.CertificadoArchivo.InputStream.Position = 0;
                    //    model.CertificadoArchivo.InputStream.CopyTo(target3);
                    //    Byte[] data3 = target3.ToArray();
                    //    //string certificadoBase64 = Convert.ToBase64String(data);

                        
                    //    //System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificado.PFXArchivo,
                    //    //     certificado.PFXContrasena, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.MachineKeySet);
                    //    //System.Security.Cryptography.RSACryptoServiceProvider rsaCryptoIPT = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey;




                    }
                    //else {
                    //    MemoryStream target3 = new MemoryStream();
                    //    model.CertificadoArchivo.InputStream.CopyTo(target3);
                    //    Byte[] data3 = target3.ToArray();
                    //    //string certificadoBase64 = Convert.ToBase64String(data);

                    //    System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
                    //    System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(data3, certificado.PFXContrasena);
                    //    cert.FriendlyName.ToString();
                    //    //System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificado.PFXArchivo,
                    //    //     certificado.PFXContrasena, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.MachineKeySet);
                    //    System.Security.Cryptography.RSACryptoServiceProvider rsaCryptoIPT = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey;


                    //}

                    if (model.PrivateKeyDER != null) {
                        MemoryStream ms = new MemoryStream();
                        model.PrivateKeyDER.InputStream.CopyTo(ms);
                        Byte[] dataDER = ms.ToArray();
                        certificado.PrivateKeyDER = dataDER;
                    }
                    certificado.PrivateKeyContrasena = model.PrivateKeyContrasena;

                    this.DBContext.Certificados.Add(certificado);
                    this.DBContext.SaveChanges();
                }
                catch (Exception ex) {
                    //log.Error(ex, "Error upload photo blob to storage");
                    ex.ToString();
                }
            }
            return RedirectToAction("Index", "Home");
        }
        public ActionResult Details(string id) {
            Guid publicKey;
            if (!Guid.TryParse(id, out publicKey))
                return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest);

            var certificado = DBContext.Certificados.Where(e => e.PublicKey == publicKey).SingleOrDefault();

            if (certificado == null)
                return HttpNotFound();


            System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            //System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificado.PFXArchivo,
            //     certificado.PFXContrasena, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.MachineKeySet);
            //// System.Security.Cryptography.RSACryptoServiceProvider rsaCryptoIPT = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey;
            System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificado.PFXArchivo,
                 certificado.PFXContrasena, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.MachineKeySet);
            System.Security.Cryptography.RSACryptoServiceProvider rsaCryptoIPT = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey;

             

            //System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
            //byte[] binData = encoder.GetBytes(cadenaOriginal);
            //byte[] binSignature = rsaCryptoIPT.SignData(binData, sha1);
            //string sello = Convert.ToBase64String(binSignature);
            //return sello;


            var model = new CertificadoDetailsViewModel(certificado);
            //model.Issuer = cert.Issuer;
            model.Issuer = cert.IssuerName.Name;
            model.Subject = cert.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, false);

           

            model.Issuer = cert.GetEffectiveDateString();
            model.Issuer = cert.GetExpirationDateString();
            model.Issuer = cert.Subject;
            model.Issuer = certificado.GetNumeroSerie(); //  cert.SerialNumber; // cert.GetSerialNumberString();
            model.Issuer = cert.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, true);
            //model.Issuer = cert.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, false);
            return View(model);
        }            
Example #5
0
        public async Task Start(CancellationToken ct)
        {
            try
            {
                AddConsoleLogger();

                logger.LogDebug("WebRTCDaemon starting.");

                var wssCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(_webSocketCertificatePath, _webSocketCertificatePassword);
                logger.LogDebug("Web Socket Server Certificate: " + wssCertificate.Subject + ", have key " + wssCertificate.HasPrivateKey + ", Expires " + wssCertificate.GetExpirationDateString() + ".");
                logger.LogDebug($"DTLS certificate thumbprint {_dtlsCertificateThumbprint}.");
                logger.LogDebug($"Web socket port {_webSocketPort}.");

                if (!File.Exists(_mediaFilePath))
                {
                    throw new ApplicationException($"The media file at does not exist at {_mediaFilePath}.");
                }

                // Initialise OpenSSL & libsrtp, saves a couple of seconds for the first client connection.
                Console.WriteLine("Initialising OpenSSL and libsrtp...");
                DtlsHandshake.InitialiseOpenSSL();
                Srtp.InitialiseLibSrtp();

                Task.Run(DoDtlsHandshakeLoopbackTest).Wait();

                Console.WriteLine("Test DTLS handshake complete.");

                // Configure the web socket and the different end point handlers.
                int webSocketPort = (!String.IsNullOrEmpty(_webSocketPort)) ? Int32.Parse(_webSocketPort) : DEFAULT_WEB_SOCKET_PORT;
                _webSocketServer = new WebSocketServer(IPAddress.Any, webSocketPort, true);
                _webSocketServer.SslConfiguration.ServerCertificate          = wssCertificate;
                _webSocketServer.SslConfiguration.CheckCertificateRevocation = false;

                // Standard encrypted WebRtc stream.
                _webSocketServer.AddWebSocketService <SDPExchange>("/max", (sdpReceiver) =>
                {
                    sdpReceiver.MediaSource        = MediaSourceEnum.Max;
                    sdpReceiver.WebSocketOpened   += WebRtcStartCall;
                    sdpReceiver.SDPAnswerReceived += WebRtcAnswerReceived;
                });

                if (!String.IsNullOrEmpty(_testPatternImagePath) && File.Exists(_testPatternImagePath))
                {
                    _webSocketServer.AddWebSocketService <SDPExchange>("/testpattern", (sdpReceiver) =>
                    {
                        sdpReceiver.MediaSource        = MediaSourceEnum.TestPattern;
                        sdpReceiver.WebSocketOpened   += WebRtcStartCall;
                        sdpReceiver.SDPAnswerReceived += WebRtcAnswerReceived;
                    });
                }

                _webSocketServer.Start();

                Console.WriteLine($"Waiting for browser web socket connection to {_webSocketServer.Address}:{_webSocketServer.Port}...");

                // Initialise the Media Foundation library that will pull the samples from the mp4 file.
                _mediaSource = new MediaSource();
                _mediaSource.Init(_mediaFilePath, true);

                _ = Task.Run(ExpireConnections);

                while (!ct.IsCancellationRequested)
                {
                    await Task.Delay(1000);
                }
            }
            catch (Exception excp)
            {
                logger.LogError("Exception WebRTCDaemon.Start. " + excp);
            }
            finally
            {
                Stop();
            }
        }
Example #6
0
        public void Start()
        {
            try
            {
                logger.Debug("WebRTCDaemon starting.");

                SDPExchangeReceiver.WebSocketOpened   += WebRtcStartCall;
                SDPExchangeReceiver.SDPAnswerReceived += WebRtcAnswerReceived;

                var wssCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(_webSocketCertificatePath, _webSocketCertificatePassword);
                logger.Debug("Web Socket Server Certificate CN: " + wssCertificate.Subject + ", have key " + wssCertificate.HasPrivateKey + ", Expires " + wssCertificate.GetExpirationDateString() + ".");

                _receiverWSS = new WebSocketServer(8081, true);
                //_receiverWSS.Log.Level = LogLevel.Debug;
                _receiverWSS.SslConfiguration = new WebSocketSharp.Net.ServerSslConfiguration(wssCertificate, false,
                                                                                              System.Security.Authentication.SslProtocols.Tls,
                                                                                              false);

                _receiverWSS.AddWebSocketService <SDPExchangeReceiver>("/stream",
                                                                       () => new SDPExchangeReceiver()
                {
                    IgnoreExtensions = true,
                });
                _receiverWSS.Start();

                ThreadPool.QueueUserWorkItem(delegate { SendTestPattern(); });
            }
            catch (Exception excp)
            {
                logger.Error("Exception WebRTCDaemon.Start. " + excp);
            }
        }
Example #7
0
        /// <summary>
        /// Once validation has completed for our requested domains we can complete the certificate
        /// request by submitting a Certificate Signing Request (CSR) to the CA
        /// </summary>
        /// <param name="log">  </param>
        /// <param name="primaryDnsIdentifier">  </param>
        /// <param name="alternativeDnsIdentifiers">  </param>
        /// <param name="config">  </param>
        /// <returns>  </returns>
        public async Task <ProcessStepResult> CompleteCertificateRequest(ILog log, CertRequestConfig config, string orderId)
        {
            var orderContext = _currentOrders[orderId];

            // check order status, if it's not 'ready' then try a few more times before giving up
            var order = await orderContext.Resource();

            var attempts = 5;

            while (attempts > 0 && (order?.Status != OrderStatus.Ready && order?.Status != OrderStatus.Valid))
            {
                await Task.Delay(2000);

                order = await orderContext.Resource();

                attempts--;
            }

            if (order?.Status != OrderStatus.Ready && order?.Status != OrderStatus.Valid)
            {
                return(new ProcessStepResult {
                    IsSuccess = false, ErrorMessage = "Certificate Request did not complete. Order did not reach Ready status in the time allowed.", Result = order
                });
            }

            // generate temp keypair for signing CSR
            var keyAlg = KeyAlgorithm.RS256;

            if (!string.IsNullOrEmpty(config.CSRKeyAlg))
            {
                if (config.CSRKeyAlg == "RS256")
                {
                    keyAlg = KeyAlgorithm.RS256;
                }

                if (config.CSRKeyAlg == "ECDSA256")
                {
                    keyAlg = KeyAlgorithm.ES256;
                }

                if (config.CSRKeyAlg == "ECDSA384")
                {
                    keyAlg = KeyAlgorithm.ES384;
                }

                if (config.CSRKeyAlg == "ECDSA521")
                {
                    keyAlg = KeyAlgorithm.ES512;
                }
            }

            var csrKey = KeyFactory.NewKey(keyAlg);

            var certFriendlyName = $"{config.PrimaryDomain} [Certify] ";

            // generate cert
            CertificateChain certificateChain = null;
            DateTime?        certExpiration   = null;

            try
            {
                if (order.Status == OrderStatus.Valid)
                {
                    // download existing cert, TODO: need to re-use key from time of last finalize
                    certificateChain = await orderContext.Download();
                }
                else
                {
                    // finalise and download
                    certificateChain = await orderContext.Generate(new CsrInfo
                    {
                        CommonName = _idnMapping.GetAscii(config.PrimaryDomain)
                    }, csrKey);
                }


                var cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificateChain.Certificate.ToDer());
                certExpiration    = cert.NotAfter;
                certFriendlyName += $"{cert.GetEffectiveDateString()} to {cert.GetExpirationDateString()}";
            }
            catch (AcmeRequestException exp)
            {
                var msg = $"Failed to finalize certificate order:  {exp.Error?.Detail}";
                log.Error(msg);

                return(new ProcessStepResult {
                    ErrorMessage = msg, IsSuccess = false, Result = exp.Error
                });
            }

            // file will be named as {expiration yyyyMMdd}_{guid} e.g. 20290301_4fd1b2ea-7b6e-4dca-b5d9-e0e7254e568b
            var certId = certExpiration.Value.ToString("yyyyMMdd") + "_" + Guid.NewGuid().ToString().Substring(0, 8);

            var domainAsPath = config.PrimaryDomain.Replace("*", "_");

            var pfxPath = ExportFullCertPFX(certFriendlyName, csrKey, certificateChain, certId, domainAsPath);

            return(new ProcessStepResult {
                IsSuccess = true, Result = pfxPath
            });
        }
Example #8
0
        public void Start()
        {
            try
            {
                Console.WriteLine("This application includes software developed by the OpenSSL Project and cryptographic software written by Eric Young ([email protected]).");

                logger.Debug("WebRTCDaemon starting.");

                var wssCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(_webSocketCertificatePath, _webSocketCertificatePassword);
                logger.Debug("Web Socket Server Certificate: " + wssCertificate.Subject + ", have key " + wssCertificate.HasPrivateKey + ", Expires " + wssCertificate.GetExpirationDateString() + ".");
                logger.Debug($"DTLS certificate thumbprint {_dtlsCertificateThumbprint}.");
                logger.Debug($"Web socket port {_webSocketPort}.");

                if (!File.Exists(_mediaFilePath))
                {
                    throw new ApplicationException($"The media file at does not exist at {_mediaFilePath}.");
                }

                IPAddress rtpIPAddress = null;
                if (String.IsNullOrEmpty(_localRtpIPAddress) == false)
                {
                    rtpIPAddress = IPAddress.Parse(_localRtpIPAddress);
                }

                // Configure the web socket and the different end point handlers.
                int webSocketPort = (!String.IsNullOrEmpty(_webSocketPort)) ? Int32.Parse(_webSocketPort) : DEFAULT_WEB_SOCKET_PORT;
                _webSocketServer = new WebSocketServer(webSocketPort, true);
                _webSocketServer.SslConfiguration = new WebSocketSharp.Net.ServerSslConfiguration(wssCertificate, false, System.Security.Authentication.SslProtocols.Default, false);
                _webSocketServer.Log.Level        = LogLevel.Debug;

                // Standard encrypted WebRtc stream.
                _webSocketServer.AddWebSocketService <SDPExchange>("/max", () =>
                {
                    SDPExchange sdpReceiver = new SDPExchange(MediaSourceEnum.Max, false, rtpIPAddress)
                    {
                        IgnoreExtensions = true
                    };
                    sdpReceiver.WebSocketOpened   += WebRtcStartCall;
                    sdpReceiver.SDPAnswerReceived += WebRtcAnswerReceived;
                    return(sdpReceiver);
                });

                // Decrypted WebRtc stream for diagnostics (browsers do not support this without specific flags being enabled).
                _webSocketServer.AddWebSocketService <SDPExchange>("/maxnocry", () =>
                {
                    SDPExchange sdpReceiver = new SDPExchange(MediaSourceEnum.Max, true, rtpIPAddress)
                    {
                        IgnoreExtensions = true
                    };
                    sdpReceiver.WebSocketOpened   += WebRtcStartCall;
                    sdpReceiver.SDPAnswerReceived += WebRtcAnswerReceived;
                    return(sdpReceiver);
                });

                if (!String.IsNullOrEmpty(_testPattermImagePath) && File.Exists(_testPattermImagePath))
                {
                    _webSocketServer.AddWebSocketService <SDPExchange>("/testpattern", () =>
                    {
                        SDPExchange sdpReceiver = new SDPExchange(MediaSourceEnum.TestPattern, false, rtpIPAddress)
                        {
                            IgnoreExtensions = true
                        };
                        sdpReceiver.WebSocketOpened   += WebRtcStartCall;
                        sdpReceiver.SDPAnswerReceived += WebRtcAnswerReceived;
                        return(sdpReceiver);
                    });
                }

                _webSocketServer.Start();

                // Initialise the Media Foundation library that will pull the samples from the mp4 file.
                _mfSampleGrabber = new SIPSorceryMedia.MFSampleGrabber();
                _mfSampleGrabber.OnClockStartEvent             += OnClockStartEvent;
                _mfSampleGrabber.OnVideoResolutionChangedEvent += OnVideoResolutionChangedEvent;
                unsafe
                {
                    _mfSampleGrabber.OnProcessSampleEvent += OnProcessSampleEvent;
                }

                // Hook up event handlers to send the media samples to the network.
                InitMediaToWebRtcClients();

                // Start test pattern.
                Task.Run((Action)SendTestPattern);

                if (!String.IsNullOrEmpty(_rawRtpBaseEndPoint))
                {
                    try
                    {
                        var rawRtpBaseEndPoint = SIPSorcery.Sys.IPSocket.GetIPEndPoint(_rawRtpBaseEndPoint);

                        if (rawRtpBaseEndPoint != null)
                        {
                            logger.Info($"Raw RTP send starting, base end point {rawRtpBaseEndPoint}.");
                            SendSamplesAsRtp(rawRtpBaseEndPoint);
                        }
                    }
                    catch (Exception rawRtpExcp)
                    {
                        logger.Warn("Exception attempting to start raw RTP. " + rawRtpExcp.Message);
                    }
                }

                // Start sampling the media file.
                Task.Run(() => _mfSampleGrabber.Run(_mediaFilePath, true));
            }
            catch (Exception excp)
            {
                logger.Error("Exception WebRTCDaemon.Start. " + excp);
            }
        }
Example #9
0
        public ActionResult Create(CertificadoCreateViewModel model)
        {
            //var model = new CertificadoCreateViewModel();
            if (ModelState.IsValid)
            {
                if (model.CertificadoArchivo == null || model.CertificadoArchivo.ContentLength == 0)
                {
                    return(View());
                }
                try {
                    // var user = UserManager.FindById(this.GetUserId());
                    Guid        publicKey   = Guid.NewGuid();
                    Certificado certificado = new Certificado();
                    //certificado.NumSerie = model.NumSerie;
                    //certificado.RFC = model.RFC;
                    //certificado.Inicia = model.Inicia; // DateTime.Parse(post["inicia"].ToString(), new System.Globalization.CultureInfo("es-MX"));
                    //certificado.Finaliza = model.Finaliza;
                    ////certificado.CertificadoBase64 = model.CertificadoArchivo;
                    ////certificado.PFXArchivo = model.PFXArchivo;

                    certificado.PFXContrasena = model.PFXContrasena;
                    certificado.Estado        = model.Estado;

                    if (model.CertificadoArchivo != null)
                    {
                        MemoryStream target = new MemoryStream();
                        model.CertificadoArchivo.InputStream.CopyTo(target);
                        Byte[] data = target.ToArray();
                        certificado.CertificadoDER = data;
                        //certificado.PFXArchivo = data;
                        certificado.CertificadoBase64 = Convert.ToBase64String(data);

                        System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
                        //System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(data, certificado.PFXContrasena);
                        System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(data);
                        // cert.FriendlyName.ToString();

                        certificado.NumSerie = Certificado.GetSerialNumberString(cert);

                        //certificado.RFC = cert.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, false);
                        string[] subject = cert.Subject.Split(',');
                        foreach (string strVal in subject)
                        {
                            string value = strVal.Trim();
                            if (value.StartsWith("OID.2.5.4.45="))
                            {
                                string value2 = value.Replace("OID.2.5.4.45=", "");
                                certificado.RFC = value2.Substring(0, value2.IndexOf('/') >= 0 ? value2.IndexOf('/') : value2.Length).Trim();
                            }
                        }

                        certificado.Inicia   = DateTime.Parse(cert.GetEffectiveDateString());
                        certificado.Finaliza = DateTime.Parse(cert.GetExpirationDateString());
                        //certificado.CertificadoBase64 = model.CertificadoArchivo;
                        //certificado.PFXArchivo = model.PFXArchivo;
                    }

                    if (model.PFXArchivo != null)
                    {
                        MemoryStream target2 = new MemoryStream();
                        model.PFXArchivo.InputStream.CopyTo(target2);
                        Byte[] dataPFX = target2.ToArray();
                        certificado.PFXArchivo = dataPFX;



                        //    MemoryStream target3 = new MemoryStream();
                        //    model.CertificadoArchivo.InputStream.Position = 0;
                        //    model.CertificadoArchivo.InputStream.CopyTo(target3);
                        //    Byte[] data3 = target3.ToArray();
                        //    //string certificadoBase64 = Convert.ToBase64String(data);


                        //    //System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificado.PFXArchivo,
                        //    //     certificado.PFXContrasena, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.MachineKeySet);
                        //    //System.Security.Cryptography.RSACryptoServiceProvider rsaCryptoIPT = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey;
                    }
                    //else {
                    //    MemoryStream target3 = new MemoryStream();
                    //    model.CertificadoArchivo.InputStream.CopyTo(target3);
                    //    Byte[] data3 = target3.ToArray();
                    //    //string certificadoBase64 = Convert.ToBase64String(data);

                    //    System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
                    //    System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(data3, certificado.PFXContrasena);
                    //    cert.FriendlyName.ToString();
                    //    //System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificado.PFXArchivo,
                    //    //     certificado.PFXContrasena, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.MachineKeySet);
                    //    System.Security.Cryptography.RSACryptoServiceProvider rsaCryptoIPT = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey;


                    //}

                    if (model.PrivateKeyDER != null)
                    {
                        MemoryStream ms = new MemoryStream();
                        model.PrivateKeyDER.InputStream.CopyTo(ms);
                        Byte[] dataDER = ms.ToArray();
                        certificado.PrivateKeyDER = dataDER;
                    }
                    certificado.PrivateKeyContrasena = model.PrivateKeyContrasena;

                    this.DBContext.Certificados.Add(certificado);
                    this.DBContext.SaveChanges();
                }
                catch (Exception ex) {
                    //log.Error(ex, "Error upload photo blob to storage");
                    ex.ToString();
                }
            }
            return(RedirectToAction("Index", "Home"));
        }
Example #10
0
        protected void btnConfirmar_Click(object sender, EventArgs e)
        {
            try
            {
                var idNf   = Conversoes.StrParaUint(Request["idNf"]);
                var idLoja = Glass.Data.DAL.NotaFiscalDAO.Instance.ObtemIdLoja(idNf);

                System.Security.Cryptography.X509Certificates.X509Certificate2 cert = Certificado.GetCertificado(idLoja);

                if (DateTime.Now > cert.NotAfter)
                {
                    throw new Exception("O certificado digital cadastrado está vencido, insira um novo certificado para emitir esta nota. Data Venc.: " + cert.GetExpirationDateString());
                }

                string msg = EnviaXML.EnviaInutilizacao(idNf, txtMotivo.Text);

                MensagemAlerta.ShowMsg(msg, Page);

                Page.ClientScript.RegisterStartupScript(typeof(string), Guid.NewGuid().ToString(),
                                                        "window.close();", true);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("URI está vazio.") || ex.Message.Contains("URI is empty."))
                {
                    var mensagem = "A inutilização não está disponivel na versão 4.00 da NF-e para o seu Estado, assim que possível será disponibilizada.";
                    Glass.MensagemAlerta.ErrorMsg("Info.:", new Exception(mensagem), Page);
                    return;
                }

                Glass.MensagemAlerta.ErrorMsg("Falha ao inutilizar NFe.", ex, Page);
                return;
            }
        }
Example #11
0
        // TODO TESTE GerarCartaCorrecao
        private XmlDocument GeraXmlCartaCorrecao(uint idCarta, bool preVisualizar)
        {
            CartaCorrecao obj = GetElement(idCarta);

            NotaFiscal nf = NotaFiscalDAO.Instance.GetElement(obj.IdNf);

            XmlDocument doc = new XmlDocument();

            XmlNode declarationNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);

            doc.AppendChild(declarationNode);

            XmlElement evento = doc.CreateElement("evento");

            evento.SetAttribute("versao", "1.00");
            evento.SetAttribute("xmlns", "http://www.portalfiscal.inf.br/nfe");
            doc.AppendChild(evento);

            XmlElement infEvento = doc.CreateElement("infEvento");

            //Identificador da TAG a ser assinada, a regra de formação
            //do Id é:
            //“ID” + tpEvento +  chave da NF-e + nSeqEvento
            infEvento.SetAttribute("Id", obj.IdInfEvento);
            evento.AppendChild(infEvento);

            // Código do órgão de recepção do Evento. Utilizar a Tabela
            // do IBGE, utilizar 90 para identificar o Ambiente Nacional.
            XmlElement cOrgao = doc.CreateElement("cOrgao");

            cOrgao.InnerText = Configuracoes.FiscalConfig.NotaFiscalConfig.ContingenciaNFe == DataSources.TipoContingenciaNFe.NaoUtilizar ? obj.Orgao.ToString() : "90";
            infEvento.AppendChild(cOrgao);

            // Identificação do Amb
            // 1 - Produção
            // 2 – Homologação
            XmlElement tpAmb = doc.CreateElement("tpAmb");

            tpAmb.InnerText = obj.TipoAmbiente.ToString();
            infEvento.AppendChild(tpAmb);

            if (!string.IsNullOrEmpty(obj.CPF))
            {
                XmlElement CPF = doc.CreateElement("CPF");
                CPF.InnerText = obj.CPF.ToString().PadLeft(11, '0');
                infEvento.AppendChild(CPF);
            }
            else if (!string.IsNullOrEmpty(obj.CNPJ))
            {
                XmlElement CNPJ = doc.CreateElement("CNPJ");
                CNPJ.InnerText = obj.CNPJ.ToString().PadLeft(14, '0');
                infEvento.AppendChild(CNPJ);
            }

            XmlElement chNFe = doc.CreateElement("chNFe");

            chNFe.InnerText = obj.ChaveNFe;
            infEvento.AppendChild(chNFe);

            XmlElement dhEvento = doc.CreateElement("dhEvento");

            dhEvento.InnerText = DateTime.Now.AddMinutes(-10).ToString("yyyy-MM-ddTHH:mm:ssK");
            infEvento.AppendChild(dhEvento);

            //Código do de evento = 110110
            XmlElement tpEvento = doc.CreateElement("tpEvento");

            tpEvento.InnerText = obj.TipoEvento.ToString();
            infEvento.AppendChild(tpEvento);

            XmlElement nSeqEvento = doc.CreateElement("nSeqEvento");

            nSeqEvento.InnerText = obj.NumeroSequencialEvento.ToString();
            infEvento.AppendChild(nSeqEvento);

            XmlElement verEvento = doc.CreateElement("verEvento");

            verEvento.InnerText = obj.VersaoEvento;
            infEvento.AppendChild(verEvento);

            XmlElement detEvento = doc.CreateElement("detEvento");

            detEvento.SetAttribute("versao", "1.00");

            ManipulacaoXml.SetNode(doc, detEvento, "descEvento", obj.DescricaoEvento);
            ManipulacaoXml.SetNode(doc, detEvento, "xCorrecao", obj.Correcao);
            ManipulacaoXml.SetNode(doc, detEvento, "xCondUso", obj.CondicaoUso);

            infEvento.AppendChild(detEvento);

            #region Assina CCe

            try
            {
                if (!preVisualizar)
                {
                    MemoryStream stream = new MemoryStream();
                    doc.Save(stream);

                    using (stream)
                    {
                        // Classe responsável por assinar o xml da NFe
                        AssinaturaDigital AD = new AssinaturaDigital();

                        System.Security.Cryptography.X509Certificates.X509Certificate2 cert = Certificado.GetCertificado(nf.IdLoja.Value);

                        if (DateTime.Now > cert.NotAfter)
                        {
                            throw new Exception("O certificado digital cadastrado está vencido, insira um novo certificado para emitir esta nota. Data Venc.: " + cert.GetExpirationDateString());
                        }

                        int resultado = AD.Assinar(ref doc, "infEvento", cert);

                        if (resultado > 0)
                        {
                            throw new Exception(AD.mensagemResultado);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Falha ao assinar Carta de Correção." + ex.Message);
            }

            #endregion

            #region Valida XML

            try
            {
                if (!preVisualizar)
                {
                    ValidaXML.Validar(doc, ValidaXML.TipoArquivoXml.CCe);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("XML inconsistente." + ex.Message);
            }

            #endregion

            #region Salva arquivo XML da CCe

            try
            {
                string fileName = Utils.GetCartaCorrecaoXmlPath + doc["evento"]["infEvento"].GetAttribute("Id").Remove(0, 3) + "-cce.xml";

                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }

                doc.Save(fileName);
            }
            catch (Exception ex)
            {
                throw new Exception("Falha ao salvar arquivo xml da CCe. " + ex.Message);
            }

            #endregion

            return(doc);
        }
Example #12
0
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("WebRTC Test Media Server:");

                //_sourceSDPOffer = String.Format(_sourceSDPOffer, WEBRTC_LISTEN_PORT.ToString(), _localIPAddress, _senderICEUser, _senderICEPassword, _sourceSRTPKey);
                //_sourceSDPOffer = String.Format(_sourceSDPOffer, WEBRTC_LISTEN_PORT.ToString(), _localIPAddress, _senderICEUser, _senderICEPassword, Crypto.GetRandomInt(10).ToString());

                SDPExchangeReceiver.WebSocketOpened += SDPExchangeReceiver_WebSocketOpened;
                SDPExchangeReceiver.SDPAnswerReceived += SDPExchangeReceiver_SDPAnswerReceived;

                //var httpsv = new HttpServer(8001, true);
                //httpsv.SslConfiguration = new WebSocketSharp.Net.ServerSslConfiguration()
                //httpsv.AddWebSocketService<Echo>("/Echo");

                var wssCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("aaron-pc.p12");
                Console.WriteLine("WSS Certificate CN: " + wssCertificate.Subject + ", have key " + wssCertificate.HasPrivateKey + ", Expires " + wssCertificate.GetExpirationDateString() + ".");

                //_receiverWSS = new WebSocketServer(8081);
                _receiverWSS = new WebSocketServer(8081, true);
                //_receiverWSS.Log.Level = LogLevel.Debug;
                _receiverWSS.SslConfiguration = new WebSocketSharp.Net.ServerSslConfiguration(wssCertificate, false,
                     System.Security.Authentication.SslProtocols.Tls,
                    false);
                //_receiverWSS.Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("test.p12");
                //_receiverWSS.AddWebSocketService<SDPExchangeReceiver>("/stream");
                _receiverWSS.AddWebSocketService<SDPExchangeReceiver>("/stream",
                    () => new SDPExchangeReceiver()
                    {
                        IgnoreExtensions = true,
                    });
                _receiverWSS.Start();

                //DtlsManaged dtls = new DtlsManaged();
                //int res = dtls.Init();
                //dtls.Dispose();
                //dtls = null;

                //Console.WriteLine("DTLS initialisation result=" + res + ".");

                IPEndPoint receiverLocalEndPoint = new IPEndPoint(IPAddress.Parse(_localIPAddress), WEBRTC_LISTEN_PORT);
                _webRTCReceiverClient = new UdpClient(receiverLocalEndPoint);

                //IPEndPoint rtpLocalEndPoint = new IPEndPoint(IPAddress.Parse(_localIPAddress), 10001);
                //_rtpClient = new UdpClient(rtpLocalEndPoint);

                logger.Debug("Commencing listen to receiver WebRTC client on local socket " + receiverLocalEndPoint + ".");
                ThreadPool.QueueUserWorkItem(delegate { ListenToReceiverWebRTCClient(_webRTCReceiverClient); });
                ThreadPool.QueueUserWorkItem(delegate { SendStunConnectivityChecks(_webRTCReceiverClient); });

                //ThreadPool.QueueUserWorkItem(delegate { RelayRTP(_rtpClient); });

                ThreadPool.QueueUserWorkItem(delegate { SendRTPFromCamera(); });

                //ThreadPool.QueueUserWorkItem(delegate { SendRTPFromRawRTPFile("rtpPackets.txt"); });

                //ThreadPool.QueueUserWorkItem(delegate { SendRTPFromRawRTPFileNewVP8Header("rtpPackets.txt"); });

                //ThreadPool.QueueUserWorkItem(delegate { SendRTPFromVP8FramesFile("framesAndHeaders.txt"); });

                //ThreadPool.QueueUserWorkItem(delegate { ICMPListen(IPAddress.Parse(_localIPAddress)); });

                //ThreadPool.QueueUserWorkItem(delegate { CaptureVP8SamplesToFile("vp8sample", 1000); });

                ManualResetEvent dontStopEvent = new ManualResetEvent(false);
                dontStopEvent.WaitOne();
            }
            catch (Exception excp)
            {
                Console.WriteLine("Exception Main. " + excp);
            }
            finally
            {
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
            }
        }
Example #13
0
        public void Start()
        {
            try
            {
                logger.Debug("WebRTCDaemon starting.");

                SDPExchangeReceiver.WebSocketOpened += WebRtcStartCall;
                SDPExchangeReceiver.SDPAnswerReceived += WebRtcAnswerReceived;

                var wssCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(_webSocketCertificatePath, _webSocketCertificatePassword);
                logger.Debug("Web Socket Server Certificate CN: " + wssCertificate.Subject + ", have key " + wssCertificate.HasPrivateKey + ", Expires " + wssCertificate.GetExpirationDateString() + ".");

                _receiverWSS = new WebSocketServer(8081, true);
                //_receiverWSS.Log.Level = LogLevel.Debug;
                _receiverWSS.SslConfiguration = new WebSocketSharp.Net.ServerSslConfiguration(wssCertificate, false,
                     System.Security.Authentication.SslProtocols.Tls,
                    false);

                _receiverWSS.AddWebSocketService<SDPExchangeReceiver>("/stream",
                    () => new SDPExchangeReceiver()
                    {
                        IgnoreExtensions = true,
                    });
                _receiverWSS.Start();

                ThreadPool.QueueUserWorkItem(delegate { SendTestPattern(); });
            }
            catch (Exception excp)
            {
                logger.Error("Exception WebRTCDaemon.Start. " + excp);
            }
        }