Created
January 31, 2026 04:18
-
-
Save hernandohhoyos/d7a1340468a92928f056ee30c4abea56 to your computer and use it in GitHub Desktop.
Blockchain simple vs hmac
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import hashlib | |
| import hmac | |
| import time | |
| # Configuración | |
| N_BLOQUES = 10000000 | |
| MENSAJE_BASE = "Data_Block_" | |
| # --- 1. GENERACIÓN DE LAS CADENAS --- | |
| def crear_blockchain_simple(n): | |
| cadena = [] | |
| hash_ant = "0" * 64 | |
| for i in range(n): | |
| msg = f"{MENSAJE_BASE}{i}{hash_ant}".encode() | |
| h = hashlib.sha256(msg).hexdigest() | |
| cadena.append({'data': f"{MENSAJE_BASE}{i}", 'hash': h, 'prev': hash_ant}) | |
| hash_ant = h | |
| return cadena | |
| def crear_blockchain_hmac(n): | |
| cadena = [] | |
| # Usamos un valor inicial como "llave génesis" | |
| llave_ant = "genesis_key".encode() | |
| for i in range(n): | |
| msg = f"{MENSAJE_BASE}{i}".encode() | |
| # El hash anterior es la LLAVE del actual | |
| h = hmac.new(llave_ant, msg, hashlib.sha256).hexdigest() | |
| cadena.append({'data': f"{MENSAJE_BASE}{i}", 'hash': h, 'prev_key': llave_ant.hex()}) | |
| llave_ant = h.encode() | |
| return cadena | |
| # --- 2. FUNCIONES DE VERIFICACIÓN (PRUEBAS DE INTEGRIDAD) --- | |
| def verificar_sha(cadena): | |
| for i in range(1, len(cadena)): | |
| # Re-calculamos: Hash(Data actual + Hash anterior) | |
| check = hashlib.sha256(f"{cadena[i]['data']}{cadena[i-1]['hash']}".encode()).hexdigest() | |
| if check != cadena[i]['hash']: | |
| return False, i | |
| return True, None | |
| def verificar_hmac(cadena): | |
| for i in range(1, len(cadena)): | |
| # Re-calculamos: HMAC(Llave=Hash anterior, Mensaje=Data actual) | |
| llave = cadena[i-1]['hash'].encode() | |
| msg = cadena[i]['data'].encode() | |
| check = hmac.new(llave, msg, hashlib.sha256).hexdigest() | |
| if check != cadena[i]['hash']: | |
| return False, i | |
| return True, None | |
| # --- 3. EJECUCIÓN DEL EXPERIMENTO --- | |
| # --- 3.1 EJECUCIÓN Y COMPARATIVA --- | |
| # Crear cadenas | |
| # Test SHA-256 | |
| start = time.time() | |
| c_sha = crear_blockchain_simple(N_BLOQUES) | |
| time_sha = time.time() - start | |
| # Test HMAC | |
| start = time.time() | |
| c_hmac = crear_blockchain_hmac(N_BLOQUES) | |
| time_hmac = time.time() - start | |
| print(f"\n--- RESULTADOS PARA {N_BLOQUES} BLOQUES ---") | |
| print(f"SHA-256 Simple: {time_sha:.6f} seg | Peso Hash: {len(c_sha[0]['hash'])} chars (Hex)") | |
| print(f"HMAC en Cadena: {time_hmac:.6f} seg | Peso Hash: {len(c_hmac[0]['hash'])} chars (Hex)") | |
| print(f"Diferencia de tiempo: {((time_hmac/time_sha)-1)*100:.2f}% más lento el HMAC") | |
| print(f"\n--- PRUEBA DE INTEGRIDAD INICIAL ---") | |
| print(f"Integridad SHA-256: {verificar_sha(c_sha)[0]}") | |
| print(f"Integridad HMAC: {verificar_hmac(c_hmac)[0]}") | |
| # --- EL ATAQUE (MODIFICACIÓN DE DATOS) --- | |
| # Cambiamos un dato a mitad de la cadena (bloque 50/55) | |
| print(f"\n[!] Alterando datos en el bloque 50/55...") | |
| c_sha[50]['data'] = "Dato_Corrupto" | |
| c_hmac[55]['data'] = "Dato_Corrupto" | |
| # Volver a verificar | |
| res_sha, pos_sha = verificar_sha(c_sha) | |
| res_hmac, pos_hmac = verificar_hmac(c_hmac) | |
| print(f"\n--- RESULTADOS POST-ATAQUE ---") | |
| print(f"¿SHA-256 sigue siendo válido?: {res_sha} (Detectado fallo en bloque {pos_sha})") | |
| print(f"¿HMAC sigue siendo válido?: {res_hmac} (Detectado fallo en bloque {pos_hmac})") | |
| # --- RESULTADOS PARA 10000000 BLOQUES --- | |
| # SHA-256 Simple: 21.632728 seg | Peso Hash: 64 chars (Hex) | |
| # HMAC en Cadena: 51.909865 seg | Peso Hash: 64 chars (Hex) | |
| # Diferencia de tiempo: 139.96% más lento el HMAC | |
| # --- PRUEBA DE INTEGRIDAD INICIAL --- | |
| # Integridad SHA-256: True | |
| # Integridad HMAC: True | |
| # [!] Alterando datos en el bloque 50/55... | |
| # --- RESULTADOS POST-ATAQUE --- | |
| # ¿SHA-256 sigue siendo válido?: False (Detectado fallo en bloque 50) | |
| # ¿HMAC sigue siendo válido?: False (Detectado fallo en bloque 55) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment