Welcome, guest | Sign In | My Account | Store | Cart

Encryption can sometimes be a nightmare, at least is my experience while Python has some excellent resources for encryption I found myself a lot of times needing an encryption solution that could port easily between VS C++, .NET, PHP, and Python projects that would be simple to implement and not rely on large bloated crypto libs.

Python, 417 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
"""
SimpleCrypt.py REV 3
Author: A.J. Mayorga
Date: 04/2010

Changelog:
    - 04/30/2010    Added Reinitialization method for change crypto params on the fly
    - 04/30/2010    Added a HMAC method for help with socket coms

SimpleCrypt development goals:
    - Import as few modules as possible minimize dependecies
    - No importing of non native python (2.6) modules 
    - No ctype calls
    - Implement to be easy to understand.
    - Allow for an abundance of tweaking.
    - Keep the internals straight forward and as simple as possible
      while still providing a solid encryption framework.
    
     
Algorithm Features:
    - Keys:
        - User provided key is used to generate a series of internal keys the number
          of which depend on the number of encryption cycles desired more 
          cycles = more entropy

        - Key magnitude can be set to determine the complexity of internally
          derived cycle keys.
          
        - Cycle keys are applied to the cycle data in a ring buffer fashion
          rather than byte for byte
      
        - Each cycle key is initialized at a different start byte than the other
          cycle keys which is determined by a combination of the derived cycle key
          and the KEY_ADV value.

        
    - Cycles (a cycle is a single pass of encryption or decryption over the data)
        - Variable number of cycles allows for fine tuning of entropy vs. speed
        
        - Each cycle uses a different data shift (initialization vector) on the 
          cycle data to determine at what byte to start
          
    - Blocks
        - provided two different methods for handling larger volumes of data
    
    - Size and padding
        - Does not pad the cipher data, the resulting cipher is the same size
          as the plaintext data. Cipher data is in raw binary (hex values here
          are for easy viewing of samples)
      
      
Essentially SimpleCrypt gives you a framework in which to encrypt your data
options are easy to use and the algorithm is easy to recreate in other languages 
C/C++, .NET and others

so if you work with custom multi-languaged solutions, encrypt files, need to 
create your own encrypted sockets or just want the ability to tweak everything
without having to delve deep in the math this can be an easy single class 
solution for getting the job done.

As always constructive critiques are always welcomed and desired if anyone can 
point out a weakness in the algorithm Ive provided the below hexed
cipher, please show me how you would crack it, Id really love to see how you did
it. Enjoy!

CRACK ME:
d55eacd6fdee9543b1b30140a98d23f9c9e03fc66cbe8a8b17b07bade9b6d9dfa03ed2dda650412dbb14a256d86cbb41c4eda61f8cf2


"""



from hashlib import sha1
from array import array


