Full completed project

This commit is contained in:
2025-02-10 12:37:33 +00:00
commit b9abff8012
229 changed files with 16866 additions and 0 deletions

View File

@@ -0,0 +1 @@
__all__ = ['uuid', 'univ', 'hash']

View File

@@ -0,0 +1,22 @@
# include<string.h>
# include<string>
# include<cmath>
typedef long long int Lint;
extern "C" Lint hash(char* str) {
Lint m = std::pow(10,7) + 7;
int p = 97;
Lint total = 0;
for (int i=0; i<strlen(str); i++) {
total += (int(str[i]) - 32) * pow(p,i);
}
Lint result = total % m;
return result;
}
extern "C" Lint printc(char* str) {
int num = strlen(str);
return num;
}

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,155 @@
from modules.user import info as user_info
from modules.algorithms.univ import dict_key_verify
from modules.algorithms.uuid import hash_string
class User():
def __init__(self, username, origin=False):
self.username = username
self.friends = user_info.friend(username=username)
self.origin = origin
self.exclude = []
self.count = 1
self.depth = 0
self.score = 0
self.friend_list = []
def find_friends(self, exclude=[], **kwargs):
self.exclude += exclude
friends = self.friends.get()
if dict_key_verify(friends, "friends"):
self.__organise_friends(friends['friends'])
self.__find_excluded()
def __organise_friends(self, friends, **kwargs):
# used to create the user objects of friends
for friend in friends:
if friend['username'] not in self.exclude:
self.friend_list.append(User(friend['username']))
def __find_excluded(self):
# gathers the users to be excluded from the next nodes neigbours and sets this list = to self.exclude
# this exclude list includes the previously passed exclude list
if self.username not in self.exclude:
self.exclude.append(self.username)
if self.origin:
self.exclude = self.exclude + [friend.username for friend in self.friend_list]
requests = self.friends.get_requests()
if dict_key_verify(requests, "requests"):
self.exclude = self.exclude + [request for request in requests["requests"]]
def __hash__(self):
obj_hash = hash_string(self.username)
return obj_hash
class Graph():
def __init__(self, username):
self.origin_user = User(username, True)
self.graph = [[]] * (10**7+7)
self.friend_directory = [None] * (10**7+7)
self.friend_directory[hash(self.origin_user)] = self.origin_user
self.exclude = []
def generate(self, depth=1):
self.origin_user.depth = depth-1
self.__add_user_friends(self.origin_user, self.origin_user, depth)
def __add_user_friends(self, origin, source, depth):
origin.find_friends(self.exclude + [source.username])
if hash(self.origin_user) == hash(origin):
self.exclude += origin.exclude
for friend in origin.friend_list:
friend_hash = hash(friend)
self.__add_edge(hash(origin), friend_hash)
# if this user already exists in the graph add to their count in the user's object
# this count keeps track of how many other users friend lists a certain user is
if self.friend_directory[friend_hash]:
self.friend_directory[friend_hash].count += 1
else:
self.friend_directory[friend_hash] = friend
if depth-1 > 0:
# recursively calls the function until the depth is 0.
self.__add_user_friends(friend, origin, depth-1)
def __add_edge(self, node, edge):
# using the + operator on the lists since .append() has some undefined behaviour on large arrays.
self.graph[node] = self.graph[node] + [edge]
def bft(self):
self.visted = []
# adds the hash of the selected orgin user to the edge queue
self.edge_queue = [hash(self.origin_user)]
self.__visit(self.edge_queue[0])
def __visit(self, origin):
# the origin is a number and so can be used as an index for the graph array
start_pos = self.graph[origin]
self.__on_visit(origin)
# adds the current node to the vistsed lists and removes it from the queue
self.edge_queue.pop(len(self.edge_queue)-1)
self.visted.append(origin)
for neigbour in start_pos:
neigbour_obj = self.friend_directory[neigbour]
origin_obj = self.friend_directory[origin]
# checks if the node has been visted yet, if not adds it to the edge queue and assigns it a depth from the origin
if neigbour not in self.visted and neigbour not in self.edge_queue:
neigbour_obj.depth = origin_obj.depth - 1
self.edge_queue = [neigbour] + self.edge_queue
if len(self.edge_queue) > 0:
# recursively calls this method until the edge_queue is empty
self.__visit(self.edge_queue[len(self.edge_queue)-1])
def __on_visit(self, origin):
origin_obj = self.friend_directory[origin]
# each node is only visited once in the graph so the count is calculated when constructing the graph
origin_obj.score = origin_obj.depth * origin_obj.count
def recomend_friends(self):
self.recomendations = []
# removing the user requesting the recomendations and their friends from the visited list
# this is done so that the user or people who are already friends of the user dont get recomended
possible = []
for user in self.visted:
user_obj = self.friend_directory[user]
if user_obj.username not in self.exclude:
possible = possible + [user]
while len(self.recomendations) != len(possible):
largest = User(username="")
largest.score = -1
for friend in possible:
friend_obj = self.friend_directory[friend]
if friend_obj not in self.recomendations and friend_obj.score > largest.score:
largest = friend_obj
self.recomendations.append(largest)
def recomend_friend(username, amount=1, depth=1):
if not (depth >= 1 and depth <= 4):
depth = 4
friend_graph = Graph(username)
friend_graph.generate(depth)
friend_graph.bft()
friend_graph.recomend_friends()
recomended = [{'username': recomended.username} for recomended in friend_graph.recomendations[:amount]]
return recomended
def main():
result = recomend_friend("Jack", 3, 4)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,390 @@
#include <cstdlib>
# include<iostream>
# include<string>
# include<random>
# include<cmath>
# include<array>
#include <fstream>
using namespace std;
typedef long int Lint; // 64 bits
typedef double Ldouble;
struct security {
int num_shares;
int num_required;
};
struct shareStruct {
int x;
Lint y;
};
bool isPrime(Lint n) {
int flag = 0;
for (int i = 2; i <= n / i; ++i) {
if (n % i == 0) {
flag = 1;
break;
}
}
if (flag == 0) return true;
else return false;
}
Lint genRandInt(int n) {
// Returns a random number
// between 2**(n-1)+1 and 2**n-1
//long max = (long)powl(2, n) - 1;
//long min = (long)powl(2, n - 1) + 1;
long max = (long)pow(2, n) - 1;
long min = (long)pow(2, n - 1) + 1;
Lint result = min + (rand() % ( max - min + 1 ) );
return result;
}
Lint genPrime() {
Lint prime = 10;
while (isPrime(prime) == false) {
int complexity = 50;
prime = genRandInt(complexity);
}
return prime;
}
int* encodeSecret(int* poly, const int secret, const int num_required) {
poly[num_required-1] = secret;
return poly;
}
Lint getPolyY(const int* poly, int poly_len, int poly_x, const Lint prime) {
Lint total = 0;
Lint poly_y = 0;
for (int i=0; i<poly_len+1; i++) {
int power = poly_len - i;
int coefficient = poly[i];
poly_y = coefficient * pow(poly_x, power);
total = total + poly_y;
}
return total;
}
shareStruct* genShares(int num_shares, int num_required, const int* poly, const Lint prime){
shareStruct* shares = new shareStruct[num_shares];
for (int i=1; i<=num_shares; i++) {
shareStruct share;
share.x = i;
share.y = getPolyY(poly, num_required-1, share.x, prime);
shares[i-1] = share;
}
return shares;
}
int* genPoly(int degree, const Lint prime, const Lint secret) {
int* poly = new int[degree];
for (int i = 0; i < degree; i++) {
int random_num = genRandInt(10);
poly[i] = prime % random_num;
}
return poly;
}
// solving polynomials
struct inputStruct {
int required;
shareStruct* shares;
};
struct polyTerm {
Lint coefficient;
int power;
};
struct linearEquation {
shareStruct point;
polyTerm* terms;
};
linearEquation* constructEquations(const int required, shareStruct shares[]) {
linearEquation* equations = new linearEquation[required];
shareStruct share;
polyTerm term;
for (int i = 0; i < required; i++) {
share = shares[i];
linearEquation equation;
polyTerm* terms = new polyTerm[required];
for (int j = 0; j < required; j++) {
term.power = required - 1 - j;
terms[j] = term;
}
equation.terms = terms;
equation.point.x = share.x;
equation.point.y = share.y;
equations[i] = equation;
// dont delete terms from memory as its referanced in equations
}
return equations;
}
struct matrix{
Lint** matrix;
int dimension_x;
int dimension_y;
};
struct matrix_system {
matrix A;
matrix B;
matrix X;
};
matrix_system formMatrix(const linearEquation* equations, int required) {
Lint** matrixA = new Lint*[required];
Lint** matrixB = new Lint*[required];
for (int i=0; i < required; i++) {
linearEquation equation = equations[i];
Lint* lineA = new Lint[required];
for (int j=0; j < required; j++) {
lineA[j] = pow(equation.point.x, equation.terms[j].power);
}
matrixA[i] = lineA;
Lint* lineB = new Lint[1];
lineB[0] = equation.point.y;
matrixB[i] = lineB;
}
matrix matrixA_data; matrix matrixB_data;
matrixA_data.matrix = matrixA; matrixB_data.matrix = matrixB;
matrixA_data.dimension_x = required; matrixB_data.dimension_x = 1;
matrixA_data.dimension_y = required; matrixB_data.dimension_y = required;
matrix_system matricies;
matricies.A = matrixA_data; matricies.B = matrixB_data;
return matricies;
}
Lint** findMinor(Lint** matrixA, const int dimension, const int pos_x, const int pos_y) {
Lint** matrixB = new Lint*[dimension-1];
int matrixB_pos_x = 0; int matrixB_pos_y = 0;
for (int i=0; i<dimension; i++) {
Lint* line = new Lint[dimension-1];
for (int j=0; j<dimension; j++) {
if (i != pos_y and j != pos_x) {
line[matrixB_pos_x] = matrixA[i][j];
matrixB_pos_x++;
}
}
if (matrixB_pos_x != 0) {
matrixB[matrixB_pos_y] = line;
matrixB_pos_y++;
}
else {
delete[] line;
}
matrixB_pos_x = 0;
}
return matrixB;
}
Lint findDet(Lint** matrixA, const int dimension) {
Lint det = 0;
if (dimension == 0) {
det = 1;
}
else if (dimension == 1) {
det = matrixA[0][0];
}
else if (dimension == 2) {
det = matrixA[0][0] * matrixA[1][1] - matrixA[0][1] * matrixA[1][0];
}
else {
for (int i=0; i<dimension; i++) {
// reuse form matrix? pottentially split it up into formMatrixA and formMatrixB?
Lint** matrixB = findMinor(matrixA, dimension, i, 0);
Lint matrixB_det = findDet(matrixB, dimension-1);
Lint term = matrixA[0][i] * matrixB_det;
if ((i+1)%2 == 0) {
term = 0-term;
}
det = det + term;
}
}
return det;
}
matrix formMatrixCofactors(Lint** matrixA, const int dimension) {
Lint** matrixB = new Lint*[dimension];
for (int i=0; i<dimension; i++) {
Lint* line = new Lint[dimension];
int sign = 1;
if ((i+1)%2 == 0) {
sign = -1;
}
for (int j=0; j<dimension; j++) {
Lint** minor = findMinor(matrixA, dimension, j, i);
Lint cofactor = findDet(minor, dimension-1) * sign;
sign = -sign;
line[j] = cofactor;
}
matrixB[i] = line;
}
matrix matrix_data; matrix_data.matrix = matrixB;
matrix_data.dimension_x = dimension; matrix_data.dimension_y = dimension;
return matrix_data;
}
matrix transposeMatrix(Lint** cofactors, const int dimension) {
Lint** matrixB = new Lint*[dimension];
for (int i=0; i<dimension; i++) {
Lint* line = new Lint[dimension];
for (int j=0; j<dimension; j++) {
line[j] = cofactors[j][i];
}
matrixB[i] = line;
}
matrix matrixB_data; matrixB_data.matrix = matrixB;
matrixB_data.dimension_x = dimension; matrixB_data.dimension_y = dimension;
return matrixB_data;
}
struct float_matrix{
Ldouble** matrix;
int dimension_x;
int dimension_y;
};
struct float_matrix_system {
matrix A;
matrix B;
matrix X;
};
float_matrix multiplyConstant(matrix matrixA_data, const int dimension, const Lint det) {
Ldouble** matrixB = new Ldouble*[dimension];
Lint** matrixA = matrixA_data.matrix;
for (int i=0; i<dimension; i++) {
Ldouble* line = new Ldouble[dimension];
for (int j=0; j<dimension; j++) {
line[j] = (1.0/det) * matrixA[i][j];
}
matrixB[i] = line;
}
float_matrix matrixB_data; matrixB_data.matrix = matrixB;
matrixB_data.dimension_x = matrixA_data.dimension_x; matrixB_data.dimension_y = matrixA_data.dimension_y;
return matrixB_data;
}
float_matrix multiplyMatricies(float_matrix inverseA_data, matrix matrixB_data) {
int dimension_x = inverseA_data.dimension_x;
int dimension_y = inverseA_data.dimension_y;
Ldouble** matrixC = new Ldouble*[matrixB_data.dimension_y];
Ldouble** inverseA = inverseA_data.matrix;
Lint** matrixB = matrixB_data.matrix;
for (int i=0; i<dimension_y; i++) {
Ldouble* line = new Ldouble[0];
Ldouble result = 0;
for (int j=0; j<dimension_x; j++) {
result = result + inverseA[i][j] * matrixB[j][0];
}
line[0] = result;
matrixC[i] = line;
}
float_matrix matrixC_data; matrixC_data.matrix = matrixC;
matrixC_data.dimension_x = matrixB_data.dimension_x; matrixC_data.dimension_y = matrixB_data.dimension_y;
return matrixC_data;
}
Lint** StructToArray(shareStruct* struct_array, int len_array) {
Lint** array = new Lint*[len_array];
for (int i=0; i<len_array; i++) {
array[i] = new Lint[2];
array[i][0] = struct_array[i].x;
array[i][1] = struct_array[i].y;
}
return array;
}
shareStruct* ArrayToStruct(Lint** array, int len_array) {
shareStruct* share_array = new shareStruct[len_array];
for (int i=0; i<len_array; i++) {
shareStruct share;
share.x = array[i][0];
share.y = array[i][1];
share_array[i] = share;
}
return share_array;
}
void writeShares(shareStruct* shares, const int num_shares, const int num_required, string root_path) {
cout << root_path << endl;
for (int i=0; i<num_shares; i++) {
shareStruct share = shares[i];
string share_path = root_path + "share-" + to_string(share.x) + ".txt";
ofstream share_file(share_path);
share_file << "Share number: " << share.x << endl;
share_file << "Share secret: " << share.y << endl;
share_file << "Minimum share required: " << to_string(num_required) << endl << endl;
share_file << "IMPORTANT: Please remind your admin that its there job to distribute and delete shares from the server";
}
}
extern "C" Lint solveInternal(shareStruct* shares, int required) {
inputStruct inputs;
inputs.shares = shares;
inputs.required = required;
linearEquation* equations = new linearEquation[inputs.required];
equations = constructEquations(inputs.required, inputs.shares);
matrix_system matricies = formMatrix(equations, inputs.required);
delete[] equations;
Lint det = findDet(matricies.A.matrix, matricies.A.dimension_x);
matrix cofactors = formMatrixCofactors(matricies.A.matrix, matricies.A.dimension_x);
matrix transposition = transposeMatrix(cofactors.matrix, cofactors.dimension_x);
float_matrix inverseA = multiplyConstant(transposition, transposition.dimension_x, det);
float_matrix matrixC = multiplyMatricies(inverseA, matricies.B);
Lint secret = matrixC.matrix[matrixC.dimension_y-1][0];
return secret;
}
extern "C" void newSecretInternal(const Lint secret, const int num_shares, const int num_required, char* root_path) {
string str(root_path);
const Lint prime = genPrime();
int* poly = genPoly(num_required-1, prime, secret);
poly = encodeSecret(poly, secret, num_required);
shareStruct* shares = genShares(num_shares, num_required, poly, prime);
writeShares(shares, num_shares, num_required, root_path);
}
int main() {
}

