From e536afb33a080aa2a0da21bff55d552ecab13b3a Mon Sep 17 00:00:00 2001 From: Thomas Hassenstein <2021544@stud.hs-mannheim.de> Date: Thu, 8 Jun 2023 21:24:01 +0200 Subject: [PATCH] =?UTF-8?q?Dateien=20hochladen=20nach=20=E2=80=9EREST?= =?UTF-8?q?=E2=80=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit vorläufigen stand hochladen (mit allen Logogrößen) --- REST/I2C_Function.py | 156 +++++++++++++++++++++++++++++++++++++++++++ REST/app.py | 86 ++++++++++++++++++++++++ REST/index.html | 82 +++++++++++++++++++++++ REST/logomiddle.png | Bin 0 -> 1814 bytes REST/logosmall.png | Bin 0 -> 776 bytes 5 files changed, 324 insertions(+) create mode 100644 REST/I2C_Function.py create mode 100644 REST/app.py create mode 100644 REST/logomiddle.png create mode 100644 REST/logosmall.png diff --git a/REST/I2C_Function.py b/REST/I2C_Function.py new file mode 100644 index 0000000..78448bb --- /dev/null +++ b/REST/I2C_Function.py @@ -0,0 +1,156 @@ +import os +import time +import json +from smbus import SMBus +from StartUpTest import StartUPTest +from TotOnline import TotOnline + +def read_data(num_numbers, bits_per_number): + addr = 0x8 + bus = SMBus(1) + + # Calculate the total number of bytes required to accommodate the desired number of bits + total_bytes = (num_numbers * bits_per_number + 7) // 8 + + # Define the filename + filename = f'{num_numbers}numbers_{bits_per_number}bits.bin' + + with open(filename, 'wb') as file: + bytes_received = 0 + while bytes_received < total_bytes: + # Read a byte from the serial port + data = bus.read_byte(addr) + file.write(bytes([data])) + bytes_received += 1 + time.sleep(0.0000001) + + return filename + +def convert_to_hex(binary_filename, num_numbers, bits_per_number): + with open(binary_filename, 'r') as f: + # Read the contents of the file + binary_content = f.read() + + # Calculate the number of bits per chunk + bits_per_chunk = len(binary_content) // num_numbers + + # Divide the binary content into equal chunks + binary_chunks = [binary_content[i * bits_per_chunk:(i + 1) * bits_per_chunk] for i in range(num_numbers)] + + # Calculate the number of hexadecimal digits per chunk + hex_digits_per_chunk = (bits_per_chunk + 3) // 4 # Round up to the nearest integer + + # Convert each binary chunk to a hexadecimal string with leading zeros + hex_chunks = [format(int(chunk, 2), f'0{hex_digits_per_chunk}X') for chunk in binary_chunks] + + # Write the hex chunks to the file with separators and newlines + hex_filename = f'{num_numbers}numbers_{bits_per_number}bits.txt' + with open(hex_filename, 'w') as f: + for i in range(num_numbers): + hex_number = hex_chunks[i] + # write the separator between numbers except for the last one + if i != num_numbers - 1: + hex_number += ';' + f.write(hex_number) + + return hex_filename + + +def convert_to_binary(filename, num_numbers, bits_per_number): + with open(filename, 'rb') as f: + # Read the contents of the file as bytes + content = f.read() + + # Convert the bytes to a string of binary digits + binary_str = ''.join(format(byte, '08b') for byte in content) + + # Truncate the binary string to the desired length + truncated_binary_str = binary_str[:num_numbers * bits_per_number] + + # Write the truncated binary string back to the file with separators + binary_filename = f'{num_numbers}numbers_{bits_per_number}bits_binary.txt' + with open(binary_filename, 'w') as f: + for i in range(0, len(truncated_binary_str), bits_per_number): + binary_number = truncated_binary_str[i:i+bits_per_number] + f.write(binary_number) + + return binary_filename + + +def process_data_in_chunks(data, chunk_size=1000000): + chunks = [data[i:i+chunk_size] for i in range(0, len(data), chunk_size)] + return chunks + +def perform_startup_tests(filename): + with open(filename, 'rb') as f: + # Read the contents of the file as bytes + content = f.read() + + #print("Run all StartUPTests") + binary_chunks = process_data_in_chunks(content) + first_chunk = binary_chunks[0] + result = StartUPTest.run_all_tests(first_chunk) + #print(result) + return result + +def perform_tot_online_tests(filename): + with open(filename, 'rb') as f: + # Read the contents of the file as bytes + content = f.read() + + #print("Run all TotOnline tests") + binary_chunks = process_data_in_chunks(content) + first_chunk = binary_chunks[0] + result = TotOnline.run_all_tests(first_chunk) + #print(result) + return result + +def analyze_data(num_numbers, bits_per_number, startup): + + if startup: + filename = read_data(10, 80000) + binary_filename = convert_to_binary(filename, 10, 80000) + perform_startup_tests(binary_filename) + perform_tot_online_tests(binary_filename) + os.unlink(filename) + os.unlink(binary_filename) + return True + else: + filename = read_data(10, 20000) + binary_filename = convert_to_binary(filename, 10, 20000) + result = perform_tot_online_tests(binary_filename) + os.unlink(filename) + os.unlink(binary_filename) + if result: + filename = read_data(num_numbers, bits_per_number) + binary_filename = convert_to_binary(filename, num_numbers, bits_per_number) + hex_filename = convert_to_hex(binary_filename, num_numbers, bits_per_number) + # Read the hex numbers from the file + with open(hex_filename, 'rb') as f: + hex_numbers_bytes = f.read() + # Decode the bytes to a string + hex_numbers_str = hex_numbers_bytes.decode('utf-8') + # Split the semicolon-separated string into a list of hex numbers + hex_numbers = hex_numbers_str.split(';') + # Remove any empty strings + hex_numbers = [hex_num for hex_num in hex_numbers if hex_num] + # Create the JSON object with the specified structure + data = {'randomNumbers': hex_numbers} + # Delete the temporary files + os.unlink(filename) + os.unlink(binary_filename) + os.unlink(hex_filename) + # Return the JSON object using Flask's jsonify function + return jsonify(data) + + else: + os.unlink(filename) + os.unlink(binary_filename) + os.unlink(hex_filename) + return False + +# Teste den Code +#result = analyze_data(50, 2560, startup=False) +#result = analyze_data(8, 8, startup=True) +#print(result) + diff --git a/REST/app.py b/REST/app.py new file mode 100644 index 0000000..26d31dc --- /dev/null +++ b/REST/app.py @@ -0,0 +1,86 @@ +import subprocess +import json +import time +from flask import Flask, request, jsonify, session +from I2C_Function import analyze_data, read_data +from flask_cors import CORS +from flask_session import Session + +app = Flask(__name__) +app.config.from_pyfile('config.py') +Session(app) +CORS(app) + +initialized = False + +@app.route('/trng/randomNum/init', methods=['GET']) +def initialize_generator(): + #quantity = 1 + #bits = 1 + #startup = True # Boolean-Wert für die Initialisierung + global initialized # Zugriff auf die globale Variable + + #result = analyze_data(int(quantity), int(bits), startup=true) + result = analyze_data(int(1), int(1), startup=True) + #session['initialized'] = True + + if result is True: + initialized = True + return jsonify({'error': 'successful operation; random number generator is ready and random numbers can be requested'}), 200 + else: + return jsonify({'error': 'Unable to initialize the random number generator within a timeout of 60 seconds.'}), 555 + + +@app.route('/trng/randomNum/getRandom', methods=['GET']) +def get_random_numbers(): + global initialized # Zugriff auf die globale Variable + quantity = request.args.get('quantity') + bits = request.args.get('numBits') + + if not quantity.isdigit() or not bits.isdigit(): + return jsonify({'error': 'Invalid input. Quantity and bits must be numeric.'}), 400 + + if int(quantity) <= 0 or int(bits) <= 0: + return jsonify({'error': 'Invalid input. Quantity and bits must be positive integers.'}), 400 + + # Überprüfe den Initialisierungsstatus + if not initialized: + return jsonify({'error': 'system not ready; try init'}), 432 + + #if 'initialized' not in session or not session['initialized']: + #return jsonify({'error': 'system not ready; try init'}), 432 + + #if 'initialized' not in session or not session['initialized', 'false']: + #return jsonify({'error': 'system not ready; try init'}), 432 + + filename = analyze_data(int(quantity), int(bits), startup=False) + + if filename is False: + return jsonify({'error': 'Unable to generate random numbers.'}), 500 + if filename: + return filename, 200 + else: + return jsonify({'error': 'Unable to generate random numbers.'}), 500 + +@app.route('/trng/randomNum/shutdown', methods=['GET']) +def shutdown_generator(): + global initialized # Zugriff auf die globale Variable + + initialized = False # Setze den Initialisierungsstatus zurück + #session['initialized'] = False + + # Beispielantwort + return jsonify({'message': 'Generator shutdown successfully.'}), 200 + +if __name__ == '__main__': + # Pfade zu den SSL-Zertifikat- und Schlüsseldateien + #cert_path = '/etc/nginx/ssl/server.crt' + #key_path = '/etc/nginx/ssl/server.key' + cert_path = '/etc/nginx/ssl/cert-gmtrom.pem' + key_path = '/etc/nginx/ssl/cert-gmtrom-key.pem' + + # Starte die Flask-Anwendung mit SSL-Konfiguration + #app.run(host='172.16.78.57', port=5000, ssl_context=(cert_path, key_path)) + app.run(host='0.0.0.0', ssl_context=(cert_path, key_path)) + #app.run(host='0.0.0.0', ssl_context=adhoc) + #app.run(ssl_context=(cert_path, key_path)) \ No newline at end of file diff --git a/REST/index.html b/REST/index.html index e69de29..b1f3e99 100644 --- a/REST/index.html +++ b/REST/index.html @@ -0,0 +1,82 @@ + + + + GMTROM - True Random Number Generator + + + + + +

