Пример #1
0
def voter(choice):

    voterkeys['sk'], voterkeys['pk'] = enc.rsakeys()

    v1 = vote(invisiblevoter, int(choice), voterkeys['pk'])

    vote.inc_votecount()

    #--votedata digitally signed and encrypted and sent to the temporary pool
    with open('temp/votefile.csv', 'a', newline="") as votefile:
        writer = csv.writer(votefile)
        encvotedata = v1.encryptvote()

        writer.writerow(encvotedata)

#--and broadcasted to other peers on the network
#pp.send_votedata_to_peer('127.0.0.1',9999,encvotedata)
    """
    This method mines new blocks after generation of every 2 votes
    Uncomment this method and comment the 'mineblocktimer()' method 
    to switch to 'vote count block mining' method - where block will be mined after 2 votes are generated and not on regular time intervals.
    """

    if vote.count % 2 == 0:
        blockx = Block().mineblock()
        with open('temp/blockchain.dat', 'ab') as blockfile:
            pickle._dump(blockx, blockfile)
        print("block added")

    pass
    """
    Now the QR code containing the information about your PIN
    and private key is printed on the thank you page.
    """
    print("thanks")
Пример #2
0
def voter():
#--the voter is eligible if reached this page.
#--hence his own keys will be generated.
    voterkeys['sk'],voterkeys['pk'] = enc.rsakeys()         #--voter public/private key pair generated here
    choice = request.form['candidate']


#--vote object created
    v1 = vote(invisiblevoter, int(choice), voterkeys['pk'])
    print(v1)
    vote.inc_votecount()

#--votedata digitally signed and encrypted and sent to the temporary pool
    with open('temp/votefile.csv','a',newline="") as votefile:
        writer = csv.writer(votefile)
        encvotedata = v1.encryptvote()
        print("************")
        writer.writerow(encvotedata)

#--and broadcasted to other peers on the network
    pp.send_votedata_to_peer('127.0.0.1',9999,encvotedata)

    """
    This method mines new blocks after generation of every 2 votes
    Uncomment this method and comment the 'mineblocktimer()' method 
    to switch to 'vote count block mining' method - where block will be mined after 2 votes are generated and not on regular time intervals.
    """

    if vote.count%2==0:
        blockx = Block().mineblock()
        with open('temp/blockchain.dat','ab') as blockfile:
            pickle._dump(blockx,blockfile)
        print("block added")

    pass

    """
    Now the QR code containing the information about your PIN
    and private key is printed on the thank you page.
    """

    return redirect('/thanks')
class Blockchain:

    #--holds the info of chain of blocks as objects
    chain = []

    #--administrator public/private key pair generated along with the blockchain initialization.
    #--the public key of admin will be used to encrypt the vote data for confidentiality
    adminpriv, adminpub = enc.rsakeys()
    with open('temp/Adminkeys.txt', 'wb') as adminkeyfile:
        pickle._dump(adminpriv, adminkeyfile)
        pickle._dump(adminpub, adminkeyfile)

    def __init__(self):
        self.addGenesis()
        print('Blockchain initialized')

    @staticmethod
    #--genesis block creation has nothing to do with blockchain class,
    #--..but has to be created when blockchain is initialized
    def genesis():

        #--genesis block created
        gen = Block(
            0, "Let the real democracy rule!!", 0,
            sha256(str("Let the real democracy rule!!").encode(
                'utf-8')).hexdigest(), DIFFICULTY, time(), '', 0, 'Errrrrorrr')
        return gen

    @staticmethod
    def addGenesis():
        genesisblock = Blockchain.genesis()

        #--find the proof of work for genesis block
        genesisblock.nonce = genesisblock.pow()
        genesisblock.hash = genesisblock.calcHash()
        Blockchain.chain.append(genesisblock)

        #--information of genesis block written to the blockchain data file
        with open('temp/Blockchain.dat', 'ab') as genfile:
            pickle._dump(genesisblock, genfile)
        print("Genesis block added")

    @staticmethod
    def display():
        #--print the information of blocks of the blockchain in the console
        try:
            with open('temp/blockchain.dat', 'rb') as blockfile:
                for block in range(len(EVoting.chain)):
                    data = pickle._load(blockfile)

                    #--print all data of a block
                    print("Block Height: ", data.height)
                    print("Data in block: ", data.data)
                    print("Number of votes: ", data.number_of_votes)
                    print("Merkle root: ", data.merkle)
                    print("Difficulty: ", data.DIFFICULTY)
                    print("Time stamp: ", data.timeStamp)
                    print("Previous hash: ", data.prevHash)
                    print("Block Hash: ", data.hash)
                    print("Nonce: ", data.nonce, '\n\t\t|\n\t\t|')

        except FileNotFoundError:
            print("\n.\n.\n.\n<<<File not found!!>>>")

    @staticmethod
    #--to clear up the votepool after a block has been mined...
    def update_votepool():
        try:
            votefile = open('temp/votefile.csv', 'w+')
            votefile.close()

        except Exception as e:
            print("Some error occured: ", e)
        return "Done"

    #--to check if whether the data pool has some data or not
    def is_votepool_empty(self):

        #--path to votefile
        my_path = PROJECT_PATH + '/temp/votefile.csv'

        #--will return true if file exists and has no data
        if os.path.isfile(os.path.expanduser(my_path)) and os.stat(
                os.path.expanduser(my_path)).st_size == 0:
            return True

    #--False otherwise
        return False
    """
    After regular intervals, we need to verify that the blockchain
    is indeed valid at all points. And no data has been tampered - EVEN IN ONE SINGLE COPY
    (if not for the whole network).
    We do that by verifying the chain of block hashes.
    """

    @classmethod
    def verify_chain(cls):
        index, conclusion = ver.sync_blocks(cls.chain)
        if not conclusion:
            if len(str(index)) == 1:
                error_msg = """+-----------------------------------------+
|                                         |
| Somebody messed up at Block number - {}  |
|                                         |
+-----------------------------------------+""".format(index)

            else:
                error_msg = """+-----------------------------------------+
|                                         |
| Somebody messed up at Block number - {} |
|                                         |
+-----------------------------------------+""".format(index)

            raise Exception(error_msg)

        return True
