logo

Seznam pro vývojáře

Identita

Seznam pro vývojářeIdentitaHashovací funkce

Hashovací funkce

Ukázky kódů pro hashování v různých jazycích. Každá metoda obsahuje jediný parametr, ve kterém očekává hodnotu v "plaintextu".

Validace hodnoty vkládané do parametru funkce je silně doporučena.

Ukázky kódů

JavaScript

const crypto = require('crypto');

function hashValue(value) {
    value = value.trim().toLowerCase();
    const utf8Value = Buffer.from(value, 'utf-8');
    const hash = crypto.createHash('sha256').update(utf8Value).digest('hex');
    return hash;
}

Python

import hashlib

def hash_value(value):
    value = value.strip().lower()
    utf8_value = value.encode('utf-8')
    value_hash = hashlib.sha256(utf8_value).hexdigest()
    return value_hash

PHP

function hashValue($value){
    $value = strtolower(trim($value));
    $hash = hash('sha256', $value);
    return $hash;
}

Java

import java.security.MessageDigest;
import java.nio.charset.StandardCharsets;
import java.math.BigInteger;

public static String hashValue(String value) {
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(value.trim().toLowerCase().getBytes(StandardCharsets.UTF_8));
        return String.format("%064x", new BigInteger(1, hash));
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

C#

using System;
using System.Security.Cryptography;
using System.Text;

public static string HashValue(string value)
{
    using (var sha = SHA256.Create())
    {
        byte[] textData = Encoding.UTF8.GetBytes(value.Trim().ToLower());
        byte[] hash = sha.ComputeHash(textData);
        return BitConverter.ToString(hash).Replace("-", String.Empty).ToLower();
    }
}