📗SpiderCrypt API Documentation
Description
Welcome . In this doc you gonna learn how to use SpiderCrypt API for data security. It provides robust functionalities for encryption, decryption, hashing, signing, and verifying data, using shared authentication keys and user identifiers to ensure traceability and security for developers ,SME,individuals .
Classes and Methods
Class SpiderCrypt
SpiderCrypt
This class is the core of the SpiderCrypt API and enables all the main cryptographic operations.
Initialization
SpiderCrypt(secret_key: str)
Parameter:
secret_key
: Shared secret key used to initialize the class. It is required for all secure operations.
Main Methods
encrypt
encrypt(data: str, auth_key: str) -> bytes
Description: Encrypts sensitive data.
Parameters:
data
: Data to encrypt (string).auth_key
: Authentication key used for this operation.
Returns: Encrypted data as bytes.
decrypt
decrypt(encrypted_data: bytes, auth_key: str) -> str
Description: Decrypts previously encrypted data.
Parameters:
encrypted_data
: Encrypted data (as bytes).auth_key
: Authentication key used for this operation.
Returns: Decrypted data as a string.
hash_data
hash_data(data: str, auth_key: str) -> bytes
Description: Creates a unique hash of the data to ensure its integrity.
Parameters:
data
: Data to hash (string).auth_key
: Authentication key used for this operation.
Returns: Hashed value as bytes.
sign_data
sign_data(data: str, auth_key: str) -> bytes
Description: Generates a digital signature of the data to ensure its authenticity.
Parameters:
data
: Data to sign (string).auth_key
: Authentication key used for this operation.
Returns: Signature of the data as bytes.
verify_signature
verify_signature(data: str, signature: bytes, auth_key: str) -> bool
Description: Verifies if the signature of the data is valid.
Parameters:
data
: Original data (string).signature
: Signature to verify (as bytes).auth_key
: Authentication key used for this operation.
Returns: A boolean indicating if the signature is valid (
True
) or not (False
).
Error Handling
PermissionError
Raised when authentication fails (e.g., if auth_key
is incorrect).
Exception
Raised for any other non-specific errors (e.g., corrupted data or invalid format).
Example Usage
Here is a complete example of using the main features of the API:
from flask import Flask, request, jsonify
from spidercrypt import SpiderCrypt # Import the SpiderCrypt library
import os
app = Flask(__name__)
# Shared authentication key for security
auth_key = os.getenv('SECRET_KEY') # Secure secret key
# Initialize SpiderCrypt with the secret key for secure operations
cipher = SpiderCrypt(secret_key=auth_key)
@app.route("/encrypt", methods=["POST"])
def encrypt():
try:
data = request.json.get("data")
if not data :
return jsonify({"error": "Missing data"}), 400
encrypted_data = cipher.encrypt(data, auth_key)
return jsonify({"encrypted_data": encrypted_data.decode()})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/decrypt", methods=["POST"])
def decrypt():
try:
encrypted_data = request.json.get("encrypted_data")
if not encrypted_data :
return jsonify({"error": "Missing encrypted data "}), 400
app.logger.info(f"Decryption requested for the user with data: {encrypted_data}")
decrypted_data = cipher.decrypt(encrypted_data.encode(), auth_key)
app.logger.info(f"Successfully decrypted data: {decrypted_data}")
return jsonify({"decrypted_data": decrypted_data})
except ValueError as e:
app.logger.error(f"Value error: {str(e)}")
return jsonify({"error": f"Value error: {str(e)}"}), 400
except Exception as e:
app.logger.error(f"Internal error: {str(e)}")
return jsonify({"error": f"Internal error: {str(e)}"}), 500
@app.route("/hash", methods=["POST"])
def hash_data():
try:
data = request.json.get("data")
if not data :
return jsonify({"error": "Missing data "}), 400
hashed_data = cipher.hash_data(data, auth_key)
return jsonify({"hashed_data": hashed_data.hex()})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/sign", methods=["POST"])
def sign_data():
try:
data = request.json.get("data")
if not data :
return jsonify({"error": "Missing data "}), 400
signature = cipher.sign_data(data, auth_key)
return jsonify({"signature": signature.hex()})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/verify", methods=["POST"])
def verify_signature():
try:
data = request.json.get("data")
signature = request.json.get("signature")
if not data or not signature :
return jsonify({"error": "Missing data, signature"}), 400
is_valid = cipher.verify_signature(data, bytes.fromhex(signature), auth_key)
return jsonify({"is_valid": is_valid})
except Exception as e:
return jsonify({"error": str(e)}), 500
# Batch Encryption
@app.route("/batch_encrypt", methods=["POST"])
def batch_encrypt():
try:
data_list = request.json.get("data_list")
if not data_list :
return jsonify({"error": "Missing data list "}), 400
encrypted_data_list = cipher.batch_encrypt(data_list, auth_key)
return jsonify({"encrypted_data_list": encrypted_data_list})
except Exception as e:
return jsonify({"error": str(e)}), 500
# Start Flask server
if __name__ == '__main__':
app.run(debug=True)
Additional Notes
Ensure the
auth_key
remains strictly confidential.Test all operations before deploying them in a production environment.
Here some API :
Python
pip install spidercrypt
Java
Make sure to have the SpiderCrypt library as a .jar
file and add it to your project.
Ruby
gem install spidercrypt
Go
Use the Go package manager to import spidercrypt
.
go get github.com/spidercrypt/spidercrypt
3. Usage Examples
Python
from flask import Flask, request, jsonify
from spidercrypt import SpiderCrypt # Import the SpiderCrypt library
import os
app = Flask(__name__)
# Shared authentication key for security
auth_key = os.getenv('SECRET_KEY') # Secure secret key
# Initialize SpiderCrypt with the secret key for secure operations
cipher = SpiderCrypt(secret_key=auth_key)
@app.route("/encrypt", methods=["POST"])
def encrypt():
try:
data = request.json.get("data")
if not data :
return jsonify({"error": "Missing data"}), 400
encrypted_data = cipher.encrypt(data, auth_key)
return jsonify({"encrypted_data": encrypted_data.decode()})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/decrypt", methods=["POST"])
def decrypt():
try:
encrypted_data = request.json.get("encrypted_data")
if not encrypted_data :
return jsonify({"error": "Missing encrypted data "}), 400
app.logger.info(f"Decryption requested for the user with data: {encrypted_data}")
decrypted_data = cipher.decrypt(encrypted_data.encode(), auth_key)
app.logger.info(f"Successfully decrypted data: {decrypted_data}")
return jsonify({"decrypted_data": decrypted_data})
except ValueError as e:
app.logger.error(f"Value error: {str(e)}")
return jsonify({"error": f"Value error: {str(e)}"}), 400
except Exception as e:
app.logger.error(f"Internal error: {str(e)}")
return jsonify({"error": f"Internal error: {str(e)}"}), 500
@app.route("/hash", methods=["POST"])
def hash_data():
try:
data = request.json.get("data")
if not data :
return jsonify({"error": "Missing data "}), 400
hashed_data = cipher.hash_data(data, auth_key)
return jsonify({"hashed_data": hashed_data.hex()})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/sign", methods=["POST"])
def sign_data():
try:
data = request.json.get("data")
if not data :
return jsonify({"error": "Missing data "}), 400
signature = cipher.sign_data(data, auth_key)
return jsonify({"signature": signature.hex()})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/verify", methods=["POST"])
def verify_signature():
try:
data = request.json.get("data")
signature = request.json.get("signature")
if not data or not signature :
return jsonify({"error": "Missing data, signature"}), 400
is_valid = cipher.verify_signature(data, bytes.fromhex(signature), auth_key)
return jsonify({"is_valid": is_valid})
except Exception as e:
return jsonify({"error": str(e)}), 500
# Batch Encryption
@app.route("/batch_encrypt", methods=["POST"])
def batch_encrypt():
try:
data_list = request.json.get("data_list")
if not data_list :
return jsonify({"error": "Missing data list "}), 400
encrypted_data_list = cipher.batch_encrypt(data_list, auth_key)
return jsonify({"encrypted_data_list": encrypted_data_list})
except Exception as e:
return jsonify({"error": str(e)}), 500
# Start Flask server
if __name__ == '__main__':
app.run(debug=True)
Ruby
require 'sinatra'
require 'json'
require 'spidercrypt' # Ensure you have the SpiderCrypt gem installed
# Initialize SpiderCrypt with a secret key
$secret_key = 'your_secret_key' # Replace with actual secret key
$crypt = SpiderCrypt.new($secret_key)
# Encrypt route
post '/encrypt' do
data = JSON.parse(request.body.read)["data"]
halt 400, { error: "Missing data" }.to_json unless data
encrypted_data = $crypt.encrypt(data)
{ encrypted_data: encrypted_data }.to_json
end
# Decrypt route
post '/decrypt' do
encrypted_data = JSON.parse(request.body.read)["encrypted_data"]
halt 400, { error: "Missing encrypted data" }.to_json unless encrypted_data
decrypted_data = $crypt.decrypt(encrypted_data)
{ decrypted_data: decrypted_data }.to_json
end
# Hash route
post '/hash' do
data = JSON.parse(request.body.read)["data"]
halt 400, { error: "Missing data" }.to_json unless data
hashed_data = $crypt.hash(data)
{ hashed_data: hashed_data }.to_json
end
# Start Sinatra server
set :port, 8080
Go
package main
import (
"github.com/gin-gonic/gin"
"github.com/spidercrypt/spidercrypt" // Make sure the SpiderCrypt package is imported
"net/http"
"log"
)
var cipher *spidercrypt.SpiderCrypt
// Initialize SpiderCrypt (secret key can be retrieved from environment variable or config)
func init() {
cipher = spidercrypt.NewSpiderCrypt("your_secret_key") // Replace with actual secret key
}
func main() {
r := gin.Default()
// Encrypt route
r.POST("/encrypt", func(c *gin.Context) {
var request struct {
Data string `json:"data"`
}
if err := c.BindJSON(&request); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing data"})
return
}
encryptedData := cipher.Encrypt(request.Data)
c.JSON(http.StatusOK, gin.H{"encrypted_data": encryptedData})
})
// Decrypt route
r.POST("/decrypt", func(c *gin.Context) {
var request struct {
EncryptedData string `json:"encrypted_data"`
}
if err := c.BindJSON(&request); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing encrypted data"})
return
}
decryptedData := cipher.Decrypt(request.EncryptedData)
c.JSON(http.StatusOK, gin.H{"decrypted_data": decryptedData})
})
// Hash route
r.POST("/hash", func(c *gin.Context) {
var request struct {
Data string `json:"data"`
}
if err := c.BindJSON(&request); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing data"})
return
}
hashedData := cipher.HashData(request.Data)
c.JSON(http.StatusOK, gin.H{"hashed_data": hashedData})
})
// Start the Gin server
r.Run(":8080") // Default port 8080
}
Nodes.js
const express = require('express');
const bodyParser = require('body-parser');
const SpiderCrypt = require('spidercrypt'); // Import SpiderCrypt package
const app = express();
const port = 8080;
app.use(bodyParser.json());
// Initialize SpiderCrypt instance with secret key
const cipher = new SpiderCrypt("your_secret_key"); // Replace with actual secret key
// Encrypt route
app.post('/encrypt', (req, res) => {
const { data } = req.body;
if (!data) {
return res.status(400).json({ error: 'Missing data' });
}
const encryptedData = cipher.encrypt(data);
res.json({ encrypted_data: encryptedData });
});
// Decrypt route
app.post('/decrypt', (req, res) => {
const { encryptedData } = req.body;
if (!encryptedData) {
return res.status(400).json({ error: 'Missing encrypted data' });
}
const decryptedData = cipher.decrypt(encryptedData);
res.json({ decrypted_data: decryptedData });
});
// Hash route
app.post('/hash', (req, res) => {
const { data } = req.body;
if (!data) {
return res.status(400).json({ error: 'Missing data' });
}
const hashedData = cipher.hash(data);
res.json({ hashed_data: hashedData });
});
// Start the server
app.listen(port, () => {
console.log(`SpiderCrypt API running on port ${port}`);
});
This API offers a comprehensive set of cybersecurity features for the protection of sensitive data. It is designed to be easy to integrate into any application that requires encryption, hashing, and digital signature operations.
The four implementations allow flexibility according to needs:
Python (Flask) : More complete with additional features like batch encryption and key generation.
Go (Gin) : Faster and lighter for environments requiring increased performance.
Ruby (Sinatra) : Simple and fast to deploy, ideal for small secure applications. -
Node.js (Express) : Suitable for web applications and services requiring fast processing in JavaScript.
Last updated