Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
krrish-v authored Jun 12, 2022
0 parents commit f343a57
Show file tree
Hide file tree
Showing 13 changed files with 5,545 additions and 0 deletions.
Binary file added BLOCK/__pycache__/block.cpython-38.pyc
Binary file not shown.
Binary file added BLOCK/__pycache__/databse.cpython-38.pyc
Binary file not shown.
65 changes: 65 additions & 0 deletions BLOCK/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@

from flask import Flask, request, render_template, url_for, redirect, jsonify
from flask_socketio import SocketIO, join_room
from databse import get_in_data, user_api, get_key, create_api
import block as blk
import databse
import time

'''
try:
file_log = open('log/web.log', 'r').close()
except:
file_log = open('log/web.log', 'w').close()
logging.basicConfig(filename="cloud_chain/api_/web.log",
format='%(asctime)s %(message)s',
filemode='a+') #change the mode to a+ if file is present
logger = logging.getLogger()
logger.info("Started the web API")
'''

app = Flask(__name__)
sock = SocketIO(app)

@app.route('/register/phone_no=<phone>,password=<password>,country=<country>,state=<state>,zipcode=<zipcode>')
def register(phone, password, country, state, zipcode):
phone = phone
password = password
country = country
state = state
zipcode = zipcode
token = databse.token()
if phone and password and country and state and zipcode == '':
return jsonify({'error': 'Incomplete detail'})
else:
status = True
date = time.ctime()
api = create_api().api()
ins_api_key = databse.user_api().insert(api)
in_data = get_in_data.insert(token, password, firstname, lastname, address, country, state, zip_code, phone_no, status, date)

if in_data is True and ins_api_key is True:
return jsonify({'api': api_key})
else:
return jsonify({'error': 502})


@app.route('/api/ask_publickey?api=<api>,token=<token>')
def other_user_pub_key(api, token):
chek_api = user_api().check(api)
if chek_api is True:

public_key = get_key().get_pub(token)
if public_key is not None: return jsonify({'status': 200, 'public_key': public_key})

elif public_key is False: return jsonify()

else: return jsonify()
else:
return jsonify()



68 changes: 68 additions & 0 deletions BLOCK/block.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@

import hashlib
import ecdsa
from ecdsa import SECP256k1
import rsa as RSA
from databse import get_key


# convert to hexfily
def hexlf(msg):
return binascii.hexlify(msg)

# base decode function
def encoded_data(msg):
return base64.b85encode(msg)

class rsa:
def keys(self):
public, private = RSA.newkeys(2048)
return str(public), str(private)

def loadkey(self, token):
pub, prv = self.keys()
load = get_key().insert(token, pub, prv)
return load


class DSA():

def get_key(self):
self.sk = ecdsa.SigningKey.generate(curve=ecdsa.BRAINPOOLP384r1, hashfunc=hashlib.sha3_384)
self.vk_ = self.sk.get_verifying_key()
self.private_key = self.sk.to_string().hex()
return self.private_key

def create_signture(self, privatekey, message: bytes):
self.sk = ecdsa.SigningKey(_error__please_use_generate=True).from_string(bytes.fromhex(privatekey), curve=ecdsa.BRAINPOOLP384r1, hashfunc=hashlib.sha3_384)
sig_ = self.sk.sign(hashlib.sha3_256(message).hexdigest().encode())
sig = bytes.hex(sig_)
public_key = bytes.hex(self.sk.get_verifying_key().to_string())
return sig, message, public_key


class verf_DSA():
def verify_signature(self, signature : bytes, message: bytes, public_key):
vk = ecdsa.VerifyingKey.from_string(bytes.fromhex(public_key), curve=ecdsa.BRAINPOOLP384r1, hashfunc=hashlib.sha3_384) # the default is sha1
verify = vk.verify(bytes.fromhex(signature), hashlib.sha3_256(message).hexdigest().encode()) # True
return verify

def hash384(message):
return hashlib.sha3_384(message.encode()).hexdigest()

def hash256(message):
return hashlib.sha3_256(message.encode()).hexdigest()


'''
c = DSA()
k = c.get_key()
print(k)
signat = c.create_signture(k, message=b'hii')
print(signat)
print(verf_DSA().verify_signature(signat[0], signat[1], signat[2]))
print(rsa().loadkey('qsfjgthfb34uifg34tr387fgvwu'))
print(get_key().get_pub('qsfjgthfb34uifg34tr387fgvwu'))
'''
39 changes: 39 additions & 0 deletions BLOCK/clientside_chat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Python program to implement client side of chat room.
import socket
import select
import sys

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if len(sys.argv) != 3:
print ("Correct usage: script, IP address, port number")
exit()
IP_address = str(sys.argv[1])
Port = int(sys.argv[2])
server.connect((IP_address, Port))

while True:

# maintains a list of possible input streams
sockets_list = [sys.stdin, server]

""" There are two possible input situations. Either the
user wants to give manual input to send to other people,
or the server is sending a message to be printed on the
screen. Select returns from sockets_list, the stream that
is reader for input. So for example, if the server wants
to send a message, then the if condition will hold true
below.If the user wants to send a message, the else
condition will evaluate as true"""
read_sockets,write_socket, error_socket = select.select(sockets_list,[],[])

