Sunday, June 10, 2012

Python Hashing encryption, decryption example

import hashlib
import random
alphanumer = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
              'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
              'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
              'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
              'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8',
              '9', '0', ' ', '.', '!', ',', '@', '#', '$', '%', '^', '&',
              '*', '(', ')', '-', '_', '+', '=', '[', ']', '{', '}', ':',
              ';', "'", '"', '?', '/', '>', '<']

class encryption:
    def generate_moduluslenkeyset(self, epart):
        epartlen = len(epart)
        setrange = range(0, 7)
        rmodlenkeyset = []
        for i in setrange:
            if epartlen > 12:
                ml = random.randint(6,12)
            else:
                ml = random.randint(6, epartlen)
            rmodlenkeyset.append(ml)
        return rmodlenkeyset
        
    
    def generate_moduluskeyset(self, epart, rmodlenkey, moduluskeyset):
        #where epart is the encrypted partition
        epartlen = len(epart)
        mk = random.randint(0,len(epart)-rmodlenkey)
        moduluskeyset +=  str(mk) + ' ' 
        return moduluskeyset

    def generate_modulushashset(self):
        setrange = range(0,7)
        mhshset = []
        mhshstring = ''
        for i in setrange:
            ri = random.randint(1, 50)
            mhshset.append(ri)
            mhshstring += str(ri) + ' '
        return mhshstring, mhshset

    def hshrtn(self, privatekey, string, itern):
        #recursive hashing function called upon itself
        #itern times
        preencryptpart = privatekey + string 
        pencryptutf16 = bytes(preencryptpart, 'utf-16')
        hshlb = hashlib.sha1()
        hshlb.update(pencryptutf16)
        hsh = hshlb.hexdigest()
        itern -= 1
        if itern > 0:
            hsh = self.hshrtn(privatekey, hsh, itern)
        return hsh

    def generatemsetlen(self, epart):
        #7 set length, although you could extend this if you wanted
        #to.
        setrange = range(0, 7)
        moduluskeyset = ''
        rmodlenkeyset = self.generate_moduluslenkeyset(epart)
        index = 0
        for i in setrange:
            rmodlenkey = rmodlenkeyset[i]
            moduluskeyset = self.generate_moduluskeyset(epart, rmodlenkey,
                                                        moduluskeyset)
            index += 1

        mset = moduluskeyset.split(' ')

        for rmodlenkey in rmodlenkeyset:
            moduluskeyset += str(rmodlenkey) + ' '
            
        return moduluskeyset, mset, rmodlenkeyset 
        
    def generate_privatekey(self):
        
        randomkey = str(random.random()) + '$' + str(random.random())
        randomkeyutf16 = bytes(randomkey, 'utf-16')
        #store this salt, alongside your raw_password
        salt = hashlib.sha1()    
        salt.update(randomkeyutf16)
        saltkey = salt.hexdigest()
        return saltkey

        
    def encrypt_message(self, raw_message):

        
        privatekey = self.generate_privatekey()
        hshkeylist = self.generate_modulushashset()
        encryptmessage = ''
        capture = False
        lindex = 0
        mhshstring, mhshset = self.generate_modulushashset()
        for letter in raw_message:
##            preencryptpart = privatekey + letter
##            pencryptutf16 = bytes(preencryptpart, 'utf-16')
##            hshlb = hashlib.sha1()
##            hshlb.update(pencryptutf16)
##            hsh = hshlb.hexdigest()
            itern = mhshset[lindex % len(mhshset)]
            
            hsh = self.hshrtn(privatekey, letter, itern)
            if not capture:
                moduluskeyset, mset, rmodlenkeyset = self.generatemsetlen(hsh)
                mset = mset[0:len(mset)-1]
##                print('e mset: ', mset)
                capture = True
                modk = len(mset)
                modl = len(rmodlenkeyset)
            mpos = lindex % modk
            mlpos = lindex % modl
##            print('mset ', mset[mpos])
##            print('mlset', rmodlenkeyset[mlpos])
            mstart = int(mset[mpos])
            mend = int(mset[mpos]) + rmodlenkeyset[mlpos]
            encryptmessage += hsh[mstart:mend]
            lindex += 1
        privatekey += ' ' + moduluskeyset + mhshstring
        print('mset ', mset)
        print('mlset ',rmodlenkeyset)
        print('mhshset ', mhshset)
        
        return encryptmessage, privatekey

    def gen_decrypttables(self, privatekeyg, encryptmessage):
        #this works in a limited context for western latin based scripts
        #you'd have to make sure to import the correct character set for
        #alternate languages.  I'd recommend encrypting into the private
        #key a language code to reduce computation times on character sets.
        keytables = privatekeyg.split(' ')
        privatekey = keytables[0]
##        print('private key: ', privatekey)
        msetmlset = keytables[1:len(keytables)-1]

        setrange = range(0, 7)
        mset = []
        mlset = []
        mhshset = []
        for i in setrange:
            mset.append(msetmlset[i])
            mlset.append(msetmlset[i + 7])
            mhshset.append(msetmlset[i + 14])
        print('mset: ', mset)
        print('mlset: ',mlset)
        print('mhshset: ', mhshset)
        
        modk = len(mset)
        modl = len(mlset)
        modh = len(mhshset)
        decryptiondict = {}
        rangec = range(1, 51)
        print(rangec)
        tabledict = {}
        for i in rangec:
            tabledict = {}
            decryptiondict[i] = tabledict
        print('computing decryption tables')    
        for letter in alphanumer:
            hsh = letter
            for i in rangec:
                tabledict = decryptiondict[i] 
