Esempio n. 1
0
        public Object Clone()
        {
            EnterpriseKeyConfig clone = new EnterpriseKeyConfig();

            clone.enterpriseId = this.enterpriseId;

            clone.ServerPKCS12Cert      = this.ServerPKCS12Cert;
            clone.ClientPKCS12Cert      = this.ClientPKCS12Cert;
            clone.ServerCert            = this.ServerCert;
            clone.ServerPKCS12String    = this.ServerPKCS12String;
            clone.ClientPKCS12String    = this.ClientPKCS12String;
            clone.ServerCertString      = this.ServerCertString;
            clone.ServerInstallationKey = this.ServerInstallationKey;

            return(clone);
        }
Esempio n. 2
0
        public void RenewCert(SqlConnection conn)
        {
            base.Connection = conn;

            DataTable dt = ExecuteDataTable("select server_cert, server_pkcs12_cert from server_cert with(nolock)");

            if ((dt != null) && (dt.Rows.Count > 0)) //Existe certificado, então lê
            {
                //Resgata o certificado do banco
                X509Certificate atualServerPKCS12Cert = CATools.LoadCert(Convert.FromBase64String(dt.Rows[0]["server_pkcs12_cert"].ToString()), "w0):X,\\Q4^NoIO,):Z!.");

                //Primeiramente atualiza todas as senhas atuais para a senha usando o certificado da empresa
                SqlTransaction trans = null;

                /*
                 * conn.BeginTransaction();
                 * try
                 * {
                 *  //Criptografa a senha de todas as entidades
                 *  DataTable dtEnterprise = ExecuteDataTable("select * from enterprise with(nolock)", trans);
                 *  if (dtEnterprise == null)
                 *      throw new Exception("Erro on enterprise SQL");
                 *
                 *  foreach (DataRow drEnt in dtEnterprise.Rows)
                 *  {
                 *      Console.WriteLine("Enterprise " + drEnt["id"]);
                 *
                 *      using (EnterpriseKeyConfig ek = new EnterpriseKeyConfig(conn, (Int64)drEnt["id"], trans))
                 *      {
                 *
                 *          DataTable dtEnt = ExecuteDataTable("select e.id, e.login, e.password from entity e with(nolock) inner join context c with(nolock) on c.id = e.context_id where c.enterprise_id = " + drEnt["id"], trans);
                 *          if (dtEnt == null)
                 *              throw new Exception("Erro on SQL");
                 *
                 *          foreach (DataRow dr in dtEnt.Rows)
                 *          {
                 *              Console.Write("\t[SK] Entity " + dr["id"] + ": ");
                 *
                 *              CryptApi decryptApi = null;
                 *              try
                 *              {
                 *
                 *                  try
                 *                  {
                 *                      //Tenta decriptografia com certificado da empresa
                 *                      decryptApi = CryptApi.ParsePackage(ek.ServerPKCS12Cert, Convert.FromBase64String(dr["password"].ToString()));
                 *
                 *                      //Processo OK, a senha ja está usando o certificado da empresa
                 *                      Console.WriteLine("OK");
                 *                      continue;
                 *
                 *                  }
                 *                  catch
                 *                  {
                 *
                 *                      //Tenta decriptografia com o certificado geral do servidor
                 *                      //Se conseguir atualiza a senha para o certificado da empresa
                 *                      decryptApi = CryptApi.ParsePackage(atualServerPKCS12Cert, Convert.FromBase64String(dr["password"].ToString()));
                 *                  }
                 *
                 *                  using (CryptApi ecryptApi = new CryptApi(ek.ServerCert, decryptApi.clearData))
                 *                  {
                 *
                 *                      DbParameterCollection pPar = new DbParameterCollection();
                 *                      String b64 = Convert.ToBase64String(ecryptApi.ToBytes());
                 *                      pPar.Add("@password", typeof(String), b64.Length).Value = b64;
                 *
                 *                      Exception ex1 = null;
                 *                      for (Int32 count = 1; count <= 3; count++)
                 *                      {
                 *                          try
                 *                          {
                 *                              ExecuteNonQuery("update entity set password = @password where id = " + dr["id"], CommandType.Text, pPar, trans);
                 *                              ex1 = null;
                 *                              break;
                 *                          }
                 *                          catch (Exception ex)
                 *                          {
                 *                              ex1 = ex;
                 *                              if (ex.Message.ToLower().IndexOf("timeout") != -1)
                 *                              {
                 *                                  System.Threading.Thread.Sleep(1000 * count);
                 *                              }
                 *                          }
                 *                      }
                 *
                 *                      if (ex1 != null)
                 *                          throw ex1;
                 *
                 *                      Log(drEnt["id"].ToString(), dr["id"].ToString(), dr["login"].ToString(), Encoding.UTF8.GetString(decryptApi.clearData));
                 *                      Console.WriteLine("OK, Updated");
                 *                  }
                 *
                 *              }
                 *              catch (Exception ex)
                 *              {
                 *                  Console.WriteLine("Err");
                 *                  throw ex;
                 *              }
                 *              finally
                 *              {
                 *                  if (decryptApi != null) decryptApi.Dispose();
                 *              }
                 *
                 *          }
                 *
                 *      }
                 *
                 *      Console.WriteLine("");
                 *  }
                 *
                 *  //Se tudo estiver OK, realiza o commit dos dados
                 *  trans.Commit();
                 *  Console.WriteLine("Commit");
                 * }
                 * catch (Exception ex)
                 * {
                 *  Console.WriteLine("Rollback");
                 *  if (trans != null) trans.Rollback();
                 *  throw ex;
                 * }*/

                //Atualiza o certificado global do servidor
                //e gera novo certificado da empresa e atualiza o mesmo
                trans = conn.BeginTransaction();
                Console.WriteLine("Update Global Server Certificate");
                try
                {
                    //Se a chave de instalaçõe é nula
                    if (this.ServerInstallationKey == null)
                    {
                        this.ServerInstallationKey = GetInstallationCode(atualServerPKCS12Cert);
                    }

                    //Cria o novo certificado, e a chave se não existir ainda
                    this.BuildCert();

                    //Exclui o certificado atual do banco
                    ExecuteNonQuery("delete from server_cert", CommandType.Text, null, trans);

                    //Salva o novo certificado
                    DbParameterCollection par = new DbParameterCollection();
                    par.Add("@server_cert", typeof(String), this.ServerCertString.Length).Value          = this.ServerCertString;
                    par.Add("@server_pkcs12_cert", typeof(String), this.ServerPKCS12String.Length).Value = this.ServerPKCS12String;

                    ExecuteNonQuery("insert into server_cert (server_cert, server_pkcs12_cert) values (@server_cert, @server_pkcs12_cert)", CommandType.Text, par, trans);


                    Console.WriteLine("Commit");
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Rollback");
                    trans.Rollback();
                    throw ex;
                }

                try
                {
                    //Criptografa a senha de todas as entidades

                    DataTable dtEnterprise = ExecuteDataTable("select * from enterprise with(nolock)", trans);
                    if (dtEnterprise == null)
                    {
                        throw new Exception("Erro on enterprise SQL");
                    }

                    foreach (DataRow drEnt in dtEnterprise.Rows)
                    {
                        Console.WriteLine("Enterprise " + drEnt["id"]);

                        using (EnterpriseKeyConfig ek = new EnterpriseKeyConfig(conn, (Int64)drEnt["id"], trans))
                            ek.RenewCert(conn);

                        Console.WriteLine("");
                    }

                    try
                    {
                        System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(typeof(ServerKey2));
                        FileInfo certFile = new FileInfo(Path.Combine(Path.GetDirectoryName(asm.Location), "server.cer"));
                        if (certFile.Exists)
                        {
                            certFile.Delete();
                        }

                        File.WriteAllBytes(certFile.FullName, Convert.FromBase64String(this.ServerCertString));
                    }
                    catch { }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else //Não foi encontrado certificado no banco, erro
            {
                //Como ao instanciar esta classe a verificação e criação do certificado ja foi realizada, não deve acontecer esse erro
                throw new Exception("Erro on find server certificate");
            }
        }