import enc as enc
import Major2.jsonify as js
import time
import pickle as pk
import simplejson as js
keys = {}
keys['private'], keys['public'] = enc.rsakeys()
#
# class vote:
#
#     def __init__(self,hiddenvoterid,candidateID,pubkey):
#         #--voterid hashed with PIN (ZKP)
#         self.hiddenvoterid = hiddenvoterid
#         self.candidate = candidateID
#         self.pubkey = pubkey
#         self.time = time.time()
#         self.votedata = [self.hiddenvoterid, self.candidate, self.time]
#
# v1 = vote('7112a70d9ef40de8a89ed2845cae954901aa6a67200e29bcc9344a0bbdb8f35a',1,keys['public'])
#print(keys['public'])
keyobj = pk._dumps(keys['public'])
print(keyobj)

ls = [
    b'C6yOrzSFsfy4bQ172sS2PRmpTmGa8euo+xg',
    b'rTDAVInfyDn+WO72sS2PRmpTmGykx74Kz/HC4='
]
ls.append(str(keyobj)[2:-1])
jsondict = {'pubkey': ls[2], 'data': ls[0], 'key': ls[1]}

#
Пример #5
0
def encrypt(raw, private_key):
    raw = pad(raw)
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(private_key, AES.MODE_CBC, iv)
    return base64.b64encode(iv + cipher.encrypt(raw))


def decrypt(enc, private_key):
    enc = base64.b64decode(enc)
    iv = enc[:16]
    cipher = AES.new(private_key, AES.MODE_CBC, iv)
    return unpad(cipher.decrypt(enc[16:]))

if __name__=='__main__':

    voterpriv, voterpub = enc.rsakeys()
    adminpriv, adminpub = enc.rsakeys()

    l = ['eee9ca050b625c9a8206beb29e5687d915f70aaa061993d9ea5bdf2041c66a26', 1, time.time()]
    #--all 3 elements of votedata appended together as a string and hashed
    #--hash converted to bytes
    #--then signed by voter's private key
    #--then appended back to the list
    l.append(enc.sign(voterpriv,bytes(sha256(str('---'.join(str(x) for x in l)).encode('utf-8')).hexdigest(),'utf-8')))
    #--now the list elements are again appended together as string and encrypted
    #--using the shared key
    #--this encrypted data is to be added to vote pool and sent to other as well.
    #--and the key must be encrypted by RSA algotithm using the public key of admin(reciever)

    vote = {'data': encrypt('***'.join(str(i) for i in l),get_private_key(pw)), 'key': enc.encrypt(adminpub,get_private_key(pw))}
    print(vote)