class SimpleCrypt:
   
    
    def __init__(self, INITKEY, DEBUG=False, CYCLES=3, 
                 BLOCK_SZ=126, KEY_ADV=0, KEY_MAGNITUDE=1):
        
        self.cycles         = CYCLES
        self.debug          = DEBUG
        self.block_sz       = BLOCK_SZ
        self.key_advance    = KEY_ADV
        self.key_magnitude  = KEY_MAGNITUDE
        
        self.key            = self.MSha(INITKEY)
        self.eKeys          = list()
        self.dKeys          = list()
        self.GenKeys()

    
    """
    Short hash method
    """
    def MSha(self, value):
        try:
            return sha1(value).digest()
        except:
            print "Exception due to ", value
            return None

      
    """
    Short hexed hash method
    """
    def MShaHex(self, value):
        try:
            return sha1(value).digest().encode('hex')
        except:
            print "Exception due to ", value
            return None

      
    """
    Sets the start byte of a cycle key
    """
    def KeyAdvance(self, key):
        k = array('B', key)   
        for x in range(self.key_advance):
            k.append(k[0])
            k.pop(0)
        return k
     
    
    """
    Sets the complexity & size of a cycle key
    based off the hash of the original supplied key
    """  
    def SetKeyMagnitude(self, key):
        k = array('B', key)
        for i in range(self.key_magnitude):
            k += array('B', sha1(k).digest()) 
            k.reverse()
        k = self.KeyAdvance(k)
        
        return k
   
  
    """
    Generate our encryption and decryption cycle keys based off of the number 
    of cycles chosen & key magnitude
    """
    def GenKeys(self):
        k = array('B', self.key)
        self.eKeys  = list()
        self.dKeys  = list()
        
        for c in range(self.cycles):
            k = sha1(k).digest()
            self.eKeys.append(self.SetKeyMagnitude(k))
            self.dKeys.append(self.SetKeyMagnitude(k))
        self.dKeys.reverse()
       
    
    """
    Allow for reinitialization of parameters for on the fly changes
    """
    def ReInit(self, ARGS):
        #(Default,New Value)[ARGS.has_key('VALUE')] #True == 1

        self.key         = (self.key,self.MSha(ARGS.get('Key')))[ARGS.has_key('Key')]
        self.cycles      = (self.cycles,ARGS.get('Cycles'))[ARGS.has_key('Cycles')]
        self.block_sz    = (self.block_sz,ARGS.get('BlockSz'))[ARGS.has_key('BlockSz')]
        self.key_advance = (self.key_advance,ARGS.get('KeyAdv'))[ARGS.has_key('KeyAdv')]
        
        self.GenKeys()


  
    """
    Set a start vector (initialization vector) of our data in a cycle
    the iv is determined by the first byte of the cycle key and the cycle mode
    aka cmode and will be different each cycle since a different key is used each
    cycle.
    
    Also the direction of or rather how the iv value is set depends on the cmode
    as well forward for encryption and backward for decryption.  
    """  
    def SetDataVector(self, data, params):
        vdata   = array('B', data)
        cmode   = params[0]
        cycle   = params[1]
        iv      = 0
          
        if   cmode == "Encrypt":
            iv    = array('B', self.eKeys[cycle])[0]
        elif cmode == "Decrypt":
            iv    = array('B', self.dKeys[cycle])[0]
            
        for x in range(iv):
            if  cmode == "Encrypt":
                vdata.append(vdata[0])
                vdata.pop(0)
            elif cmode == "Decrypt":
                v = vdata.pop(len(vdata)-1)
                vdata.insert(0,v)
        
        if self.debug:
           print "IV: ",iv
           print "SetDataVector-IN:\t",data.tostring().encode('hex')
           print "SetDataVector-OUT:\t",vdata.tostring().encode('hex'),"\n"
        
        return vdata
    
      
    """
    Here the cycle key is rolled over the data(Xor). Should the 
    data be longer than the key (which most times will be the case) the the first
    byte of the cycle key is moved to the end the key and is used again 
    Think ring buffer
     
    """
    def Cycle(self, data, params):
        keyplaceholder  = 0 
        dataholder      = array('B')
        cycleKey        = array('B')
        cmode           = params[0]
        cycle           = params[1]
        
        if cmode == "Encrypt":
            cycleKey    = array('B', self.eKeys[cycle])
        elif cmode == "Decrypt":
            cycleKey    = array('B', self.dKeys[cycle])
        
        if self.debug:
            print "CYCLE-KEY        :\t",cycleKey.tostring().encode('hex')
        
        for i in range(len(data)):
            dataholder.append(data[i] ^ cycleKey[keyplaceholder])
            if keyplaceholder == len(cycleKey)-1:
                keyplaceholder = 0
                cycleKey.append(cycleKey[0])
                cycleKey.pop(0)       
            else:
                keyplaceholder += 1
        
        if self.debug:
            print cmode+"Cycle-"+str(cycle),"-IN :\t",data.tostring().encode('hex')
            print cmode+"Cycle-"+str(cycle),"-OUT:\t",dataholder.tostring().encode('hex'),"\n"
        
        return dataholder
    
  
    """
    Core element bring together all of the above for encryption
    *NOTE - trying to shove larger amounts of data in here wil give you issues
    call directly for strings or other small variable storage
    for large data blocks see below
    """
    def Encrypt(self, data):    
        data        = array('B', data)
        for cycle in range(self.cycles):
            params  = ("Encrypt", cycle)
            data    = self.Cycle(self.SetDataVector(data, params), params)      
            
        return data.tostring()
          
  
    """
    Generator using previous encrypt call, but in a sensible way for large
    amounts of data that will be broken into blocks according to the set
    BLOCK_SZ.  
    """
    def EncryptBlock(self, bdata):
        while True:            
            block = bdata[:(min(len(bdata), self.block_sz))]
            if not block:
                break
            bdata = bdata[len(block):]
            yield self.Encrypt(block)
       

    """
    Generator widget for easily encryption files
    """
    def EncryptFile(self, FileObject):
        while True:
            data = FileObject.read(self.block_sz)
            if not data:
                break
            yield self.Encrypt(data)
           
        
    """
    Core of decryption
    """
    def Decrypt(self, data):
        data        = array('B', data)

        for cycle in range(self.cycles):
            params  = ("Decrypt", cycle)
            data    = self.SetDataVector(self.Cycle(data, params), params)
        
        return data.tostring()
    
  
    """
    Generator decrypt large block data
    """  
    def DecryptBlock(self, bdata):
        while True:
            block = bdata[:(min(len(bdata), self.block_sz))]
            if not block:
                break
            bdata = bdata[len(block):]
            yield self.Decrypt(block)
          
        
    """
    Generator widget for file decryption
    """ 
    def DecryptFile(self, FileObject):
        while True:
            data = FileObject.read(self.block_sz)
            if not data:
                break
            yield self.Decrypt(data)
           
    
    """
    HMAC "ish" widget primarily for use with sockets, hashing key to data
    helps ensure data integrity and authentication, do it this way to stay
    lean rather than import another module
    """
    def GenHMAC(self, data):
        hmac = sha1(self.key.encode('hex')+data.encode('hex')).hexdigest()
        return hmac
 
 
