def __init__(self, umacKey, tagLength = 64): self.taglen = tagLength/8 self.iters = iters = max(1, min(4,tagLength//32)) # setup keys def kdf(kdfCipher, index, numbytes): ct = [ kdfCipher.encrypt('%s%s%s%s' % ('\x00' * 7, chr(index), '\x00' * 7, chr(i+1))) for i in xrange((numbytes+15)//16) ] return (''.join(ct))[ : numbytes] kdfCipher = rijndael.rijndael(umacKey) self.pdfCipher = rijndael.rijndael(kdf(kdfCipher,0,len(umacKey))) # L1Key is a sequence of tuples, each (32-bit * 256) L1Key = kdf(kdfCipher, 1, 1024 + (iters - 1) * 16) self.L1Key = [ struct.unpack('>256I', L1Key[16*i:16*i+1024]) for i in xrange(iters) ] # L2Key is a sequence of tuples, each (64-bit, 128-bit) L2Key = kdf(kdfCipher, 2, iters * 24) L2Key = [ struct.unpack('>3Q', L2Key[24*i:24*(i+1)]) for i in xrange(iters) ] self.L2Key = [ (L2Key[i][0] & MP64, ((L2Key[i][1] << 64) + L2Key[i][2]) & MP128) for i in xrange(iters) ] # L3Key is a sequence of tuples, each ( [64-bit * 8], 32-bit ) tmp1 = kdf(kdfCipher, 3, iters * 64) tmp1 = [ struct.unpack('>8Q', tmp1[64*i:64*(i+1)]) for i in xrange(iters) ] tmp1 = [ map(lambda x : x % (2**36 - 5), i) for i in tmp1 ] tmp2 = kdf(kdfCipher, 4, iters * 4) tmp2 = struct.unpack('>%sI' % str(iters), tmp2) self.L3Key = zip(tmp1, tmp2) # Setup empty lists to accumulate L1Hash outputs self.L1Out = [ list() for i in xrange(iters) ] # A sequence of empty lists self.L3Out = list()
def encode(self, code, realcodesize=None): try: key = "00000000000000000000000000000000" key = key.decode("hex") code = code.decode("hex") if realcodesize == None: realcodesize = len(code) codesize = len(code) if codesize == 0: return None if codesize == 16: r = rijndael.rijndael(key, block_size=16) code = r.encrypt(code) elif codesize > 16: while codesize % 16 != 0: code = code.encode("hex") code = code + "00" code = code.decode("hex") codesize = len(code) r = rijndael.rijndael(key, block_size=16) text = "" while len(code) > 15: fragment = code[:16] code = code[16:] fragment = r.encrypt(fragment) text = text + fragment code = text elif codesize > 0 and codesize < 16: while codesize < 16: code = code.encode("hex") code = code + "00" code = code.decode("hex") codesize = len(code) r = rijndael.rijndael(key, block_size=16) code = r.encrypt(code) length_raw = realcodesize length_crypt = ((codesize + 7) / 8) length_crypt = int(length_crypt) length_crypt = length_crypt * 8 length_raw = hex(length_raw) length_crypt = hex(length_crypt) length_raw = length_raw[2:] length_crypt = length_crypt[2:] while len(length_raw) < 8: length_raw = "0" + length_raw while len(length_crypt) < 8: length_crypt = "0" + length_crypt #print length_raw, length_crypt length_raw = length_raw.decode("hex") length_crypt = length_crypt.decode("hex") data = length_crypt + length_raw + code except Exception: print "[crypt]", "error on encode /", traceback.format_exc() data = None return data
def encode(self, code, realcodesize=None): try: key = "00000000000000000000000000000000" key = key.decode("hex") code = code.decode("hex") if realcodesize == None: realcodesize = len(code) codesize = len(code) if codesize == 0: return None if codesize == 16: r = rijndael.rijndael(key, block_size = 16) code = r.encrypt(code) elif codesize > 16: while codesize % 16 != 0: code = code.encode("hex") code = code + "00" code = code.decode("hex") codesize = len(code) r = rijndael.rijndael(key, block_size = 16) text = "" while len(code) > 15: fragment = code[:16] code = code[16:] fragment = r.encrypt(fragment) text = text + fragment code = text elif codesize > 0 and codesize < 16: while codesize < 16: code = code.encode("hex") code = code + "00" code = code.decode("hex") codesize = len(code) r = rijndael.rijndael(key, block_size = 16) code = r.encrypt(code) length_raw = realcodesize length_crypt = ((codesize + 7) / 8) length_crypt = int(length_crypt) length_crypt = length_crypt * 8 length_raw = hex(length_raw) length_crypt = hex(length_crypt) length_raw = length_raw[2:] length_crypt = length_crypt[2:] while len(length_raw) < 8: length_raw = "0" + length_raw while len(length_crypt) < 8: length_crypt = "0" + length_crypt #print length_raw, length_crypt length_raw = length_raw.decode("hex") length_crypt = length_crypt.decode("hex") data = length_crypt + length_raw + code except Exception: print "[crypt]","error on encode /", traceback.format_exc() data = None return data
def decode(self, code): try: key = "00000000000000000000000000000000" key = key.decode("hex") if len(code) < 16: return None, None textlength = int(code[8:16], 16) code = code[16:] code = code.decode("hex") codesize = len(code) if codesize == 0: return None, None if codesize % 16 != 0: print "error on decode: block size don't match", code.encode( "hex") return None, None r = rijndael.rijndael(key, block_size=16) if codesize > 16: text = "" while len(code) > 15: fragment = code[:16] code = code[16:] fragment = r.decrypt(fragment) text = text + fragment elif codesize == 16: text = r.decrypt(code) text = text.encode("hex") except Exception: print "[crypt]", "error on decode /", traceback.format_exc() text, textlength = None, None return text, textlength
def retrieve_passcode(self, count): if not hasattr(self, 'rijndael'): self.rijndael = rijndael(self.key.decode('hex'), block_size = 16) # Pack the count into a 128-bit block (1> 0x01x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00) block_128bit = pack('<2Q', (count & 0xFFFFFFFF), (count << 128) & 0xFFFFFFFF) # Feed the 128-bit block to rijndael block = self.rijndael.encrypt(block_128bit) # Swap the endian block = block[::-1] # Convert the block into a number num = 0 for x in block: num = num * 256 num = num + ord(x) passcode = [] character_set_len = len(self.character_set) # Perform the long division for i in range(self.code_length): passcode.append(self.character_set[num%character_set_len]) num = num/character_set_len return ''.join(passcode) # Join the passcode into a string seperated by '' (nothing)
def encryptFlashData(nonce, key, data, imageLen): encyptedBlock = '' if imageLen % 16 != 0: for x in range(16 - imageLen % 16): data = data + chr(255) imageLen = len(data) r = rijndael(key, block_size=16) for x in range(imageLen / 16): encryptNonce = '' for i in nonce: tempString = '%08x' % i y = 0 while y < 8: encryptNonce = encryptNonce + chr( string.atoi(tempString[y:y + 2], 16)) y = y + 2 encChunk = r.encrypt(encryptNonce) if nonce[3] == 4294967295: nonce[3] = 0 else: nonce[3] += 1 chunk = data[x * 16:(x + 1) * 16] lchunk = list(map(ord, chunk)) lencChunk = list(map(ord, encChunk)) outputString = '' loutChunk = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for i in range(16): loutChunk[i] = lchunk[i] ^ lencChunk[i] encyptedBlock = encyptedBlock + chr(lchunk[i] ^ lencChunk[i]) return encyptedBlock
def aes_decrypt(indata,size,key): #Decryption decdata = "" r = rijndael.rijndael(key) for i in range(0,size,16): decdata+= r.decrypt(indata[i:i+16]) return decdata
def aes_encrypt(indata,size,key): #Encryption encdata = "" r = rijndael.rijndael(key) for i in range(0,size,16): encdata+= r.encrypt(indata[i:i+16]) return encdata
def decode(self,code): try: key = "00000000000000000000000000000000" key = key.decode("hex") if len(code) < 16: return None,None textlength = int(code[8:16],16) code = code[16:] code = code.decode("hex") codesize = len(code) if codesize == 0: return None,None if codesize % 16 != 0: print "error on decode: block size don't match",code.encode("hex") return None,None r = rijndael.rijndael(key, block_size = 16) if codesize > 16: text = "" while len(code) > 15: fragment = code[:16] code = code[16:] fragment = r.decrypt(fragment) text = text + fragment elif codesize == 16: text = r.decrypt(code) text = text.encode("hex") except Exception: print "[crypt]","error on decode /", traceback.format_exc() text,textlength = None,None return text,textlength
def cbc_decrypt(msg, IV, key, size=32): r = rijndael(key, size) pad = zeropad(size) cri = cbc(pad, r, IV) return cri.decrypt(msg)
def extract_data(): f = open(sys.argv[2],"rb") f.seek(datapool_offset,0) md34test = f.read(8) f.seek(datapool_offset,0) if("NEIWAIJM" == md34test): print("Microdog 3.4 Library Detected.") decdata = f.read(MH34_DATAPOOL_SIZE) f.close() else: encdata = f.read(MH40_DATAPOOL_SIZE) decdata = "" key = f.read(MH40_KEY_SIZE) f.close() #Decryption r = rijndael.rijndael(key) for i in range(0,MH40_DATAPOOL_SIZE,16): decdata+= r.decrypt(encdata[i:i+16]) dog_id = struct.unpack("<I",decdata[OFFSET_SN:OFFSET_SN+4])[0] dog_data = struct.unpack(">Q",decdata[OFFSET_DOGID_LO:OFFSET_DOGID_LO+4]+decdata[OFFSET_DOGID_HI:OFFSET_DOGID_HI+4])[0] print("DogID: %04x" % dog_id) print("Dogdata: %08x" % dog_data) #Write decrypted output to file. f = open(sys.argv[3],"wb") f.write(decdata) f.close() print("Wrote decrypted datapool to disk.") exit(0)
def cbc_encrypt(msg, IV, key, size=32): r = rijndael(key, size) pad = zeropad(size) cri = cbc(pad, r, IV) encod = cri.encrypt(msg) return encod #.encode('hex')
def decrypt(key, encoded): padded_key = key.ljust(KEY_SIZE, '\0') ciphertext = base64.b64decode(encoded) r = rijndael.rijndael(padded_key, BLOCK_SIZE) padded_text = '' for start in range(0, len(ciphertext), BLOCK_SIZE): padded_text += r.decrypt(ciphertext[start:start+BLOCK_SIZE]) plaintext = padded_text.split('\x00', 1)[0] return plaintext
def encrypt(key, plaintext): padded_key = key.ljust(KEY_SIZE, '\0') padded_text = plaintext + (BLOCK_SIZE - len(plaintext) % BLOCK_SIZE) * '\0' r = rijndael.rijndael(padded_key, BLOCK_SIZE) ciphertext = '' for start in range(0, len(padded_text), BLOCK_SIZE): ciphertext += r.encrypt(padded_text[start:start+BLOCK_SIZE]) encoded = base64.b64encode(ciphertext) return encoded
def encrypt(key, plaintext): padded_key = key.ljust(KEY_SIZE, '\0') padded_text = plaintext + (BLOCK_SIZE - len(plaintext) % BLOCK_SIZE) * '\0' r = rijndael.rijndael(padded_key, BLOCK_SIZE) ciphertext = '' for start in range(0, len(padded_text), BLOCK_SIZE): ciphertext += r.encrypt(padded_text[start:start + BLOCK_SIZE]) encoded = base64.b64encode(ciphertext) return encoded
def decrypt(key, encoded): padded_key = key.ljust(KEY_SIZE, '\0') ciphertext = base64.b64decode(encoded) r = rijndael.rijndael(padded_key, BLOCK_SIZE) padded_text = '' for start in range(0, len(ciphertext), BLOCK_SIZE): padded_text += r.decrypt(ciphertext[start:start + BLOCK_SIZE]) plaintext = padded_text.split('\x00', 1)[0] return plaintext
def e(hash, m): """ Internal method used by L{decode}. """ n = len(hash) aes = rijndael.rijndael(hash) aes_m = aes.encrypt(m) hash = "" for i in range(0, n): hash += chr(ord(aes_m[i]) ^ ord(m[i])) return hash
def au8CRAResponse(u32Response, abEncryptKey, abMACAddress): EncryptEngine = rijndael(abEncryptKey, block_size=16) DoubleMac = abMACAddress + abMACAddress encMac = EncryptEngine.encrypt(DoubleMac) lchunk = list(map(ord, struct.pack('>LLLL', u32Response, u32Response, u32Response, u32Response))) lencChunk = list(map(ord, encMac)) EncryptedChunk = '' for i in range(16): EncryptedByte = lchunk[i] ^ lencChunk[i] EncryptedChunk = EncryptedChunk + chr(EncryptedByte) return EncryptedChunk
def Encrypt(self, fstream, key): if len(key) > 32: raise ValueError('Key too long') key = key.ljust(32) f = open(self.filename, 'wb') padding = len(fstream) % 32 fstream += " " * (32 - padding) obj = rijndael(key, block_size=32) string = '' for i in range(len(fstream) / 32): string += obj.encrypt(fstream[i * 32:i * 32 + 32]) fstream = string f.write(fstream) f.close()
def u32CRAChallenge(au8ChallengeEncrypted, abEncryptKey, abMACAddress): EncryptEngine = rijndael(abEncryptKey, block_size=16) encryptNonce = abMACAddress + abMACAddress encChunk = EncryptEngine.encrypt(encryptNonce) lchunk = list(map(ord, au8ChallengeEncrypted)) lencChunk = list(map(ord, encChunk)) DecryptedChunk = '' for i in range(16): DecryptedByte = lchunk[i] ^ lencChunk[i] DecryptedChunk = DecryptedChunk + chr(DecryptedByte) lstChallenge = struct.unpack('>LLLL', DecryptedChunk) return lstChallenge[0]
def Decrypt(self, key): if len(key) > 32: raise ValueError('Key too long') key = key.ljust(32) try: f = open(self.filename, 'rb') fstream = f.read() f.close() obj = rijndael(key, block_size=32) string = '' for i in range(len(fstream) / 32): string += obj.decrypt(fstream[i * 32:i * 32 + 32]) return string except: print 'unable to read file: ', sys.exc_info()[0] return ''
def decrypt_file(encrypted_filename, decrypted_filename, rsa_cipher): with open(encrypted_filename, 'rb') as encrypted_file: # Get the file size by seeking into end encrypted_file.seek(0, io.SEEK_END) file_size = encrypted_file.tell() # Some checks encrypted_file.seek(0) if 0 != encrypted_file.tell() or file_size < 4: raise DecryptError() header_size = unpack('I', encrypted_file.read(4))[0] if header_size > file_size: raise DecryptError() # Read and decrypt header header = encrypted_file.read(header_size) try: decrypted_header = cipher.decrypt(header) except: raise DecryptError() # Read initialization vector and key from header aes_iv_length = unpack('I', decrypted_header[0:4])[0] aes_iv_start = 4 aes_iv = decrypted_header[aes_iv_start:aes_iv_start + aes_iv_length] aes_key_length_start = aes_iv_start + aes_iv_length aes_key_length = unpack('I', decrypted_header[aes_key_length_start:aes_key_length_start + 4])[0] aes_key_start = aes_key_length_start + 4 aes_key = decrypted_header[aes_key_start:aes_key_start + aes_key_length] # Read encrypted file into memory ciphertext = encrypted_file.read() # Initialize cipher and crypto-block-chain rjn_cipher = rijndael(aes_key, 32) padding = zeropad(32) cbc_cipher = cbc(padding, rjn_cipher, aes_iv) # Decrypt the file decrypted_ct = cbc_cipher.decrypt(ciphertext) with open(decrypted_filename, 'wb') as decrypted_file: decrypted_file.write(decrypted_ct)
def _decrypt_password(self, password): key = settings.get('KEY') if not key: return password import rijndael import base64 dcode = base64.b64decode(password) key_size = 16 block_size = 32 key = key.ljust(key_size, '\0') enc = rijndael.rijndael(key, block_size) padded_text = '' # tweak from padded text from php encryption # http://stackoverflow.com/questions/8217269/decrypting-strings-in-python-that-were-encrypted-with-mcrypt-rijndael-256-in-php for start in range(0, len(dcode), block_size): padded_text += enc.decrypt(dcode[start:start+block_size]) password = padded_text.split('\x00', 1)[0] return password
def encrypt(key, plaintext): padded_key = key.ljust(KEY_SIZE, '\0') padded_text = plaintext + (BLOCK_SIZE - len(plaintext) % BLOCK_SIZE) * '\0' # could also be one of #if len(plaintext) % BLOCK_SIZE != 0: # padded_text = plaintext.ljust((len(plaintext) / BLOCK_SIZE) + 1 * BLOCKSIZE), '\0') # -OR- #padded_text = plaintext.ljust((len(plaintext) + (BLOCK_SIZE - len(plaintext) % BLOCK_SIZE)), '\0') r = rijndael.rijndael(padded_key, BLOCK_SIZE) ciphertext = '' for start in range(0, len(padded_text), BLOCK_SIZE): ciphertext += r.encrypt(padded_text[start:start+BLOCK_SIZE]) encoded = base64.b64encode(ciphertext) return encoded
def encrypt(key, plaintext): padded_key = key.ljust(KEY_SIZE, '\0') padded_text = plaintext + (BLOCK_SIZE - len(plaintext) % BLOCK_SIZE) * '\0' # could also be one of #if len(plaintext) % BLOCK_SIZE != 0: # padded_text = plaintext.ljust((len(plaintext) / BLOCK_SIZE) + 1 * BLOCKSIZE), '\0') # -OR- #padded_text = plaintext.ljust((len(plaintext) + (BLOCK_SIZE - len(plaintext) % BLOCK_SIZE)), '\0') r = rijndael.rijndael(padded_key, BLOCK_SIZE) ciphertext = '' for start in range(0, len(padded_text), BLOCK_SIZE): ciphertext += r.encrypt(padded_text[start:start + BLOCK_SIZE]) encoded = base64.b64encode(ciphertext) return encoded
def convert_data(): #Get target key f = open(sys.argv[2],"rb") f.seek(datapool_offset,0) md34test = f.read(8) #Make a copy of our input file. f.seek(0,0) outdata = f.read() if("NEIWAIJM" == md34test): print("Microdog 3.4 Library Detected.") encdata = f.read(MH34_DATAPOOL_SIZE) outdata = outdata[:datapool_offset] + encdata + outdata[datapool_offset+MH34_DATAPOOL_SIZE:] f.close() else: f.seek(datapool_offset+MH40_DATAPOOL_SIZE,0) key = f.read(MH40_KEY_SIZE) f.close() #Get target data f = open(sys.argv[5],"rb") decdata = f.read() f.close() #Encrypt target data with key r = rijndael.rijndael(key) encdata = "" for i in range(0,MH40_DATAPOOL_SIZE,16): encdata+= r.encrypt(decdata[i:i+16]) #Modify our in-memory binary copy with the new data. outdata = outdata[:datapool_offset] + encdata + outdata[datapool_offset+MH40_DATAPOOL_SIZE:] #Write modified binary to file. f = open(sys.argv[3],"wb") f.write(outdata) f.close()
def bin2hex(b): r = "" for i in range(0, len(b)): r = ''.join([r, '%02x' % ord(b[i])]) return r def shuffle(b): lut = (0xf, 7, 0xb, 5, 0xa, 0xd, 6, 3, 9, 4, 2, 1, 0, 8, 0xc, 0xe) s = [0,1,2,3,4,5,6,7,9,9,10,11,12,13,14,15] for i in range(0, 16): s[lut[i]] = b[i] return ''.join(s) k = hex2bin("00010203050607080A0B0C0D0F101112") r = aes.rijndael(k, block_size = 16) p = hex2bin("506812A45F08C889B97F5980038B8359") c1 = r.encrypt(p) shuffled = shuffle(p) print bin2hex(p) print bin2hex(shuffled) c2 = r.encrypt(shuffled) print bin2hex(c1) print bin2hex(c2) print bin2hex(shuffle(c2))
def __init__(self, key, mode, IV): AES.__init__(self, key, mode, IV, "python") self.rijndael = rijndael(key, 16) self.IV = IV
def applySamyGOKeyTransform(input): r = rijndael.rijndael(keys.transKey.decode('hex'), 16) return r.encrypt(input)
def generate_random_sequence_key(self): self.key = sha256(urandom(256)).hexdigest() self.rijndael = rijndael(self.key.decode('hex'), block_size = 16)
def __init__(self, key=''): if key: self.key = key self.rijndael = rijndael(self.key.decode('hex'), block_size = 16)
import base64 try: arr = [] num = 1 while num <= 32: arr.append( num ) num += 1 key = string.join( map( chr, arr ), '' ) arr = [ 65, 110, 68, 26, 69, 178, 200, 219, 65, 110, 68, 26, 69, 178, 200, 219 ] iv = string.join( map( chr, arr ), '' ) del arr, num r = rijndael.rijndael( key, 16 ) except Exception, ex: print type(ex) print ex # Pads a string with null bytes if the length of the string # is not a multiple of the BLOCKSIZE being used for the # current implementation of the Rijndael algorithm. # def PadString(string, multiple): padded = string blocksize = multiple while( (len(padded) % blocksize) != 0 ): padded = padded + '\0' return padded
def gen_rand(): return [[random.randint(0, 255) for j in range(0, 4)] for i in range(0, 4)] e = aes.aes() total = 1024 passed = 0 for i in range(total): key = gen_rand() pt = gen_rand() r = rijndael.rijndael(e.hex_to_packed(key), block_size = 16) ct = e.encblock(pt, key) gold_ct = e.packed_to_hex(r.encrypt(e.hex_to_packed(pt))) if gold_ct != ct: print "ERROR in test vector #%i!" % i print "Key: %s" % e.hex_to_str(key) print "Plaintext: %s" % e.hex_to_str(pt) print "Ciphertext: %s" % e.hex_to_str(gold_ct) print "Calculated: %s" % e.hex_to_str(ct) else: passed += 1 print "Passed %i / %i tests (%02.1f%%)" % (passed, total, 100.0*float(passed)/total) if passed != total: