Hash Generator API Examples
Complete code examples and integration guides for the Hash Generator API in multiple programming languages.Quick Examples
Generate MD5 Hash
Copy
curl "https://api.sinaty.business/hash/?text=hello&algorithm=md5"
Generate SHA-256 Hash with Salt
Copy
curl "https://api.sinaty.business/hash/?text=password&algorithm=sha256&salt=mysalt&iterations=1000"
Generate Multiple Hashes
Copy
curl "https://api.sinaty.business/hash/?text=hello&algorithm=sha1,sha256,sha512&format=hex"
JavaScript/Node.js Examples
Basic Hash Generation
Copy
async function generateHash(text, algorithm = 'sha256') {
try {
const response = await fetch(
`https://api.sinaty.business/hash/?text=${encodeURIComponent(text)}&algorithm=${algorithm}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.hash;
} catch (error) {
console.error('Error generating hash:', error);
return null;
}
}
// Usage
const hash = await generateHash('hello world', 'sha256');
console.log('Hash:', hash);
Hash with Salt and Iterations
Copy
async function generateSecureHash(text, algorithm = 'sha256', salt = null, iterations = 1000) {
try {
const params = new URLSearchParams({
text: text,
algorithm: algorithm,
iterations: iterations.toString()
});
if (salt) {
params.append('salt', salt);
}
const response = await fetch(
`https://api.sinaty.business/hash/?${params}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.hash;
} catch (error) {
console.error('Error generating secure hash:', error);
return null;
}
}
// Usage for password hashing
const passwordHash = await generateSecureHash('mypassword', 'sha256', 'mysalt', 10000);
console.log('Password hash:', passwordHash);
Multiple Algorithm Hashing
Copy
async function generateMultipleHashes(text, algorithms = ['md5', 'sha1', 'sha256']) {
try {
const response = await fetch(
`https://api.sinaty.business/hash/?text=${encodeURIComponent(text)}&algorithm=${algorithms.join(',')}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.hashes;
} catch (error) {
console.error('Error generating multiple hashes:', error);
return {};
}
}
// Usage
const hashes = await generateMultipleHashes('hello world', ['md5', 'sha256', 'sha512']);
console.log('Multiple hashes:', hashes);
Different Output Formats
Copy
async function generateHashInFormat(text, algorithm = 'sha256', format = 'hex') {
try {
const response = await fetch(
`https://api.sinaty.business/hash/?text=${encodeURIComponent(text)}&algorithm=${algorithm}&format=${format}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.hash;
} catch (error) {
console.error('Error generating hash:', error);
return null;
}
}
// Usage with different formats
const hexHash = await generateHashInFormat('hello', 'sha256', 'hex');
const base64Hash = await generateHashInFormat('hello', 'sha256', 'base64');
const binaryHash = await generateHashInFormat('hello', 'sha256', 'binary');
console.log('Hex hash:', hexHash);
console.log('Base64 hash:', base64Hash);
console.log('Binary hash:', binaryHash);
Python Examples
Basic Hash Generation
Copy
import requests
import json
def generate_hash(text, algorithm='sha256'):
"""Generate a hash for the given text."""
try:
url = "https://api.sinaty.business/hash/"
params = {
'text': text,
'algorithm': algorithm
}
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
return data['hash']
except requests.exceptions.RequestException as e:
print(f"Error generating hash: {e}")
return None
# Usage
hash_value = generate_hash('hello world', 'sha256')
print(f"Hash: {hash_value}")
Secure Hash with Salt
Copy
def generate_secure_hash(text, algorithm='sha256', salt=None, iterations=1000):
"""Generate a secure hash with salt and iterations."""
try:
url = "https://api.sinaty.business/hash/"
params = {
'text': text,
'algorithm': algorithm,
'iterations': iterations
}
if salt:
params['salt'] = salt
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
return data['hash']
except requests.exceptions.RequestException as e:
print(f"Error generating secure hash: {e}")
return None
# Usage for password hashing
password_hash = generate_secure_hash('mypassword', 'sha256', 'mysalt', 10000)
print(f"Password hash: {password_hash}")
Multiple Algorithm Hashing
Copy
def generate_multiple_hashes(text, algorithms=None):
"""Generate hashes using multiple algorithms."""
if algorithms is None:
algorithms = ['md5', 'sha1', 'sha256']
try:
url = "https://api.sinaty.business/hash/"
params = {
'text': text,
'algorithm': ','.join(algorithms)
}
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
return data['hashes']
except requests.exceptions.RequestException as e:
print(f"Error generating multiple hashes: {e}")
return {}
# Usage
hashes = generate_multiple_hashes('hello world', ['md5', 'sha256', 'sha512'])
for algorithm, hash_value in hashes.items():
print(f"{algorithm}: {hash_value}")
File Hashing
Copy
def hash_file_content(file_path, algorithm='sha256'):
"""Hash the content of a file."""
try:
with open(file_path, 'rb') as file:
content = file.read().decode('utf-8')
return generate_hash(content, algorithm)
except Exception as e:
print(f"Error hashing file: {e}")
return None
# Usage
file_hash = hash_file_content('document.txt', 'sha256')
print(f"File hash: {file_hash}")
PHP Examples
Basic Hash Generation
Copy
<?php
function generateHash($text, $algorithm = 'sha256') {
$url = "https://api.sinaty.business/hash/";
$params = http_build_query([
'text' => $text,
'algorithm' => $algorithm
]);
$fullUrl = $url . '?' . $params;
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => 'Content-Type: application/json'
]
]);
$response = file_get_contents($fullUrl, false, $context);
if ($response === false) {
return null;
}
$data = json_decode($response, true);
return $data['hash'] ?? null;
}
// Usage
$hash = generateHash('hello world', 'sha256');
echo "Hash: " . $hash . "\n";
?>
Secure Hash with Salt
Copy
<?php
function generateSecureHash($text, $algorithm = 'sha256', $salt = null, $iterations = 1000) {
$url = "https://api.sinaty.business/hash/";
$params = [
'text' => $text,
'algorithm' => $algorithm,
'iterations' => $iterations
];
if ($salt) {
$params['salt'] = $salt;
}
$fullUrl = $url . '?' . http_build_query($params);
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => 'Content-Type: application/json'
]
]);
$response = file_get_contents($fullUrl, false, $context);
if ($response === false) {
return null;
}
$data = json_decode($response, true);
return $data['hash'] ?? null;
}
// Usage for password hashing
$passwordHash = generateSecureHash('mypassword', 'sha256', 'mysalt', 10000);
echo "Password hash: " . $passwordHash . "\n";
?>
Go Examples
Basic Hash Generation
Copy
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
type HashResponse struct {
Hash string `json:"hash"`
}
func generateHash(text, algorithm string) (string, error) {
baseURL := "https://api.sinaty.business/hash/"
params := url.Values{}
params.Add("text", text)
params.Add("algorithm", algorithm)
fullURL := baseURL + "?" + params.Encode()
resp, err := http.Get(fullURL)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
var response HashResponse
err = json.Unmarshal(body, &response)
if err != nil {
return "", err
}
return response.Hash, nil
}
func main() {
hash, err := generateHash("hello world", "sha256")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Hash: %s\n", hash)
}
Ruby Examples
Basic Hash Generation
Copy
require 'net/http'
require 'json'
require 'uri'
def generate_hash(text, algorithm = 'sha256')
url = "https://api.sinaty.business/hash/"
uri = URI(url)
params = {
'text' => text,
'algorithm' => algorithm
}
uri.query = URI.encode_www_form(params)
response = Net::HTTP.get_response(uri)
if response.is_a?(Net::HTTPSuccess)
data = JSON.parse(response.body)
return data['hash']
else
puts "Error: #{response.code} - #{response.message}"
return nil
end
rescue => e
puts "Error generating hash: #{e.message}"
return nil
end
# Usage
hash = generate_hash('hello world', 'sha256')
puts "Hash: #{hash}"
cURL Examples
Basic Hash Generation
Copy
# Generate MD5 hash
curl "https://api.sinaty.business/hash/?text=hello&algorithm=md5"
# Generate SHA-256 hash
curl "https://api.sinaty.business/hash/?text=hello&algorithm=sha256"
# Generate SHA-512 hash
curl "https://api.sinaty.business/hash/?text=hello&algorithm=sha512"
Advanced Hash Generation
Copy
# Hash with salt and iterations
curl "https://api.sinaty.business/hash/?text=password&algorithm=sha256&salt=mysalt&iterations=1000"
# Multiple algorithms
curl "https://api.sinaty.business/hash/?text=hello&algorithm=md5,sha1,sha256"
# Different output formats
curl "https://api.sinaty.business/hash/?text=hello&algorithm=sha256&format=base64"
curl "https://api.sinaty.business/hash/?text=hello&algorithm=sha256&format=binary"
Integration Examples
React Component for File Hashing
Copy
import React, { useState } from 'react';
function FileHasher() {
const [file, setFile] = useState(null);
const [hash, setHash] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const handleFileChange = (event) => {
setFile(event.target.files[0]);
};
const generateFileHash = async (algorithm = 'sha256') => {
if (!file) return;
setLoading(true);
setError(null);
try {
const reader = new FileReader();
reader.onload = async (e) => {
const content = e.target.result;
const response = await fetch(
`https://api.sinaty.business/hash/?text=${encodeURIComponent(content)}&algorithm=${algorithm}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setHash(data.hash);
};
reader.readAsText(file);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
return (
<div>
<h2>File Hash Generator</h2>
<input type="file" onChange={handleFileChange} />
<button
onClick={() => generateFileHash('sha256')}
disabled={!file || loading}
>
{loading ? 'Generating...' : 'Generate Hash'}
</button>
{hash && <p>Hash: {hash}</p>}
{error && <p style={{color: 'red'}}>Error: {error}</p>}
</div>
);
}
export default FileHasher;
Express.js Password Hashing Middleware
Copy
const express = require('express');
const fetch = require('node-fetch');
const app = express();
app.use(express.json());
// Middleware to hash passwords
async function hashPassword(req, res, next) {
try {
const { password } = req.body;
if (!password) {
return res.status(400).json({ error: 'Password is required' });
}
// Generate a random salt
const salt = Math.random().toString(36).substring(2, 15);
const params = new URLSearchParams({
text: password,
algorithm: 'sha256',
salt: salt,
iterations: '10000'
});
const response = await fetch(
`https://api.sinaty.business/hash/?${params}`
);
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
const data = await response.json();
req.hashedPassword = data.hash;
req.salt = salt;
next();
} catch (error) {
res.status(500).json({ error: error.message });
}
}
// Route for user registration
app.post('/register', hashPassword, (req, res) => {
// Save user with hashed password and salt
const user = {
username: req.body.username,
password: req.hashedPassword,
salt: req.salt
};
// Here you would save to database
console.log('User registered:', user);
res.json({ message: 'User registered successfully' });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Data Integrity Verification
Copy
async function verifyDataIntegrity(originalData, expectedHash, algorithm = 'sha256') {
try {
const response = await fetch(
`https://api.sinaty.business/hash/?text=${encodeURIComponent(originalData)}&algorithm=${algorithm}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
const currentHash = data.hash;
return {
isValid: currentHash === expectedHash,
currentHash: currentHash,
expectedHash: expectedHash
};
} catch (error) {
console.error('Error verifying data integrity:', error);
return { isValid: false, error: error.message };
}
}
// Usage
const data = 'Hello, World!';
const expectedHash = 'a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e';
const result = await verifyDataIntegrity(data, expectedHash, 'sha256');
console.log('Data integrity check:', result);
Common Use Cases
Password Security
Copy
// Generate secure password hash
async function hashPassword(password, salt = null) {
if (!salt) {
salt = Math.random().toString(36).substring(2, 15);
}
const hash = await generateSecureHash(password, 'sha256', salt, 10000);
return { hash, salt };
}
// Verify password
async function verifyPassword(password, storedHash, salt) {
const hash = await generateSecureHash(password, 'sha256', salt, 10000);
return hash === storedHash;
}
File Integrity
Copy
// Generate file checksum
async function generateFileChecksum(fileContent, algorithm = 'sha256') {
return await generateHash(fileContent, algorithm);
}
// Verify file integrity
async function verifyFileIntegrity(fileContent, expectedChecksum, algorithm = 'sha256') {
const actualChecksum = await generateFileChecksum(fileContent, algorithm);
return actualChecksum === expectedChecksum;
}
API Request Signing
Copy
// Sign API request
async function signRequest(data, secretKey) {
const message = JSON.stringify(data) + secretKey;
return await generateHash(message, 'sha256');
}
// Verify request signature
async function verifyRequestSignature(data, signature, secretKey) {
const expectedSignature = await signRequest(data, secretKey);
return signature === expectedSignature;
}