GMTROM - True Random Number Generator

+
+

+ +

+ +

+ + +
+ +
+
+ + + + \ No newline at end of file diff --git a/REST/logomiddle.png b/REST/logomiddle.png new file mode 100644 index 0000000000000000000000000000000000000000..0f2b6db60050f06a1230dad4105cca7452b38adf GIT binary patch literal 1814 zcmV+x2kH2UP)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGf6951U69E94oEQKA2CGR#K~z{rtyf)a zT*VchGc$L0ZO6e$2zH>MvDY?~*dY~d1*mBisf{S2v3Kp*Efn#F)IRjBAR$2%Q3+mn z09936sfDUVh1%X-TPP%=s(>Jb_z4Y372+S#{I~|=#EBj6diUO$!#BG(CX3e&iStQU zvv_UcYeZ?VQ~A}!9c2tJcWHAoWctYE`}lwgsELFY7ajwP+PY^5i}*rr3bAEP~c zY`9cKENj5AROh#}PsQCI1)yI?9#iO2Vz-};1 z6kx*)JXB`_b@>**_m;v&inIR5-Yv0(Mg4lTr_PaJJYWZon~gjay^q5G<{zV{>iJS~`RZthAA zUb-fd_e=PzXSQKt!XS<<$(3*JaMR9LvU#KT;iMZ7k`to?$sM7nhy?>&!YL`|QBsYk zK03P}e^~M67vbD)t8)J$Wo{OVW=GN;8$(ga0GD(gQwxe}W27qj+V(wf1V!mJMC-l# z@&WN7MZyTycZJiX95|Nl*s82t3m17U-KqUWNrWSfWvTI}@vEK@L2(M2P(Q~q<>cEkgyVsU9 zt`6+$50xShhuz}d<!qZu3%!hJY66R&cMKQm6cOJw@Db|27bpL1I8_7-{`qJs`OA|l@C2CjQ!WIjMG+30xx3teL>s*4-X_VBmK$VqnVwxCF$1#!aixWszDxTctUDx zMAgQg{^?L&28rYgf4YAzgb0>IB~b^=c}W{JF_KFD139zPky)s*B*@oOi0e9(y@&O! zhfBjQMLM(6zQ8O#bH7>gZ!j#X0)(jsZu%L&MC zkaL$7PFWV~OVQMo9>OsnLFv?Ed={?%HOlt>ijUyCuol_@Q8&D|dwpqzaujA))fl#U zxZFrmF z^lUzXSm5-OKl0CAkx*wzFz=S5nT~HDhEs6)=UyyQi?J!sc7ev1gX@-%f6j`SYhDqm zJt#qS8vdB7mgde-Z%K>}{kI9M`4=>$Pr~pCHuf2qHKv&!3{{o|N@*+ljRK0QSlY$R z|1jNAS8L^V28@>|XhlGtxXrht+@}=r^{wm9lqKsT_B;N{u7<+AY4fD@-ABg3 zz#Hu8=|kRJIovI&0=%A|Q-6a+2*Odwq@_P`TkwV3d?;mXG89MrP zyJT0+G0$(eM&1an7zad;Yvrd*D4KbG!S#({VIfJ zEhu&#AE5yn3Xkw*3PasmlbXC-Aj~ESSUvzI zt6T>yuqjR&LDJ4SFJX*fYO490>krd+{#5#KT^2%o0bg+&n?PSiNB{r;07*qoM6N<$ Ef{d7Wt^fc4 literal 0 HcmV?d00001 diff --git a/REST/logosmall.png b/REST/logosmall.png new file mode 100644 index 0000000000000000000000000000000000000000..a9df110b522d2c35470b915c48cba74f1f375915 GIT binary patch literal 776 zcmV+j1NZ!iP)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGf6951U69E94oEQKA0-Z@jK~y+Tjg!ky z6G0fjzi(#ShDVD8L5V0Js6YUlKzv*@985f@eNZ__qA?~OJ$Ta#@uXM(0zNGX)?r~$2Dp|rHSGk&wKkbp7%lHHl_HTykw5OxuJ(d&ZzdJUJh3Mqt3 zqSP2bN4pQp418{X+31Tzxx^U*HLbMR zd44A3J#K}Vm>HPCZDVH{&!&PDsbr z!$bnR-ssao|2+mcW}uvihXZX^%pU4*_U9zP*G(>J8S3Id7GOmgjs-#wQNlY!ETIVm zNmS$Yrv(^O{+P&QD$k9CBF>5zXk7WChmj9hVA zZouvNl;l{+H~=NEgUA)`Q=K|U7^RNAru8jKiHyNH6zrts2Kf!AWDIRoGGr5B&pt~J zO})>*7npv54j~(M(6hjqcGnQ_fCE-jSw7`g>-)t^(grRb&Nbe0{q+ig`sh)g5h7wj1_ zlx@$~sFW(YjR!Su9HMOOND~Cc()9iYU|VkRJYBY234mYC92O!467