for socks in read_sockets:
if socks == server:
message = socks.recv(2048)
print (message)
else:
message = sys.stdin.readline()
server.send(message)
sys.stdout.write("<You>")
sys.stdout.write(message)
sys.stdout.flush()
server.close()
135 changes: 135 additions & 0 deletions BLOCK/cryptograph.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@

from Crypto.Cipher import AES
import hashlib
import binascii
import secrets
import os

#padding of data
# code extarcted from open source library
def add_padding(message: bytes, target_length: int) -> bytes:\
#target length is key.bit_length() == 256, 384, 512...
max_msglength = target_length - 11
msglength = len(message)

if msglength > max_msglength:
raise OverflowError('%i bytes needed for message, but there is only'
' space for %i' % (msglength, max_msglength))

# Get random padding
padding = b''
padding_length = target_length - msglength - 3

# We remove 0-bytes, so we'll end up with less padding than we've asked for,
# so keep adding data until we're at the correct length.
while len(padding) < padding_length:
needed_bytes = padding_length - len(padding)

# Always read at least 8 bytes more than we need, and trim off the rest
# after removing the 0-bytes. This increases the chance of getting
# enough bytes, especially when needed_bytes is small
new_padding = os.urandom(needed_bytes + 5)
new_padding = new_padding.replace(b'\x00', b'')
padding = padding + new_padding[:needed_bytes]

assert len(padding) == padding_length

return b''.join([b'\x00\x02',
padding,
b'\x00',
message])


#remove pading from decrypted message
def remove_padding(msg: bytes):
cleartext_marker_bad = not compare_digest(msg[:2], b'\x00\x02')
sep_idx = msg.find(b'\x00', 2)
sep_idx_bad = sep_idx < 10
anything_bad = cleartext_marker_bad | sep_idx_bad

if anything_bad:
raise DecryptionError('Decryption failed')
return msg[sep_idx + 1:]

n_field = 39402006196394479212279040100143613805079739270465446667946905279627659399113263569398956308152294913554433653942643

class aes_():
def __init__(self, data: bytes, password_hash): #password should be in hash form
self.data = data
self.password_hash = password_hash

def aes_key(self):#key and hash
self.key = secrets.randbelow(n_field)

self.enc_key = hashlib.sha3_256(int.to_bytes(self.key, 256, 'big'))
self.enc_key.update(self.password_hash.encode())

return self.enc_key.digest(), self.key #password and key should always be rememberd

def hexlfy(self, byte):
self.byte = byte
return binascii.hexlify(self.byte)

def encrypt(self):
self.key_, self.primary_key = self.aes_key()

self.encrypt_mode = AES.new(self.key_, AES.MODE_GCM)
#padding blocksize
self.size = 256
self.data_ = add_padding(self.data, self.size)
self.encrypt_data = self.encrypt_mode.encrypt_and_digest(self.data_)

#it's a iv that is used while decrypting
self.iv = self.encrypt_mode.nonce
# seperating data form encrypted text
self.enc_data, self.authtab = self.encrypt_data
#compiling all data together(encrypted_data + authtag)
self.whole_encdata = self.hexlfy(self.enc_data) + b' ~ ' + self.hexlfy(self.authtab)
#key with nonce(that is iv)
self._key_ = self.primary_key, self.hexlfy(self.iv)

# return a byte data contains(encrypted data, authtab, nonce) and aes key(sha3-512 user key)
return (self.whole_encdata, self._key_)

def aes_gmc(data):
encrypted_data = aes_(data).encrypt_aes()
return encrypted_data



class aes_decrypt():
def __init__(self, primary_key, nonce, password_hash, data):
#seperate the encrypted data and authtag
self.datta = data
self.priv_key = primary_key
self.hash = password_hash
self.nonce = nonce
self.data = tuple(map(bytes, self.datta.split(b' ~ ')))

def aes_key(self):
#creating a key by required input
self.enc_key = hashlib.sha3_256(int.to_bytes(self.priv_key, 256, 'big'))
self.enc_key.update(self.hash.encode())

return self.enc_key.digest()

def decryption(self):
self.authtag = binascii.unhexlify(self.data[1])
self.enc_data = binascii.unhexlify(self.data[0])
self.nonce = binascii.unhexlify(self.nonce)
self.key_ = self.aes_key()
self.decrypt_mode = AES.new(self.key_, AES.MODE_GCM, nonce=self.nonce)
# padding block size
self.size = 256
self.decrypt_data = self.decrypt_mode.decrypt_and_verify(self.enc_data, self.authtag)

return remove_padding(self.decrypt_data)


#hash = hashlib.sha3_256('password_'.encode()).hexdigest()
#a = aes_(b'data', hash)
#enc_data = a.encrypt()
#print(enc_data)

#b = aes_decrypt(enc_data[1][0], enc_data[1][1], hash, enc_data[0])
#print(b.decryption())
Binary file added BLOCK/database/api.db
Binary file not shown.
Binary file added BLOCK/database/data.db
Binary file not shown.
Binary file added BLOCK/database/keys.db
Binary file not shown.
Loading

0 comments on commit f343a57

Please sign in to comment.