Skip to main content
This example demonstrates two encryption approaches: basic SHA1 encryption and efficient SHA512 encryption with salt for enhanced security.

Overview

The HelperCryptography class provides cryptographic utilities for hashing sensitive data like passwords. It offers both basic and advanced encryption methods with comparison capabilities.

Encryption Methods

Basic Encryption (SHA1)

Simple SHA1-based encryption suitable for basic hashing needs.

Efficient Encryption (SHA512 + Salt)

Advanced encryption using SHA512 with randomly generated salt, iterated 12 times for enhanced security.

Complete Implementation

1

Create the Cryptography Helper

The HelperCryptography class provides static methods for encryption.
Helpers/HelperCryptography.cs
using System.Security.Cryptography;
using System.Text;

namespace MvcCoreUtilidades.Helpers
{
    public class HelperCryptography
    {
        public static string Salt { get; set; }

        private static string GenerateSalt()
        {
            Random random = new Random();
            string salt = "";
            for (int i = 1; i <= 30; i++)
            {
                int num = random.Next(1, 255);
                char letra = Convert.ToChar(num);
                salt += letra;
            }
            return salt;
        }

        public static string CifrarContenido(string contenido, bool comparar)
        {
            if (comparar == false)
            {
                Salt = GenerateSalt();
            }

            string contenidoSalt = contenido + Salt;
            SHA512 managed = SHA512.Create();
            UnicodeEncoding encoding = new UnicodeEncoding();
            byte[] salida;
            salida = encoding.GetBytes(contenidoSalt);
            for (int i = 1; i <= 12; i++)
            {
                salida = managed.ComputeHash(salida);
            }
            managed.Clear();
            string resultado = encoding.GetString(salida);
            return resultado;
        }

        public static string EncriptarTextoBasico(string contenido)
        {
            byte[] entrada;
            byte[] salida;
            UnicodeEncoding encoding = new UnicodeEncoding();
            SHA1 managed = SHA1.Create();
            entrada = encoding.GetBytes(contenido);
            salida = managed.ComputeHash(entrada);

            string resultado = encoding.GetString(salida);
            return resultado;
        }
    }
}
See HelperCryptography.cs:24 and HelperCryptography.cs:45
2

Create the Controller

The controller handles both encryption methods with encrypt and compare actions.
Controllers/CifradosController.cs
using Microsoft.AspNetCore.Mvc;
using MvcCoreUtilidades.Helpers;

namespace MvcCoreUtilidades.Controllers
{
    public class CifradosController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult CifradoBasico()
        {
            return View();
        }

        public IActionResult CifradoEficiente()
        {
            return View();
        }

        [HttpPost]
        public IActionResult CifradoEficiente(string contenido, string resultado, string accion)
        {
            if (accion.ToLower() == "cifrar")
            {
                string response = HelperCryptography.CifrarContenido(contenido, false);
                ViewData["TEXTOCIFRADO"] = response;
                ViewData["SALT"] = HelperCryptography.Salt;
            }
            else if (accion.ToLower() == "comparar")
            {
                string response = HelperCryptography.CifrarContenido(contenido, true);
                if (response != resultado)
                {
                    ViewData["MENSAJE"] = "Los datos son distintos...";
                }
                else
                {
                    ViewData["MENSAJE"] = "Los datos son IGUALES!!!";
                }
            }
            return View();
        }

        [HttpPost]
        public IActionResult CifradoBasico(string contenido, string resultado, string accion)
        {
            string response =
            HelperCryptography.EncriptarTextoBasico(contenido);
            if (accion.ToLower() == "cifrar")
            {
                ViewData["TEXTOCIFRADO"] = response;
            }
            else if (accion.ToLower() == "comparar")
            {
                if (response != resultado)
                {
                    ViewData["MENSAJE"] = "Los datos no coinciden";
                }
                else
                {
                    ViewData["MENSAJE"] = "Contenidos iguales!!!";
                }
            }
            return View();
        }
    }
}
See CifradosController.cs:24 and CifradosController.cs:48
3

Create the Views

Basic Encryption View:
Views/Cifrados/CifradoBasico.cshtml
<h1>Cifrado básico Texto</h1>

<form method="post" class="my-2">
    <label>Contenido a cifrar: </label>
    <input type="text" name="contenido" class="form-control" />
    <label class="mt-1">Resultado cifrado: </label>
    <textarea rows="5" name="resultado" class="form-control">@ViewData["TEXTOCIFRADO"]</textarea>
    <button class="btn btn-info my-2" name="accion" value="cifrar">
    Cifrar contenido
    </button>
    <button class="btn btn-danger" name="accion" value="comparar">
    Comparar cifrado
    </button>
</form>
<h2 style="color: blue">@ViewData["MENSAJE"]</h2>
Efficient Encryption View:
Views/Cifrados/CifradoEficiente.cshtml
<h1>Cifrado Eficiente</h1>

<form method="post" class="my-2">
    <label>Contenido a cifrar: </label>
    <input type="text" name="contenido" class="form-control" />
    <label class="mt-1">Resultado cifrado: </label>
    <textarea rows="5" name="resultado" class="form-control">@ViewData["TEXTOCIFRADO"]</textarea>
    <button class="btn btn-info my-2" name="accion" value="cifrar">
        Cifrar contenido
    </button>
    <button class="btn btn-danger" name="accion" value="comparar">
        Comparar cifrado
    </button>
</form>
<h3 style="color:red">@ViewData["SALT"]</h3>
<h2 style="color:blue">@ViewData["MENSAJE"]</h2>

How It Works

Basic Encryption Workflow

  1. Encrypt: Enter text → Click “Cifrar contenido” → Get SHA1 hash
  2. Compare: Enter original text → Paste encrypted result → Click “Comparar cifrado” → Verify match

Efficient Encryption Workflow

  1. Encrypt: Enter text → Click “Cifrar contenido” → Get SHA512 hash + Salt displayed
  2. Store Salt: Save the displayed salt (red text) - required for comparison
  3. Compare: Enter original text → Paste encrypted result → Click “Comparar cifrado” → Uses same salt to verify

Key Differences

  • Algorithm: SHA1
  • Salt: None
  • Iterations: 1
  • Security: Basic
  • Use Case: Simple hashing, checksums
  • Same input always produces same output
  • Algorithm: SHA512
  • Salt: 30-character random string
  • Iterations: 12 (repeated hashing)
  • Security: Enhanced
  • Use Case: Password hashing, sensitive data
  • Same input produces different output each time (due to random salt)

Important Security Notes

The salt is generated randomly each time you encrypt. For comparison to work:
  1. Store the salt along with the encrypted value
  2. Use the same salt when comparing (set comparar = true)
  3. The HelperCryptography.Salt property must contain the original salt
For production password hashing, consider using:
  • BCrypt or Argon2 instead of custom implementations
  • Built-in ASP.NET Core Identity password hashers
  • These provide industry-standard security

Usage Examples

Encrypting a Password

// Encrypt with SHA512 + Salt
string encrypted = HelperCryptography.CifrarContenido("myPassword123", false);
string salt = HelperCryptography.Salt;

// Store both encrypted value and salt in database

Comparing a Password

// Retrieve salt from database
HelperCryptography.Salt = storedSalt;

// Compare user input with stored encrypted value
string inputEncrypted = HelperCryptography.CifrarContenido(userInput, true);
if (inputEncrypted == storedEncryptedPassword)
{
    // Password matches
}

HelperCryptography

Complete API reference for encryption methods

Controllers

CifradosController API reference

Build docs developers (and LLMs) love