Utilities.Security 1.1.0

dotnet add package Utilities.Security --version 1.1.0
                    
NuGet\Install-Package Utilities.Security -Version 1.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Utilities.Security" Version="1.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Utilities.Security" Version="1.1.0" />
                    
Directory.Packages.props
<PackageReference Include="Utilities.Security" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Utilities.Security --version 1.1.0
                    
#r "nuget: Utilities.Security, 1.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Utilities.Security@1.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Utilities.Security&version=1.1.0
                    
Install as a Cake Addin
#tool nuget:?package=Utilities.Security&version=1.1.0
                    
Install as a Cake Tool

Backend Utilities

 ____             _                  _   _   _ _   _ _ _ _   _           
| __ )  __ _  ___| | _____ _ __   __| | | | | | |_(_) (_) |_(_) ___  ___ 
|  _ \ / _` |/ __| |/ / _ \ '_ \ / _` | | | | | __| | | | __| |/ _ \/ __|
| |_) | (_| | (__|   <  __/ | | | (_| | | |_| | |_| | | | |_| |  __/\__ \
|____/ \__,_|\___|_|\_\___|_| |_|\__,_|  \___/ \__|_|_|_|\__|_|\___||___/

Biblioteca utilitária para aplicações .NET com foco em operações comuns de backend. O repositório está dividido em dois pacotes:

  • Utilities.General: compressão, HTTP, JSON, extensões de string, validação de documentos e utilitários de e-mail.
  • Utilities.Security: criptografia, JWT, validação de senha, Base64 e helpers para bytes/hash.

Alvos do projeto

  • Utilities.General: netstandard2.1
  • Utilities.Security: net10.0

O módulo Utilities.Security referencia Utilities.General, então os recursos de serialização e extensões compartilhadas podem ser reutilizados entre os dois pacotes.

Estrutura

General

  • CompressUtil: compacta/descompacta texto Base64 com GZip, cria/extrai arquivos ZIP e trabalha com ZIP em memória.
  • MailUtil: classe base abstrata para envio SMTP com suporte a um ou múltiplos destinatários e anexos.
  • Extensions/StringExtension: desserialização simples de JSON e helpers de string como Left, Right e validações de caracteres.
  • Http/HttpClientUtil: classe base para clientes HTTP com GET, POST, PUT, DELETE, configuração de retries, headers e autenticação.
  • Json/Utils: serialização, desserialização e minificação de JSON com System.Text.Json.
  • Validations/DocumentValidation: valida CPF e CNPJ.

Security

  • Cryptography/CryptographyUtil: AES, Rijndael, MD5 e rotinas auxiliares de conversão.
  • Cryptography/RsaCryptography: criptografia RSA com PEM e certificados X509.
  • Jwt/*: geração de token JWT, configuração RSA e extensão para registrar autenticação/autorização no IServiceCollection.
  • Extensions/WebSecurityExtension: validação de complexidade de senha, encode/decode Base64 e verificação de URL local.
  • Utils/BytesUtils: serializa objetos para byte[] e reconstrói objetos a partir de bytes.
  • Utils/StringUtils: geração de código aleatório e cálculo de hash MD5 a partir de objetos.

Como usar

Você pode consumir a biblioteca por referência de projeto ou empacotamento NuGet interno. Em uma solução local:

<ItemGroup>
  <ProjectReference Include="Source\General\Utilities.General.csproj" />
  <ProjectReference Include="Source\Security\Utilities.Security.csproj" />
</ItemGroup>

Exemplos

Serialização JSON

using Utilities.General.Json;

var payload = new { Name = "Kuva", Enabled = true };
var json = Utils.Serialize(payload);
var restored = Utils.Deserialize<Dictionary<string, object>>(json!);

Compressão de texto

using Utilities.General;

var compressed = CompressUtil.CompressString("conteudo sensivel");
var original = CompressUtil.DecompressString(compressed);

Validação de CPF/CNPJ

using Utilities.General.Validations;

bool cpfValido = DocumentValidation.IsCpf("123.456.789-09");
bool cnpjValido = DocumentValidation.IsCnpj("12.345.678/0001-95");

Extensões de string

using Utilities.General.Extensions;

var resumo = "BackendUtilities".Left(7);       // Backend
var sufixo = "BackendUtilities".Right(9);      // Utilities
var temNumero = "Senha123!".HasNumber();       // true
var semAcento = "ação".GetUnicodeString();     // acao

Cliente HTTP customizado

HttpClientUtil é uma classe abstrata. A forma esperada de uso é criar um client especializado com a BaseUri da integração:

using Utilities.General.Http;

public sealed class SandboxClient : HttpClientUtil
{
    public SandboxClient()
        : base(new HttpConfiguration
        {
            BaseUri = "https://sandbox.kuva.com.br/api/",
            AttempsRequest = 3
        })
    {
    }
}

Depois disso, use os métodos assíncronos com callback de conclusão:

await client.GetAsync("values", HttpClientUtil.HttpApplication.Json,
    async (response, error) =>
    {
        if (error != null)
        {
            await error.LogErrorAsync();
            return;
        }

        var content = await response.Content.ReadAsStringAsync();
        var result = content.ConvertJsonObject<dynamic>();
    });

Geração de JWT

using Utilities.Security.Jwt;

var auth = new JwtAuthentication(
    new RsaSigningConfiguration(),
    new JwtConfiguration
    {
        Audience = "MyAudience",
        Issuer = "MyIssuer",
        Milliseconds = 60000
    });

var token = auth.TokenGenerate("user@kuva.com", "custom");

Registro de autenticação JWT no ASP.NET Core

using Utilities.Security.Jwt;

builder.Services.AddKuvaJwt(builder.Configuration.GetSection("JwtConfiguration"));

Se a configuração contiver RsaCertificateThumbPrint, a biblioteca tenta usar o certificado do repositório local da máquina; caso contrário, gera uma chave RSA em memória.

Validação de senha

using Utilities.Security;
using Utilities.Security.Extensions;

if (!"Senha123!".ValidatePasswordComplexity(out var error))
{
    Console.WriteLine(error);
}

Critérios aplicados:

  • mínimo de 8 caracteres
  • ao menos uma letra minúscula
  • ao menos uma letra maiúscula
  • ao menos um número
  • ao menos um símbolo

Conversão para bytes e hash

using Utilities.Security.Utils;

var bytes = BytesUtils.GetBytesFrom(new { Id = 1, Name = "Kuva" });
var restored = BytesUtils.GetObjectFromBytes<Dictionary<string, object>>(bytes);
var hash = StringUtils.ComputeHash(new { Id = 1, Name = "Kuva" });

Observações

  • Algumas APIs retornam null, default ou false em caso de falha em vez de lançar exceção; trate esse fluxo explicitamente no consumo.
  • MailUtil e HttpClientUtil são classes base e foram desenhadas para especialização em implementações concretas.
  • A validação de documentos considera entradas com ou sem máscara para CPF e CNPJ.
  • O suporte de JWT depende de componentes do ASP.NET Core e certificados locais quando o thumbprint é configurado.

Testes

O comportamento da biblioteca é coberto pelo projeto Source/UtilitiesTest, incluindo cenários adicionais para JSON, HTTP, criptografia, JWT, extensões e validações.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.0 105 5/2/2026
1.0.3 247 2/24/2025