if __name__ == '__main__':       
            
    
    ############################################################################
    # Usage Example this is not the crackme cipher in the above comment
    
    
    key     =  "My Secret Key Blah Blah Blah"
    plain   =  "THIS IS MY MESSAGE AND STUFF AND JUNK I WANT TO HIDE ABC123 "
    cipher  =  ""
    dcrypt  =  ""
    text    =  "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do"
    text    += " eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut"
    text    += " enim ad minim veniam, quis nostrud exercitation ullamco laboris"
    text    += " nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor"
    text    += " in reprehenderit in voluptate velit esse cillum dolore eu fugiat"
    text    += " nulla pariatur. Excepteur sint occaecat cupidatat non proident,"
    text    += " sunt in culpa qui officia deserunt mollit anim id est laborum."

    print "PLAIN TXT          :\t",plain,"  SZ:",len(plain)
    print "PLAIN KEY          :\t",key
   
    #Create Two Instances That Will Pass Back And Forth Data Must Have Same init values of course
    #Block_SZ wont matter unless your calling the larger data handling methods
    
    crypt1 =  SimpleCrypt(INITKEY=key, DEBUG=True, CYCLES=3, BLOCK_SZ=25, KEY_ADV=5, KEY_MAGNITUDE=1)
    crypt2 =  SimpleCrypt(INITKEY=key, DEBUG=True, CYCLES=3, BLOCK_SZ=25, KEY_ADV=5, KEY_MAGNITUDE=1)
    
    #SIMPLE DATA ENCRYPTION TEST ! NOT SUITABLE FOR LARGE VOLUMES -USE BELOW
    cipher = crypt1.Encrypt(plain) 
    dcrypt = crypt2.Decrypt(cipher)
    
    """
    #TEST FOR ENCRYPTING LARGER AMOUNTS OF DATA
    
    plain = text*20
    
    crypt.block_sz = 50
    for c in crypt1.EncryptBlock(plain):
        print "BLOCK:                \t",c.encode('hex')
        cipher += c

    #Here you could Base64 or Hex encode and pump through a socket
    #Careful Base64 is smaller than Hex but python base64.encodestring()
    #adds newline chars "\n", So use something like cipher = cipher[:-1]
    #before sending on socket else will corrupt the cipher on the otherside.
    
    for d in crypt2.DecryptBlock(cipher):
        dcrypt += d
        
    """
    
    """
    #TEST FOR ENCRYPTING FILES - VIEW ACTUAL FILES FOR RESULTS
    import os
    if not os.path.exists("test.txt"):
        fp = open("test.txt", "wb+") #Make sure to use rb or wb for binary files 
        fp.write(text*1024)
        fp.close()
        
    fp0 = open("test.txt", "rb+")
    fp1 = open("cipher.txt", "wb+")
    
    crypt.block_sz = 256
    for cipher in crypt1.EncryptFile(fp0):
        fp1.write(cipher)
    fp0.close()
    fp1.close()
    
    fp2 = open("cipher.txt", "rb+")
    fp3 = open("decrypted.txt", "wb+")
        
    for decrypt in crypt2.DecryptFile(fp2):
        fp3.write(decrypt)    
    
    fp2.close()
    fp3.close()
    """
    
    
    print "CIPHER TXT         :\t",cipher.encode('hex'),"  SZ:",len(cipher),"\n\n"
    print "#"*99,"\n\n"
    print "PLAIN TXT          :\t",plain,"\t",sha1(plain).digest().encode('hex')
    print "DECRYPT TXT        :\t",dcrypt,"\t",sha1(dcrypt).digest().encode('hex')
    
    

1 comment

a 11 years, 1 month ago  # | flag

vdata.pop(len(vdata)-1) can be written as vdata.pop()