/// <summary>
        /// Parses the Authorization header and creates user credentials
        /// </summary>
        /// <param name="actionContext"></param>
        protected virtual AuthenticationIdentity AuthHeader(HttpActionContext actionContext)
        {
            string authHeader = null;
            var    auth       = actionContext.Request.Headers.Authorization;

            if (auth != null && auth.Scheme == "Bearer")
            {
                authHeader = auth.Parameter;
            }
            if (string.IsNullOrEmpty(authHeader))
            {
                return(null);
            }

            var jwtKey = System.Configuration.ConfigurationManager.AppSettings["jwtKey"];

            SymmetricAlgorithm     sa   = new SymmetricAlgorithm(SymmetricAlgorithm.Tipo.TripleDES);
            AuthenticationIdentity user = null;

            try
            {
                authHeader = JWT.JsonWebToken.Decode(authHeader, sa.Decrypt(jwtKey));
                user       = JsonConvert.DeserializeObject <AuthenticationIdentity>(authHeader);
            }
            catch
            {
            }

            return(user);
        }
Beispiel #2
0
        public IPrincipal CreatePrincipal(string userName, string password)
        {
            if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(Password))
            {
                throw new Exception("Usuário não configurado.");
            }

            string senhaDescriptografada = "";

            try
            {
                SymmetricAlgorithm sa = new SymmetricAlgorithm(SymmetricAlgorithm.Tipo.TripleDES);
                senhaDescriptografada = sa.Decrypt(password, System.Text.Encoding.UTF8);
            }
            catch
            {
                throw new Exception("Acesso não autorizado.");
            }

            if (userName != UserName || senhaDescriptografada != Password)
            {
                throw new Exception("Acesso não autorizado.");
            }

            var        identity  = new GenericIdentity(UserName);
            IPrincipal principal = new GenericPrincipal(identity, new[] { "User" });

            return(principal);
        }
        /// <summary>
        ///   <para>Decrypts encrypted contents of a <see cref="Stream"/>, using specified symmetric algorithm.</para>
        /// </summary>
        /// <param name="self">Symmetric algorithm which have been used for encryption previously and should be used for decryption now.</param>
        /// <param name="source">Stream of binary data to be decrypted.</param>
        /// <param name="close">Whether to close <paramref name="source"/> stream when all data from it has been read and decrypted.</param>
        /// <returns>Decrypted binary data.</returns>
        /// <exception cref="ArgumentNullException">If either <paramref name="self"/> or <paramref name="source"/> is a <c>null</c> reference.</exception>
        /// <seealso cref="Decrypt(SymmetricAlgorithm, byte[])"/>
        public static byte[] Decrypt(this SymmetricAlgorithm self, Stream source, bool close = false)
        {
            Assertion.NotNull(self);
            Assertion.NotNull(source);

            return(self.Decrypt(source.Bytes(close)));
        }
        /// <summary>
        /// Returns a binary array of decrypted data for the given parameters.
        /// </summary>
        /// <param name="algorithm"><see cref="SymmetricAlgorithm"/> to use for decryption.</param>
        /// <param name="data">Source buffer containing data to decrypt.</param>
        /// <param name="startIndex">Offset into <paramref name="data"/> buffer.</param>
        /// <param name="length">Number of bytes in <paramref name="data"/> buffer to decrypt starting from <paramref name="startIndex"/> offset.</param>
        /// <param name="key">The secret key to use for the symmetric algorithm.</param>
        /// <param name="iv">The initialization vector to use for the symmetric algorithm.</param>
        /// <returns>Decrypted version of <paramref name="data"/> buffer.</returns>
        public static byte[] Decrypt(this SymmetricAlgorithm algorithm, byte[] data, int startIndex, int length, byte[] key, byte[] iv)
        {
            // Fastest to use existing buffer in non-expandable memory stream for source and large block allocated memory stream for destination
            using MemoryStream source = new MemoryStream(data, startIndex, length);
            using BlockAllocatedMemoryStream destination = new BlockAllocatedMemoryStream();

            algorithm.Decrypt(source, destination, key, iv);
            return(destination.ToArray());
        }
Beispiel #5
0
        public static string CreateToken(string usuario, string entidade, string grupo)
        {
            var jwtKey                      = System.Configuration.ConfigurationManager.AppSettings["jwtKey"];
            SymmetricAlgorithm sa           = new SymmetricAlgorithm(SymmetricAlgorithm.Tipo.TripleDES);
            var currentTime                 = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
            var expTime                     = DateTime.UtcNow.AddMinutes(30).ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
            Dictionary <string, object> dic = new Dictionary <string, object>();

            dic.Add("Login", usuario);
            dic.Add("Entity", entidade);
            dic.Add("Group", grupo);
            dic.Add("iat", currentTime);
            dic.Add("exp", expTime);
            return(JWT.JsonWebToken.Encode(dic, sa.Decrypt(jwtKey), JWT.JwtHashAlgorithm.HS256));
        }
        /// <summary>
        /// Retorna os dados do log para entidade.
        /// </summary>
        /// <param name="dados">Dados do log criptografado</param>
        /// <returns></returns>
        public static LOG_DadosUsuarioAD GetDadosUsuarioADToEntity(string dados)
        {
            SymmetricAlgorithm encript = new SymmetricAlgorithm(SymmetricAlgorithm.Tipo.TripleDES);

            dados = encript.Decrypt(dados);

            LOG_DadosUsuarioAD log = new LOG_DadosUsuarioAD();

            using (XmlReader reader = XmlReader.Create(new StringReader(dados)))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(LOG_DadosUsuarioAD));
                log = (LOG_DadosUsuarioAD)serializer.Deserialize(reader);
            }

            return(log);
        }
 /// <summary>
 /// Descifra con algoritmo simétrico una cadena cifrada mediante SymmetricEncryptAndSerializeToHexString
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="s"></param>
 /// <returns></returns>
 public static T DecryptAndDeserializeFromHexString <T> (this SymmetricAlgorithm self, string s)
 {
     return(self.Decrypt <T> (s.HexStringToByteArray()));
 }