View File

@@ -0,0 +1,47 @@
# checks a string for illegal characters
# string = string to be checked
# allow_chars = allowed characters should be passed as a string
def char_check(string, allow_chars):
# default allow_chars value
if allow_chars == None:
allow_chars = ascii_letters + digits
#allowed_char = ascii_letters + digits + "_" + "-"
if set(string).difference(allow_chars):
return True
else:
return False
def dict_key_verify(dictionary, keys, mode="and", *args, **kwargs):
# checks if the dictionary exists, if the key exists as a field and if that fields value is not none
# can be used to check if multiple keys exist
if mode != "and" and mode != "or":
mode = "and"
if type(keys) != list:
keys = [keys]
verified = []
if type(keys) != list:
keys = [keys]
for key in keys:
if type(dictionary) != dict or key not in dictionary or not dictionary[key]:
verified.append(False)
else:
verified.append(True)
if mode == "and":
if all(verified) == True:
return True
if mode == "or":
if True in verified:
return True
return False
if __name__ == "__main__":
data = {'name': "joe", 'job': "cuck", 'age': "69"}
answer = dict_key_verify(data, ['job', 'names'], "and")
print(answer)

View File

@@ -0,0 +1,102 @@
import random
import ctypes
import pathlib
import hashlib
# RBP
import time
# RBP
def bin_to_hex(byte):
byte_hex = ""
total = 0
for i, bit in enumerate(byte):
total += int(bit) * 2 ** i
first_place = total // 16
second_place = total - first_place * 16
places = [first_place, second_place]
for i, place in enumerate(places):
if place < 10:
byte_hex += str(place)
else:
byte_hex += chr(65 + place - 10)
return byte_hex.lower()
def den_to_bin(number):
byte_string = ""
result = 2
power = 0
# finds the greatest power of 2 that can fit in the number
# this defines the length of the binary number
while result > 0:
result = number // 2**power
if result == 0:
break
power += 1
for i in range(power-1, -1, -1):
bit = number // 2**i
number -= bit * 2**i
byte_string += str(bit)
return byte_string
def set_bits(binary, num_bits):
for i in range(num_bits - len(binary)):
binary += "0"
return binary
#uuid START
def generate():
byte_list = []
# generates 16 8 bit numbers as strings
for i in range(16):
number = random.randint(0, 255)
bits = den_to_bin(number)
byte = set_bits(bits , 8)
byte_list.append(byte)
# setting certain places as pre-defined, as stated by the UUID4 spec (see apendix)
byte_list[6] = byte_list[6][:4] + "0010"
byte_list[8] = byte_list[8][:6] + "01"
# UUIDs are always shown in terms of hex
hex_string = ""
for byte_index, byte in enumerate(byte_list):
byte_hex = bin_to_hex(byte)
# adds the dashes in the indexes as required by the UUID4 spec
if byte_index in [4, 6, 8, 10]:
hex_string += "-"
hex_string += byte_hex
return hex_string
#uuid END
#string hash START
def hash_string(string):
string = string.replace("-", "0")
string = string.replace("_", "0")
libname = pathlib.Path().absolute() / "modules/algorithms/libcpphash.so"
c_lib = ctypes.CDLL(libname)
charptr = ctypes.POINTER(ctypes.c_char)
c_lib.printc.argtypes = [charptr]
c_lib.printc.restypes = int
result = c_lib.hash(ctypes.c_char_p(string.encode('utf-8')))
return result
def long_hash(string):
result = hashlib.sha256(string.encode('utf-8'))
result = result.hexdigest()
return result
# string hash END
if __name__ == "__main__":
result = hash_string("hello")
print(result)