##                keystring = privatekey + letter
##                bkeystring = bytes(keystring, 'utf-16')
##                hshlb = hashlib.sha1()
##                hshlb.update(bkeystring)
##                hsh = hshlb.hexdigest()
                hsh = self.hshrtn(privatekey, hsh, 1)
                tabledict[hsh] = letter
                decryptiondict[i] = tabledict
                
        
        print('finished computing decryption tables')
##        print(decryptiondict[2])
        decryptmessage = ''
        count = 0
        
        while len(encryptmessage) > 0:
##            print(decryptmessage)
            mpos = count % modk
            mlpos = count % modl
            mhpos = count % modh
            mstart = int(mset[mpos])
            mend = int(mset[mpos]) + int(mlset[mlpos])
            for hsh in decryptiondict[int(mhshset[mhpos])]:
                hshtrunc = hsh[mstart: mend]
               
                if encryptmessage.find(hshtrunc) == 0:
##                    print('found')
                    decryptmessage += decryptiondict[int(mhshset[mhpos])][hsh]
                    hshlen = len(hshtrunc)
                    encryptmessage = encryptmessage[hshlen:
                                                    len(encryptmessage)]
                    break
            count += 1
            if count > 9999999999999:
                break
            
        return decryptmessage
        
    def set_password(self, raw_password, saltkey = None):
        
        randomkey = str(random.random()) + '$' + str(random.random())
        randomkeyutf16 = bytes(randomkey, 'utf-16')
        #store this salt, alongside your raw_password
        if saltkey == None:
            salt = hashlib.sha1()    
            salt.update(randomkeyutf16)
            saltkey = salt.hexdigest()[:5]
        preencryptpass = saltkey + '$' + raw_password
        pencryptutf16 = bytes(preencryptpass, 'utf-16')
        hshlb = hashlib.sha1()
        hshlb.update(pencryptutf16)
        hsh = hshlb.hexdigest()
        self.password = '%s$%s' % (saltkey, hsh)

    def check_password(self, raw_password):
        """
        Returns a boolean of whether the raw_password was correct. Handles
        encryption formats behind the scenes.
        """
        
        saltkey, hsh = self.password.split('$')
        preencryptpass = saltkey + '$' + raw_password
        pencryptutf16 = bytes(preencryptpass, 'utf-16')
        hshlb = hashlib.sha1()
        hshlb.update(pencryptutf16)
        hsh2 = hshlb.hexdigest()
        return hsh == hsh2

    def __init__(self, rawpassword):
        self.set_password(rawpassword)
        
rawpass = 'abcdeabcde'
a = encryption(rawpass)
print(a.password)
b = a.check_password('abcdeabcde')
encryptmessage, privatekey = a.encrypt_message('The cat walked home.  The eagle has landed.  The eagle has landed.')
print('encryptmessage: ', encryptmessage)
print('privatekey: ', privatekey)
decryptmessage = a.gen_decrypttables(privatekey, encryptmessage)
print (decryptmessage)

Last generation modulates a randomly indexed re iterated hashing an original privatekey and letter (up to a 50th successive cycle), there are seven random hashing key values provided here
for this modulation cycle.
Because a privatekey is restacked onto a successively hashed encryption letter, at least in theory without having the privatekey, no successive hash generation can be reproduced here. This means effectively one shouldn't be able to discern ancestral to child relation patterns (via rehashing) without access to the private key. This should further limit pattern matching to isolated repeated segments of the same encryption blocks on a given ith hash iterated character privatekey generation. Thus in all modulating the index, length, and nth successive hash generation of a given character private key. While in theory computations should increase with added generations of rehashing of the same character privatekey encryption over successive generations up to 50 here. I've spared redundancy in processing by pre generating computed tables prior to main iteration loop decryption processing. Thus making computation virtually the same in so far as the main iteration process were concerned.
Code also provided at this link

   Hashing encryption decryption python example

Have another variant of this example, which instead varies successive encryption stacking from
letter position to letter position, only repeating the ith stacking process by global NCAP positions.
Presently possible repetitions allow for at best a possible 1/10000 chance for repeating a encryption letter splice fragment with NCAP set to 10000, where pre computed tables appear to be the lengthier point in processing.  Cache or storage of pre computed tables for a given private key  would solve this problem.

 2nd example hashing encryption decryption script python

Okay so future generation ideas here.  I wanted to create an encryption so that:
private keys remain fixed, while varying relative to history the slice of a given encrypted letter private key combination.  Hmm, a second public key could be furnished alongside the encrypted message. Here, the public key translates to a time stamp signature which uniquely signatures the encryption process of privatekey and letter to a given time frame.  In this way historical analysis can't be made with respect to present encryption structures.  The downside's to this method is greater vulnerabilities to tampering with the decryption process of the message itself, but the upside is that decryption through pattern analysis only that much harder.  Certainly the advantage to keying here, is that a message encrypted by way of private and public keys is that message authentication, provided excellent software and hardware security likely means that even if an decryption authenticator like a public key or the encrypted message itself or tampered renders a message that is indecipherable.  Meaning at least a tampered message in theory shouldn't be intruded upon in terms of content revelations.

3rd example hashing encryption decryption with private and public keys script python

No successive generation of message with the same private key produces the same result relative the other so long as public keys vary which this script provides.  Two users must have a private key (shared with no one else) but can share a public key that is transmitted with an associated message (in less secure conditions).  The public key is associated to the message that it were used in the encryption process and no other.  Changing NCAP is contingent on the character position count of your content.  One could in theory change this to any number desired at present, albeit computation times significantly increase at say 100,000 for decryption table generation.  The highest level of security in terms of pattern matching I would imagine are such that NCAP is close to matching the character position count of your message.

No comments:

Post a Comment

Oblivion

 Between the fascination of an upcoming pandemic ridden college football season, Taylor Swift, and Kim Kardashian, wildfires, crazier weathe...