Beispiel #8
0
        public HttpResponseMessage PostLogin(Usuario usuario)
        {
            try
            {
                var user = new SYS_Usuario {
                    usu_login = usuario.login, usu_senha = usuario.senha, ent_id = usuario.entidade
                };
                LoginStatus status = SYS_UsuarioBO.ValidarLogin(user);

                if (status == LoginStatus.Sucesso)
                {
                    if (SYS_UsuarioBO.GetSelectBy_ent_id_usu_login(user))
                    {
                        var grupos = SYS_GrupoBO.GetSelectBySis_idAndUsu_id(user.usu_id, ApplicationWEB.SistemaID);
                        if (grupos.Count > 0)
                        {
                            var grupo = grupos.First();
                            Dictionary <string, object> dic = new Dictionary <string, object>();
                            dic.Add("login", user.usu_login);
                            dic.Add("entity", user.ent_id);
                            dic.Add("group", grupo.gru_id);

                            var jwtKey            = System.Configuration.ConfigurationManager.AppSettings["jwtKey"];
                            SymmetricAlgorithm sa = new SymmetricAlgorithm(SymmetricAlgorithm.Tipo.TripleDES);

                            PES_Pessoa entityPessoa = new PES_Pessoa {
                                pes_id = user.pes_id
                            };
                            PES_PessoaBO.GetEntity(entityPessoa);

                            bool docente = false;
                            if (grupo.vis_id == SysVisaoID.Individual)
                            {
                                // Carrega a entidade docente de acordo com a pessoa do usuário logado.
                                ACA_Docente entityDocente;
                                ACA_DocenteBO.GetSelectBy_Pessoa(user.ent_id, user.pes_id, out entityDocente);
                                docente = entityDocente.doc_id > 0;
                            }

                            UsuarioLogado usuarioLogado = new UsuarioLogado {
                                grupo   = grupos.First().gru_nome,
                                nome    = (string.IsNullOrEmpty(entityPessoa.pes_nome) ? user.usu_login : entityPessoa.pes_nome),
                                docente = docente,
                                token   = JWT.JsonWebToken.Encode(dic, sa.Decrypt(jwtKey), JWT.JwtHashAlgorithm.HS256)
                            };

                            return(Request.CreateResponse(HttpStatusCode.OK, usuarioLogado));
                        }
                        else
                        {
                            return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Usuário não está vinculado a um grupo"));
                        }
                    }
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Usuário não encontrado"));
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Usuário ou senha inválidos"));
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
Beispiel #9
0
        /// <summary>
        /// Verifica configuraçãoes da Integração Externa,
        /// e cria objeto WebProxy apartir das mesmas.
        /// <param name="entityIntegracaoExterna">Entidade SYS_IntegracaoExterna</param>
        /// <param name="proxy"></param>
        /// <returns></returns>
        public static bool GerarProxy(SYS_IntegracaoExterna entityIntegracaoExterna, out WebProxy proxy)
        {
            bool flagProxy = ((entityIntegracaoExterna.ine_proxy) && (!string.IsNullOrEmpty(entityIntegracaoExterna.ine_proxyIP)));

            // Verifica se configurado para Usar Proxy
            if (flagProxy)
            {
                int proxyPorta = (!string.IsNullOrEmpty(entityIntegracaoExterna.ine_proxyPorta) ? Convert.ToInt32(entityIntegracaoExterna.ine_proxyPorta) : 0);
                proxy = new WebProxy(entityIntegracaoExterna.ine_proxyIP, proxyPorta);

                // Verifica se configurado para Usar Autenticação,
                // caso esteja instancia o NetworkCredential do proxy
                if (entityIntegracaoExterna.ine_proxyAutenticacao)
                {
                    if ((!string.IsNullOrEmpty(entityIntegracaoExterna.ine_proxyAutenticacaoUsuario)) &&
                        (!string.IsNullOrEmpty(entityIntegracaoExterna.ine_proxyAutenticacaoSenha)))
                    {
                        SymmetricAlgorithm encript    = new SymmetricAlgorithm(SymmetricAlgorithm.Tipo.TripleDES);
                        NetworkCredential  credencial = new NetworkCredential(entityIntegracaoExterna.ine_proxyAutenticacaoUsuario, encript.Decrypt(entityIntegracaoExterna.ine_proxyAutenticacaoSenha));
                        proxy.Credentials = credencial;
                    }
                }
            }
            else
            {
                proxy = new WebProxy();
            }

            return(flagProxy);
        }
 public virtual byte[] Decrypt(byte[] input)
 {
     return(_algorithm.Decrypt(input));
 }