Exemple #1
2
    def runTest(self):
        # Encrypt/Decrypt data and test output parameter

        cipher = ARC2.new(b'4'*16, ARC2.MODE_ECB)

        pt = b'5' * 16
        ct = cipher.encrypt(pt)

        output = bytearray(16)
        res = cipher.encrypt(pt, output=output)
        self.assertEqual(ct, output)
        self.assertEqual(res, None)
        
        res = cipher.decrypt(ct, output=output)
        self.assertEqual(pt, output)
        self.assertEqual(res, None)

        import sys
        if sys.version[:3] != '2.6':
            output = memoryview(bytearray(16))
            cipher.encrypt(pt, output=output)
            self.assertEqual(ct, output)
        
            cipher.decrypt(ct, output=output)
            self.assertEqual(pt, output)

        self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16)
        self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16)

        shorter_output = bytearray(7)
        self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
        self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
Exemple #2
0
    def runTest(self):
        ARC2.new(b'\x00' * 16, ARC2.MODE_ECB, effective_keylen=40)
        self.assertRaises(ValueError, ARC2.new, bchr(0) * 4, ARC2.MODE_ECB)
        self.assertRaises(ValueError, ARC2.new, bchr(0) * 129, ARC2.MODE_ECB)

        self.assertRaises(ValueError, ARC2.new, bchr(0) * 16, ARC2.MODE_ECB,
                          effective_keylen=39)
        self.assertRaises(ValueError, ARC2.new, bchr(0) * 16, ARC2.MODE_ECB,
                          effective_keylen=1025)
Exemple #3
0
 def _getcipher_real(self, key, algo):
     """
     do the real job of decrypting using functions
     form PyCrypto
     """
     if (algo == "AES"):
         key = hashlib.sha256(key)
         cipher = cAES.new(key.digest(), cAES.MODE_ECB)
     elif (algo == 'ARC2'):
         cipher = cARC2.new(key, cARC2.MODE_ECB)
     elif (algo == 'ARC4'):
         raise CryptoUnsupportedException("ARC4 is currently unsupported")
     elif (algo == 'Blowfish'):
         cipher = cBlowfish.new(key, cBlowfish.MODE_ECB)
     elif (algo == 'CAST'):
         cipher = cCAST.new(key, cCAST.MODE_ECB)
     elif (algo == 'DES'):
         if len(key) != 8:
             raise Exception("DES Encrypted keys must be 8 characters "
                             "long!")
         cipher = cDES.new(key, cDES.MODE_ECB)
     elif (algo == 'DES3'):
         key = hashlib.sha224(key)
         cipher = cDES3.new(key.digest()[:24], cDES3.MODE_ECB)
     elif (algo == 'XOR'):
         raise CryptoUnsupportedException("XOR is currently unsupported")
     else:
         raise CryptoException("Invalid algorithm specified")
     return cipher
Exemple #4
0
 def _getcipher_real(self, key, algo):
     """
     do the real job of decrypting using functions
     form PyCrypto
     """
     if (algo == "AES"):
         key = self._padkey(key, [16, 24, 32])
         cipher = cAES.new(key, cAES.MODE_ECB)
     elif (algo == 'ARC2'):
         cipher = cARC2.new(key, cARC2.MODE_ECB)
     elif (algo == 'ARC4'):
         raise CryptoUnsupportedException("ARC4 is currently unsupported")
     elif (algo == 'Blowfish'):
         cipher = cBlowfish.new(key, cBlowfish.MODE_ECB)
     elif (algo == 'CAST'):
         cipher = cCAST.new(key, cCAST.MODE_ECB)
     elif (algo == 'DES'):
         self._padkey(key, [8])
         cipher = cDES.new(key, cDES.MODE_ECB)
     elif (algo == 'DES3'):
         key = self._padkey(key, [16, 24])
         cipher =  cDES3.new(key, cDES3.MODE_ECB)
     elif (algo == 'XOR'):
         raise CryptoUnsupportedException("XOR is currently unsupported")
     else:
         raise CryptoException("Invalid algorithm specified")
     return cipher
Exemple #5
0
	def encrypt(self, key, mode, data, IV):
		if(mode == 1):
			obj = ARC2.new(str(key), ARC2.MODE_ECB, str(IV))
			return obj.encrypt(data)

		elif(mode == 2):
			obj = ARC2.new(str(key), ARC2.MODE_CBC, str(IV))	
			return obj.encrypt(data)

		elif(mode == 3):
			obj = ARC2.new(str(key), ARC2.MODE_CFB, str(IV))
			return obj.encrypt(data)

		elif(mode == 4):
			obj = ARC2.new(str(key), ARC2.MODE_OFB, str(IV))
			return obj.encrypt(data)
def decryptAES(file, ciphertext):
    # print "AES"
    text = b''
    # base64_decoded_text = base64.b64decode(ciphertext)
    base64_decoded_text =ciphertext.decode('base64')
    key = "0xccb97558940b82637c8bec3c770f86fa3a391a56"


    #read salt from file
    fo = open(file, "rb")
    salt = readBytes(fo)

    version = struct.unpack('b', fo.read(1))[0]

    # read encryptionKey from file
    if version != -1:
        encrypt_key = readBytes(fo)
        if version >=2:
            encrypt_key = readBytes(fo)

    # var 'key2key' means RC2 key to AES key
    print "encrypt_key(%d): %s" % (len(encrypt_key), encrypt_key.encode('hex'))
    hasher = SHA.new()
    hasher.update(salt)
    hasher.update(key)
    # hasher.update(key)
    # hasher.update(salt)
    key2key = hasher.digest()
    print key2key.encode('hex')

    for i in range(1, 5):
        hasher = SHA.new()
        hasher.update(key2key)
        key2key = hasher.digest()
        print key2key.encode('hex')

    print "key2key len:", len(key2key)
    print "key2key:", key2key.encode("hex")

    print encrypt_key[:8].encode('hex')
    rc2 = ARC2.new(key2key[8:], ARC2.MODE_CBC, key2key[:8])

    print encrypt_key[8:].encode('hex')
    key = rc2.decrypt(encrypt_key)

    print "key:", key.encode('hex')


    # iv = ciphertext.index(0, 16)
    # ciphertext2 = ciphertext.index(16)
    #
    # AESCipher = AES.new(key, AES.MODE_CBC, iv)
    #
    # text = AESCipher.decrypt(ciphertext2)

    fo.close()
    return text
Exemple #7
0
def decrypt_file(in_filename, out_filename, chunk_size, key, iv):
    arc2 = ARC2.new(key, ARC2.MODE_CFB, iv)

    with open(in_filename, 'r') as in_file:
        with open(out_filename, 'w') as out_file:
            while True:
                chunk = in_file.read(chunk_size)
                if len(chunk) == 0:
                    break
                out_file.write(arc2.decrypt(chunk))
Exemple #8
0
def encrypt_file(in_filename, out_filename, chunk_size, key, iv):
    arc2 = ARC2.new(key, ARC2.MODE_CFB, iv)

    with open(in_filename, 'r') as in_file:
        with open(out_filename, 'w') as out_file:
            while True:
                chunk = in_file.read(chunk_size)
                if len(chunk) == 0:
                    break
                elif len(chunk) % 16 != 0:
                    chunk += ' ' * (16 - len(chunk) % 16)
                out_file.write(arc2.encrypt(chunk))
Exemple #9
0
from Cryptodome.Cipher import ARC4 as pycryptodomex_arc4
from Cryptodome.Cipher import Blowfish as pycryptodomex_blowfish
from Cryptodome.Cipher import DES as pycryptodomex_des
from Cryptodome.Cipher import XOR as pycryptodomex_xor
from Crypto.Hash import SHA
from Crypto import Random
from Crypto.Util import Counter
from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers import algorithms
from cryptography.hazmat.primitives.ciphers import modes
from cryptography.hazmat.backends import default_backend
from struct import pack

key = b'Sixteen byte key'
iv = Random.new().read(pycrypto_arc2.block_size)
cipher = pycrypto_arc2.new(key, pycrypto_arc2.MODE_CFB, iv)
msg = iv + cipher.encrypt(b'Attack at dawn')
cipher = pycryptodomex_arc2.new(key, pycryptodomex_arc2.MODE_CFB, iv)
msg = iv + cipher.encrypt(b'Attack at dawn')

key = b'Very long and confidential key'
nonce = Random.new().read(16)
tempkey = SHA.new(key+nonce).digest()
cipher = pycrypto_arc4.new(tempkey)
msg = nonce + cipher.encrypt(b'Open the pod bay doors, HAL')
cipher = pycryptodomex_arc4.new(tempkey)
msg = nonce + cipher.encrypt(b'Open the pod bay doors, HAL')

iv = Random.new().read(bs)
key = b'An arbitrarily long key'
plaintext = b'docendo discimus '
Exemple #10
0
# -*- coding: utf-8 -*-
"""
Created on Sun Jan  7 09:55:37 2018

@author: Santi
"""
import os
from Crypto.Cipher import ARC2

cipher = ARC2.new('ELPbestAsignaturaEver')

if os.path.exists("executions"):
    fileexecutions = open("executions", 'rb')
    n = fileexecutions.read()
    fileexecutions.close()
    print(n)
    n = cipher.decrypt(n)
    n = str(n).strip('b').strip("'").strip(' ')
    n = int(n) + 1
else:
    n = 1
numberExecutions = open("nexes.txt", 'w')
numberExecutions.write(str(n))
numberExecutions.close()
tocipher = str(n)
i = 1
proof = False
while not proof:
    if len(tocipher) < (8 * i):
        tocipher = tocipher + " "
    elif len(tocipher) > (8 * i):
Exemple #11
0
def pycrypto_rc2(keysize=32, data_size=1024, mode_str="", mode=ARC2.MODE_EAX):
    plaintext = get_random_bytes(data_size * 1024)
    secret = get_random_bytes(keysize)
    cipher = ARC2.new(key=secret, mode=mode)
    _ = cipher.iv + cipher.encrypt(plaintext)
Exemple #12
0
def mitmFilter(plain, cipher, key):
    enc = ARC2.new(key[0], ARC2.MODE_ECB).encrypt(plain)
    dec = ARC2.new(key[1], ARC2.MODE_ECB).decrypt(cipher)
    return enc == dec
Exemple #13
0
keyspace = (''.join(x).decode('hex') for x in
               itertools.product(hexchars, repeat=keysize*2))

plain = raw_input("Plaintext> ").decode('hex')
cipher = raw_input("Ciphertext> ").decode('hex')

pairs = (mitmPair(plain, cipher, key) for key in keyspace)
encDict = {}
decDict = {}
for pair in pairs:
    encDict[pair[0]] = pair[2]
    decDict[pair[1]] = pair[2]
keyspace = [(encDict[m], decDict[m])
            for m in encDict.viewkeys() & decDict.viewkeys()]

# while we have not narrowed the key
while len(keyspace) != 1:
    print("Keyspace of {} remaining keys".format(len(keyspace)))
    plain = raw_input("Plaintext> ").decode('hex')
    cipher = raw_input("Ciphertext> ").decode('hex')
    keyspace = [key for key in keyspace if mitmFilter(plain, cipher, key)]

key = keyspace[0]
print("Found key {}{}".format(key[0].encode('hex'), key[1].encode('hex')))
c1 = ARC2.new(key[0], ARC2.MODE_ECB)
c2 = ARC2.new(key[1], ARC2.MODE_ECB)

while True:
    cipher = raw_input("Ciphertext> ").decode('hex')
    print("Plaintext: {}".format(c1.decrypt(c2.decrypt(cipher))))
Exemple #14
0
 def encrypt(self, txt, pre, enc, post, pwd, tags=True):
     #
     if type(txt) != type('') and type(txt) != type(u''):
         raise TypeError('Invalid data type for encryption: "%s" !' %
                         str(type(txt)))
     #
     # Scramble operation.
     if not pre or pre == 'N' or pre == 'None':
         pass
     elif pre == 'ZLIB' or pre == SCRAMBLE_D['ZLIB']:
         txt = zlib.compress(txt)
     elif pre == 'BZ2' or pre == SCRAMBLE_D['BZ2']:
         txt = bz2.compress(txt)
     elif pre == 'ROT13' or pre == SCRAMBLE_D['ROT13']:
         txt = string.translate(txt, ROT)
     else:
         raise Exception('Invalid scramble "%s" !' % pre)
     #
     # Check RSA key path.
     if enc in ['RSA', 'RSA'] and not os.path.exists(self.rsa_path):
         print('RSA encryption must specify a valid path !')
         self.__error(2, pre, enc, post, field='L')
         return
     #
     pwd = self._fix_password(pwd, enc)
     #
     if enc == 'AES' or enc == ENC['AES']:
         o = AES.new(pwd, mode=3, segment_size=16)
     elif enc == 'ARC2' or enc == ENC['ARC2']:
         o = ARC2.new(pwd, mode=3, segment_size=16)
     elif enc == 'CAST' or enc == ENC['CAST']:
         o = CAST.new(pwd, mode=3, segment_size=16)
     elif enc == 'Blowfish' or enc == ENC['Blowfish']:
         o = Blowfish.new(pwd, mode=3, segment_size=16)
     elif enc == 'DES3' or enc == ENC['DES3']:
         o = DES3.new(pwd, mode=3, segment_size=16)
     elif enc == 'RSA' or enc == ENC['RSA']:
         # Using Blowfish encryption for RSA.
         o = Blowfish.new(pwd, Blowfish.MODE_CFB)
     elif not enc or enc in ['None', ENC['None']]:
         o = None
     else:
         raise Exception('Invalid encryption mode "%s" !' % enc)
     #
     # Encryption operation.
     if o:
         pad_len = 16 - (len(txt) % 16)
         padding = (chr(pad_len) * pad_len)
         txt = o.encrypt(txt + padding)
     #
     # Codec operation.
     if post == 'Base64 Codec' or post == ENCODE_D['Base64 Codec']:
         if tags:
             txt = '<#>%s:%s:%s<#>%s' % \
                 (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post].replace(' Codec',''), ba.b2a_base64(txt).decode())
         else:
             txt = ba.b2a_base64(txt).decode()
     elif post == 'Base32 Codec' or post == ENCODE_D['Base32 Codec']:
         if tags:
             txt = '<#>%s:%s:%s<#>%s' % \
                 (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post].replace(' Codec',''), base64.b32encode(txt).decode())
         else:
             txt = base64.b32encode(txt).decode()
     elif post == 'HEX Codec' or post == ENCODE_D['HEX Codec']:
         if tags:
             txt = '<#>%s:%s:%s<#>%s' % \
                 (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post].replace(' Codec',''), ba.b2a_hex(txt).decode())
         else:
             txt = ba.b2a_hex(txt).decode()
     elif post == 'Quopri Codec' or post == ENCODE_D['Quopri Codec']:
         if tags:
             txt = '<#>%s:%s:%s<#>%s' % (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post].replace(' Codec',''), \
                 ba.b2a_qp(txt, quotetabs=True, header=True).decode())
         else:
             txt = ba.b2a_qp(txt, quotetabs=True, header=True).decode()
     elif post == 'Json' or post == ENCODE_D['Json']:
         if tags:
             # Format : {"pre": "AAA", "enc": "BBB", "post": "CCC", "data": "Blah blah blah"}
             txt = '{"pre": "%s", "enc": "%s", "post": "%s", "data": "%s"}' % \
                 (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post], ba.b2a_base64(txt).rstrip().decode())
         else:
             txt = json.dumps(
                 {'data': ba.b2a_base64(txt).rstrip().decode()})
     elif post == 'XML':
         if tags:
             # Format : <root><pre>AAA</pre> <enc>BBB</enc> <post>CCC</post> <data>Blah blah blah</data></root>
             txt = '<root>\n<pre>%s</pre><enc>%s</enc><post>%s</post>\n<data>%s</data>\n</root>' % \
                 (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post], ba.b2a_base64(txt).rstrip().decode())
         else:
             txt = '<root>\n<data>%s</data>\n</root>' % ba.b2a_base64(
                 txt).rstrip().decode()
     else:
         raise Exception('Invalid codec "%s" !' % post)
     #
     # The final text must be String, to be used in GUI
     return txt
Exemple #15
0
    def encrypt(self, string, isfile=False, addmeta=False):
        '''
        If key is setted up the method will encrypt the string with a path compliant result
        '''

        # If we got an encryption key
        if self.__key:

            # Start ciphering system
            if self.__algorithm == 'AESCFB':
                cipher = AES.new(self.__key, AES.MODE_CFB)
            elif self.__algorithm == 'AESECB':
                cipher = AES.new(self.__key, AES.MODE_ECB)
            elif self.__algorithm == 'ARC2CFB':
                cipher = ARC2.new(self.__key, ARC2.MODE_CFB)
            elif self.__algorithm == 'ARC2ECB':
                cipher = ARC2.new(self.__key, ARC2.MODE_ECB)
            elif self.__algorithm == 'BlowfishCFB':
                cipher = Blowfish.new(self.__key, Blowfish.MODE_CFB)
            elif self.__algorithm == 'BlowfishECB':
                cipher = Blowfish.new(self.__key, Blowfish.MODE_ECB)
            elif self.__algorithm == 'CASTCFB':
                cipher = CAST.new(self.__key, CAST.MODE_CFB)
            elif self.__algorithm == 'CASTECB':
                cipher = CAST.new(self.__key, CAST.MODE_ECB)
            elif self.__algorithm == 'DESCFB':
                cipher = DES.new(self.__key, DES.MODE_CFB)
            elif self.__algorithm == 'DESECB':
                cipher = DES.new(self.__key, DES.MODE_ECB)
            else:
                raise IOError, "Specified encryption algorithm is unkown: %s" % (
                    self.__algorithm)

            # Add padding to the string if required
            if self.padding:
                (string, padder) = self.pad(string)
            else:
                padder = ''

            # Encrypt the string
            encoded = cipher.encrypt(string)

            # Security check
            if len(encoded) != len(string):
                self.error(
                    "Encrypt => Normal and decoded string are different size: %s -> %s\n"
                    % (len(encoded), len(string)))

            # Check if is a file
            if isfile:

                # Metadata
                if not addmeta:
                    b64corrected = encoded
                else:
                    b64corrected = encoded + padder
            else:
                # Encode the result
                b64encoded = base64.b64encode(encoded)
                # Correct the result to be path compliant
                b64corrected = b64encoded.replace("/", "_")
        else:
            # Nothing to do
            b64corrected = string

        # Return the result
        return b64corrected
Exemple #16
0
def decryptRc2(rc2type, importx, filepath, export, expfilepath, inputformat,
               ivtype, iv, passwd, raw):

    if importx == 'file':

        f = open(filepath, 'r')
        raw = f.read()
        f.close()

    elif importx == 'print':

        raw = raw

    else:

        print('\033[1;31m[-]\033[0m Unknown error.')
        return False

    inp = raw

    if inputformat == 'base64':

        iput = base64.b64decode(inp)

    elif inputformat == 'raw':

        iput = inp

    elif inputformat == 'base32':

        iput = base64.b32decode(inp)

    elif inputformat == 'base16':

        iput = base64.b16decode(inp)

    elif inputformat == 'base58':

        iput = base58.b58decode(inp)

    elif inputformat == 'base85':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif inputformat == 'hex':

        iput = inp.decode('hex')

    elif inputformat == 'dec':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif inputformat == 'octal':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif inputformat == 'binary':

        iput = text_from_bits(inp)

    else:

        print('\033[1;31m[-]\033[0m Unknown error.')
        return False

    key = passwd

    if ivtype == 'randomstart':

        iv = iput[:8]
        iput = iput[8:]

    elif ivtype == 'randomend':

        iv = iput[-8:]
        iput = iput[:-8]

    elif ivtype == 'custom':

        iv = iv
        iput = iput

    elif ivtype == 'noiv':

        iv = ''
        iput = iput

    else:

        print('\033[1;31m[-]\033[0m Unknown error.')
        return False

    if rc2type == 'ecb':

        cipher = ARC2.new(key, ARC2.MODE_ECB)

    elif rc2type == 'ofb':

        cipher = ARC2.new(key, ARC2.MODE_OFB, iv)

    elif rc2type == 'cbc':

        cipher = ARC2.new(key, ARC2.MODE_CBC, iv)

    elif rc2type == 'ocb':

        cipher = ARC2.new(key, ARC2.MODE_OCB, iv)

    elif rc2type == 'ctr':

        cipher = ARC2.new(key, ARC2.MODE_CTR)

    elif rc2type == 'cfb':

        cipher = ARC2.new(key, ARC2.MODE_CFB, iv)

    else:

        print('\033[1;31m[-]\033[0m Unknown error.')
        return False

    out = cipher.decrypt(iput)

    out = unpad(out)

    if export == 'file':

        filename = open(expfilepath, 'w')
        filename.write(out)
        filename.close()

        return True

    elif export == 'print':

        return out

    else:

        print('\033[1;31m[-]\033[0m Unknown error.')
        return False
Exemple #17
0
 def decrypt(self, cipher):
     cryptor = ARC2.new(self.key, ARC2.MODE_CBC, 8 * ' ')
     return self.__extract_plain(cryptor.decrypt(cipher))
Exemple #18
0
 def encrypt(self, plain):
     cryptor = ARC2.new(self.key, ARC2.MODE_CBC, 8 * ' ')
     return cryptor.encrypt(self.__extend_plain(plain))
Exemple #19
0
from Crypto.Cipher import ARC2
from Crypto.Cipher import ARC4
from Crypto.Cipher import Blowfish
from Crypto.Cipher import DES
from Crypto.Cipher import XOR
from Crypto.Hash import SHA
from Crypto.Util import Counter
from struct import pack

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers import algorithms

key = b'Sixteen byte key'
iv = Random.new().read(ARC2.block_size)
cipher = ARC2.new(key, ARC2.MODE_CFB, iv)
msg = iv + cipher.encrypt(b'Attack at dawn')

key = b'Very long and confidential key'
nonce = Random.new().read(16)
tempkey = SHA.new(key + nonce).digest()
cipher = ARC4.new(tempkey)
msg = nonce + cipher.encrypt(b'Open the pod bay doors, HAL')

bs = Blowfish.block_size
key = b'An arbitrarily long key'
iv = Random.new().read(bs)
cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
plaintext = b'docendo discimus '
plen = bs - divmod(len(plaintext), bs)[1]
padding = [plen] * plen
from Crypto.Cipher import DES, DES3, ARC2, ARC4, Blowfish, AES
from Crypto.Random import get_random_bytes

key = b'-8B key-'
DES.new(
    key, DES.MODE_OFB
)  # Noncompliant: DES works with 56-bit keys allow attacks via exhaustive search

key = DES3.adjust_key_parity(get_random_bytes(24))
cipher = DES3.new(
    key, DES3.MODE_CFB
)  # Noncompliant: Triple DES is vulnerable to meet-in-the-middle attack

key = b'Sixteen byte key'
cipher = ARC2.new(
    key,
    ARC2.MODE_CFB)  # Noncompliant: RC2 is vulnerable to a related-key attack

key = b'Very long and confidential key'
cipher = ARC4.new(
    key
)  # Noncompliant: vulnerable to several attacks (see https://en.wikipedia.org/wiki/RC4#Security)

key = b'An arbitrarily long key'
cipher = Blowfish.new(
    key, Blowfish.MODE_CBC
)  # Noncompliant: Blowfish use a 64-bit block size makes it vulnerable to birthday attacks
Exemple #21
0
def ARC2_decrypt(msg, key):
    iv = base64.b64decode(msg)[:8]
    Dec_msg = base64.b64decode(msg)[8:]
    d = ARC2.new(key, ARC2.MODE_CBC, iv)
    plain = d.decrypt(Dec_msg)
    print("Your Encode >>> ", plain.decode('ascii'))
Exemple #22
0
 def RC2_encrypt(self, data, key, iv):
     # RC2加密函数
     encrypt = ARC2.new(key, ARC2.MODE_CFB, iv)
     data = encrypt.encrypt(data)
     return iv + data
Exemple #23
0
import numpy as np
import matplotlib.pyplot as plt
from array import *
from datetime import datetime

plt.rc('font', family='Verdana')
entime = array('d')
detime = array('d')
x = np.arange(1, 100, 1)
#size blok
BLOCK_SIZE = 32

for i in range(1, 100):
    #generation key
    secret = os.urandom(BLOCK_SIZE)
    obj = ARC2.new(secret)
    message = "InternetofThingsIoTis the future"
    print(len(message))

    # Encryption
    first = datetime.now().microsecond
    ciphertext = obj.encrypt(message)
    delta = (datetime.now().microsecond - first)
    entime.append(delta)
    print("Encryption time = " + str(delta))
    time.sleep(0.001)

    # Decode
    first = datetime.now().microsecond
    mes = obj.decrypt(ciphertext)
    delta = (datetime.now().microsecond - first)
Exemple #24
0
def encryptRc2(rc2type, importx, impfilepath, export, filepath, outputformat,
               ivtype, iv, passwd, raw, keyimport):

    if keyimport == 'base64':

        key = base64.b64decode(passwd)

    elif keyimport == 'base32':

        key = base64.b32decode(passwd)

    elif keyimport == 'base16':

        key = base64.b16decode(passwd)

    elif keyimport == 'base58':

        key = base58.b58decode(passwd)

    elif keyimport == 'base85':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif keyimport == 'hex':

        key = passwd.decode('hex')

    elif keyimport == 'dec':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif keyimport == 'octal':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif keyimport == 'binary':

        key = text_from_bits(passwd)

    elif keyimport == 'raw':

        key = passwd

    else:

        print('\033[1;31m[-]\033[0m Unknown error.')
        return False

    if importx == 'file':

        f = open(impfilepath, 'r')
        raw = f.read()
        f.close()

    elif importx == 'print':

        raw = raw

    else:

        print('\033[1;31m[-]\033[0m Unknown error.')
        return False

    raw = pad(raw)

    key = passwd

    if ivtype == 'randomstart':

        iv = Random.new().read(ARC2.block_size)
        sadd = iv
        eadd = ''

    elif ivtype == 'randomend':

        iv = Random.new().read(ARC2.block_size)
        sadd = ''
        eadd = iv

    elif ivtype == 'custom':

        iv = iv
        sadd = iv
        eadd = ''

    elif ivtype == 'noiv':

        sadd = ''
        eadd = ''

    else:

        print('\033[1;31m[-]\033[0m Unknown error.')
        return False

    if rc2type == 'ecb':

        cipher = ARC2.new(key, ARC2.MODE_ECB)

    elif rc2type == 'cbc':

        cipher = ARC2.new(key, ARC2.MODE_CBC, iv)

    elif rc2type == 'ofb':

        cipher = ARC2.new(key, ARC2.MODE_OFB, iv)

    elif rc2type == 'ocb':

        cipher = ARC2.new(key, ARC2.MODE_OCB, iv)

    elif rc2type == 'ctr':

        cipher = ARC2.new(key, ARC2.MODE_CTR)

    elif rc2type == 'cfb':

        cipher = ARC2.new(key, ARC2.MODE_CFB, iv)

    else:

        print('\033[1;31m[-]\033[0m Unknown error.')
        return False

    out = cipher.encrypt(raw)

    out = sadd + out + eadd

    if outputformat == 'base64':

        output = base64.b64encode(out)

    elif outputformat == 'raw':

        output = out

    elif outputformat == 'base32':

        output = base64.b32encode(out)

    elif outputformat == 'base16':

        output = base64.b16encode(out)

    elif outputformat == 'base58':

        output = base58.b58encode(out)

    elif outputformat == 'base85':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif outputformat == 'hex':

        output = out.encode('hex')

    elif outputformat == 'dec':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif outputformat == 'octal':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif outputformat == 'binary':

        output = text_to_bits(out)

    else:

        print('\033[1;31m[-]\033[0m Unknown error.')
        return False

    if export == 'file':

        filename = open(filepath, 'w')
        filename.write(output)
        filename.close()

        return True

    elif export == 'print':

        return output

    else:

        print('\033[1;31m[-]\033[0m Unknown error.')
        return False
Exemple #25
0
    def decrypt(self, b64corrected, isfile=False, removemeta=False):
        '''
        If key is setted up the method will decrypt the string from a path compliant encrypted string
        '''

        # If we got an encryption key
        if self.__key:

            # Start ciphering system
            if self.__algorithm == 'AESCFB':
                cipher = AES.new(self.__key, AES.MODE_CFB)
            elif self.__algorithm == 'AESECB':
                cipher = AES.new(self.__key, AES.MODE_ECB)
            elif self.__algorithm == 'ARC2CFB':
                cipher = ARC2.new(self.__key, ARC2.MODE_CFB)
            elif self.__algorithm == 'ARC2ECB':
                cipher = ARC2.new(self.__key, ARC2.MODE_ECB)
            elif self.__algorithm == 'BlowfishCFB':
                cipher = Blowfish.new(self.__key, Blowfish.MODE_CFB)
            elif self.__algorithm == 'BlowfishECB':
                cipher = Blowfish.new(self.__key, Blowfish.MODE_ECB)
            elif self.__algorithm == 'CASTCFB':
                cipher = CAST.new(self.__key, CAST.MODE_CFB)
            elif self.__algorithm == 'CASTECB':
                cipher = CAST.new(self.__key, CAST.MODE_ECB)
            elif self.__algorithm == 'DESCFB':
                cipher = DES.new(self.__key, DES.MODE_CFB)
            elif self.__algorithm == 'DESECB':
                cipher = DES.new(self.__key, DES.MODE_ECB)
            else:
                raise IOError, "Specified decrypting algorithm is unkown: %s" % (
                    self.__algorithm)

            # If is a file
            if isfile:

                # And we have to use padding
                if self.padding:

                    # Remove metatada
                    if not removemeta:
                        encoded = b64corrected
                    else:
                        encoded = b64corrected[:-1]
                else:
                    # No padder was used
                    encoded = b64corrected
            else:
                # Revert the path compliant correction
                b64encoded = b64corrected.replace("_", "/")

                # Decode the result
                encoded = base64.b64decode(b64encoded)

            # Decrypt the encoded string
            string = cipher.decrypt(encoded)

            # Security check
            if len(encoded) != len(string):
                self.error(
                    "Decrypt => Normal and encoded string are different size: %s -> %s\n"
                    % (len(encoded), len(string)))

            # Unpad the string
            if self.padding:
                try:
                    string = self.unpad(string)
                except Exception, e:
                    self.error("Unpad error: %s - String:%s - Encoded:%s\n" %
                               (e, string, b64corrected))
                    raise
def ceaserGenCipher(key,msg):
    cipher = ARC2.new(str(key), ARC2.MODE_CFB, "12345678")
    return cipher.encrypt(msg)
Exemple #27
0
    def decrypt(self, txt, pre, enc, post, pwd):
        #
        if type(txt) != type('') and type(txt) != type(u''):
            raise TypeError('Invalid data type for decryption: "%s" !' %
                            str(type(txt)))
        #
        if not (pre and enc and post):
            self.guess_pre_enc_post(txt)

            pre = self.pre
            enc = self.enc
            post = self.post

            if '{' in txt and '}' in txt and '"data":' in txt:
                temp = json.loads(txt.decode())
                txt = temp['data'].encode()
                del temp
            elif '<data>' in txt and '</data>' in txt:
                txt = re.search('<data>(.+)</data>', txt, re.S).group(1)
            else:
                txt = re.sub(NO_TAGS, '', txt)

        else:
            # If Json.
            if '{' in txt and '}' in txt and '"data":' in txt:
                pre = 'Json'
                temp = json.loads(txt.decode())
                txt = temp['data'].encode()
                del temp

            # If XML.
            elif '<data>' in txt and '</data>' in txt:
                pre = 'XML'
                txt = re.search('<data>(.+)</data>', txt, re.S).group(1)

            else:
                txt = re.sub(NO_TAGS, '', txt)
        #
        # Check RSA key path.
        if enc == 'RSA' and not os.path.exists(self.rsa_path):
            print('RSA decryption must specify a valid path !')
            self.__error(2, pre, enc, post)
            return
        #
        # Adapting password for encryption.
        pwd = self._fix_password(pwd, enc)
        #
        # Codec operation.
        if not pre:
            self.__error(1, 'None', enc, post)
            return
        elif pre == 'Base64 Codec' or pre == ENCODE_D['Base64 Codec']:
            try:
                txt = ba.a2b_base64(txt)
            except:
                self.__error(1, pre, enc, post)
                return
        elif pre == 'Base32 Codec' or pre == ENCODE_D['Base32 Codec']:
            try:
                txt = base64.b32decode(txt)
            except:
                self.__error(1, pre, enc, post)
                return
        elif pre == 'HEX Codec' or pre == ENCODE_D['HEX Codec']:
            try:
                txt = ba.a2b_hex(txt)
            except:
                self.__error(1, pre, enc, post)
                return
        elif pre == 'Quopri Codec' or pre == ENCODE_D['Quopri Codec']:
            try:
                txt = ba.a2b_qp(txt, header=True)
            except:
                self.__error(1, pre, enc, post)
                return
        elif pre == 'Json' or pre == ENCODE_D['Json']:
            try:
                txt = ba.a2b_base64(txt)
            except:
                self.__error(1, pre, enc, post)
                return
        elif pre == 'XML':
            try:
                txt = ba.a2b_base64(txt)
            except:
                self.__error(1, pre, enc, post)
                return
        else:
            raise Exception('Invalid codec "%s" !' % pre)
        #
        if enc == 'AES' or enc == ENC['AES']:
            o = AES.new(pwd, mode=3, segment_size=16)
        elif enc == 'ARC2' or enc == ENC['ARC2']:
            o = ARC2.new(pwd, mode=3, segment_size=16)
        elif enc == 'CAST' or enc == ENC['CAST']:
            o = CAST.new(pwd, mode=3, segment_size=16)
        elif enc == 'Blowfish' or enc == ENC['Blowfish']:
            o = Blowfish.new(pwd, mode=3, segment_size=16)
        elif enc == 'DES3' or enc == ENC['DES3']:
            o = DES3.new(pwd, mode=3, segment_size=16)
        elif enc == 'RSA' or enc == ENC['RSA']:
            # Using Blowfish decryption for RSA.
            o = Blowfish.new(pwd, mode=3, segment_size=16)
        elif not enc or enc in ['None', ENC['None']]:
            o = None
        else:
            raise Exception('Invalid decrypt "%s" !' % enc)
        #
        # Decryption operation.
        if o:
            try:
                temp = o.decrypt(txt)
                pad_len = ord(temp[-1])
                txt = temp[:-pad_len]
                del temp
            except:
                self.__error(2, pre, enc, post)
                return
        #
        # Un-scramble operation.
        if not post or post == 'N' or post == 'None':
            pass
        elif post == 'ZLIB' or post == SCRAMBLE_D['ZLIB']:
            try:
                txt = zlib.decompress(txt)
            except:
                self.__error(3, pre, enc, post)
                return
        elif post == 'BZ2' or post == SCRAMBLE_D['BZ2']:
            try:
                txt = bz2.decompress(txt)
            except:
                self.__error(3, pre, enc, post)
                return
        elif post == 'ROT13' or post == SCRAMBLE_D['ROT13']:
            txt = string.translate(txt, ROT)
        else:
            raise Exception('Invalid scramble "%s" !' % post)
        #
        return txt
Exemple #28
0
 def RC2_decrypt(self, data, key):
     # RC2解密函数
     iv = data[0:8]
     decrypt = ARC2.new(key, ARC2.MODE_CFB, iv)
     data = decrypt.decrypt(data[8:])
     return data
Exemple #29
0
def mitmPair(plain, cipher, key):
    c = ARC2.new(key, ARC2.MODE_ECB)
    enc = c.encrypt(plain)
    dec = c.decrypt(cipher)
    return (enc, dec, key)
Exemple #30
0
def mitmPair(plain, cipher, key):
    c = ARC2.new(key, ARC2.MODE_ECB)
    enc = c.encrypt(plain)
    dec = c.decrypt(cipher)
    return (enc, dec, key)
Exemple #31
0
from Crypto.Cipher import ARC4
from Crypto.Cipher import Blowfish
from Crypto.Cipher import DES
from Crypto.Cipher import XOR
from Crypto.Hash import SHA
from Crypto import Random
from Crypto.Util import Counter
from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers import algorithms
from cryptography.hazmat.primitives.ciphers import modes
from cryptography.hazmat.backends import default_backend
from struct import pack

key = b'Sixteen byte key'
iv = Random.new().read(ARC2.block_size)
cipher = ARC2.new(key, ARC2.MODE_CFB, iv)
msg = iv + cipher.encrypt(b'Attack at dawn')

key = b'Very long and confidential key'
nonce = Random.new().read(16)
tempkey = SHA.new(key+nonce).digest()
cipher = ARC4.new(tempkey)
msg = nonce + cipher.encrypt(b'Open the pod bay doors, HAL')

bs = Blowfish.block_size
key = b'An arbitrarily long key'
iv = Random.new().read(bs)
cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
plaintext = b'docendo discimus '
plen = bs - divmod(len(plaintext),bs)[1]
padding = [plen]*plen
Exemple #32
0
def rc2_cbc_encrypt(key,iv,data):
    cryptos = ARC2.new(key, ARC2.MODE_CBC,iv)
    cipher_text = cryptos.encrypt(rc2pad(data))
    return cipher_text
Exemple #33
0
class Crypter(object):
    """Implements modern authenticated encryption for strings

    The current version (1) uses HMAC-SHA256 and AES256-CBC using
    Encrypt-then-MAC. Should be secure >>>2030 according to NIST standards.
    http://www.keylength.com/ for a summary of algorithms and expected
    security. The message is padded with null characters. This means that
    strings with null characters should not use this method unless a
    different padding scheme is added

    AES in GCM mode is faster, but the pycrypto implementation is immature.
    This may be a better choice for future versions.

    There is currently legacy support for decryption under the old key
    using ARC2
    TODO(devinlundberg): remove legacy ARC2 decryption support
    """
    __metaclass__ = SingletonType
    # Remove legacy crypter in future.
    _legacy_crypter = ARC2.new(PinballConfig.SECRET_KEY, ARC2.MODE_ECB)
    _aes_block_size = 16
    _padding_char = '\x00'

    def _serialize(self, ciphertext, mac, **params):
        """Creates a serialized crypto object with current version and key"""
        encoded_params = {k: v.encode('base64') for k, v in params.items()}
        return json.dumps({
            'version': PinballConfig.CRYPTO_VERSION,
            'ciphertext': ciphertext.encode('base64'),
            'auth': mac.encode('base64'),
            'params': encoded_params
        }).encode('base64')

    def _deserialize(self, encoded_ciphertext):
        """Gets version, ciphertext, auth, and params from serialized object"""
        try:
            ciphertext_json = encoded_ciphertext.decode('base64')
        except binascii.Error:
            raise CryptoException('Invalid Base64')
        try:
            ciphertext_obj = json.loads(ciphertext_json)
        except ValueError:
            raise CryptoException('Invalid JSON format')
        if any(key not in ciphertext_obj
               for key in ('version', 'ciphertext', 'auth', 'params')):
            raise CryptoException('Invalid JSON parameters')
        version = ciphertext_obj['version']
        try:
            ciphertext = ciphertext_obj['ciphertext'].decode('base64')
            auth = ciphertext_obj['auth'].decode('base64')
            params = {
                k: v.decode('base64')
                for k, v in ciphertext_obj['params'].items()
            }
        except binascii.Error:
            raise CryptoException('Invalid Base64')
        except AttributeError:
            raise CryptoException('Unsupported types')
        return version, ciphertext, auth, params

    def _cbc_hmac_sha256_decrypt(self, ciphertext, auth, iv):
        """Authenticated decrypt using AES-CBC and HMAC SHA256
        Encrypt-then-MAC"""
        hmac = HMAC.new(PinballConfig.HMAC_KEY, digestmod=SHA256)
        hmac.update(ciphertext)
        hmac.update(iv)
        if hmac.hexdigest() != auth:
            raise CryptoException('Decryption Failed')
        aes = AES.new(PinballConfig.AES_CBC_KEY, AES.MODE_CBC, iv)
        return aes.decrypt(ciphertext).rstrip(self._padding_char)

    def encrypt(self, message):
        """Encrypts string of any length using the current crypto version

        Args:
            message: The string that needs to be encrypted.

        Returns:
            A serialized authenticated encrypted object
        """
        iv = ''.join(
            chr(random.randint(0, 255)) for _ in range(self._aes_block_size))
        aes = AES.new(PinballConfig.AES_CBC_KEY, AES.MODE_CBC, iv)
        hmac = HMAC.new(PinballConfig.HMAC_KEY, digestmod=SHA256)
        padded_length = (len(message) + self._aes_block_size - len(message) %
                         (self._aes_block_size))
        padded_message = message.ljust(padded_length, self._padding_char)
        ciphertext = aes.encrypt(padded_message)
        hmac.update(ciphertext)
        hmac.update(iv)
        return self._serialize(ciphertext, hmac.hexdigest(), iv=iv)

    def decrypt(self, encoded_ciphertext):
        """Deserializes and decrypts a string with the current or legacy
        algorithms

        Args:
            encoded_ciphertext: The string that needs to be decrypted.

        Returns:
            The decrypted message.

        Throws:
            CryptoException: on failed decryption.
        """
        try:
            version, ciphertext, auth, params = self._deserialize(
                encoded_ciphertext)
        except CryptoException:
            # This should raise an exception when support for ARC2 ends.
            return self._legacy_crypter.decrypt(encoded_ciphertext).rstrip('0')
        if version == 1:
            if 'iv' not in params:
                raise CryptoException('Missing IV')
            return self._cbc_hmac_sha256_decrypt(ciphertext, auth,
                                                 params['iv'])
        else:
            raise CryptoException('Unsupported Crypto Version')
Exemple #34
0
def rc2_ebc_encrypt(key,data):
    iv = Random.new().read(ARC2.block_size)
    cryptos = ARC2.new(key, ARC2.MODE_ECB)
    cipher_text = cryptos.encrypt(rc2pad(data))
    return cipher_text
Exemple #35
0
keyspace = (''.join(x).decode('hex')
            for x in itertools.product(hexchars, repeat=keysize * 2))

plain = raw_input("Plaintext> ").decode('hex')
cipher = raw_input("Ciphertext> ").decode('hex')

pairs = (mitmPair(plain, cipher, key) for key in keyspace)
encDict = {}
decDict = {}
for pair in pairs:
    encDict[pair[0]] = pair[2]
    decDict[pair[1]] = pair[2]
keyspace = [(encDict[m], decDict[m])
            for m in encDict.viewkeys() & decDict.viewkeys()]

# while we have not narrowed the key
while len(keyspace) != 1:
    print("Keyspace of {} remaining keys".format(len(keyspace)))
    plain = raw_input("Plaintext> ").decode('hex')
    cipher = raw_input("Ciphertext> ").decode('hex')
    keyspace = [key for key in keyspace if mitmFilter(plain, cipher, key)]

key = keyspace[0]
print("Found key {}{}".format(key[0].encode('hex'), key[1].encode('hex')))
c1 = ARC2.new(key[0], ARC2.MODE_ECB)
c2 = ARC2.new(key[1], ARC2.MODE_ECB)

while True:
    cipher = raw_input("Ciphertext> ").decode('hex')
    print("Plaintext: {}".format(c1.decrypt(c2.decrypt(cipher))))
def ceaserExtractPlain(key,msg):
    cipher = ARC2.new(str(key), ARC2.MODE_CFB, "12345678")
    return cipher.decrypt(msg)
Exemple #37
0
def mitmFilter(plain, cipher, key):
    enc = ARC2.new(key[0], ARC2.MODE_ECB).encrypt(plain)
    dec = ARC2.new(key[1], ARC2.MODE_ECB).decrypt(cipher)
    return enc == dec
Exemple #38
0
 def encrypt(self, txt, pre, enc, post, pwd, tags=True):
     #
     if type(txt) != type('') and type(txt) != type(u''):
         raise TypeError('Invalid data type for encryption: "%s" !' % str(type(txt)))
     #
     # Scramble operation.
     if not pre or pre == 'N' or pre == 'None':
         pass
     elif pre == 'ZLIB' or pre == SCRAMBLE_D['ZLIB']:
         txt = zlib.compress(txt)
     elif pre == 'BZ2' or pre == SCRAMBLE_D['BZ2']:
         txt = bz2.compress(txt)
     elif pre == 'ROT13' or pre == SCRAMBLE_D['ROT13']:
         txt = string.translate(txt, ROT)
     else:
         raise Exception('Invalid scramble "%s" !' % pre)
     #
     # Check RSA key path.
     if enc in ['RSA', 'RSA'] and not os.path.exists(self.rsa_path):
         print('RSA encryption must specify a valid path !')
         self.__error(2, pre, enc, post, field='L')
         return
     #
     pwd = self._fix_password(pwd, enc)
     #
     if enc == 'AES' or enc == ENC['AES']:
         o = AES.new(pwd, mode=3, segment_size=16)
     elif enc == 'ARC2' or enc == ENC['ARC2']:
         o = ARC2.new(pwd, mode=3, segment_size=16)
     elif enc == 'CAST' or enc == ENC['CAST']:
         o = CAST.new(pwd, mode=3, segment_size=16)
     elif enc == 'Blowfish' or enc == ENC['Blowfish']:
         o = Blowfish.new(pwd, mode=3, segment_size=16)
     elif enc == 'DES3' or enc == ENC['DES3']:
         o = DES3.new(pwd, mode=3, segment_size=16)
     elif enc == 'RSA' or enc == ENC['RSA']:
         # Using Blowfish encryption for RSA.
         o = Blowfish.new(pwd, Blowfish.MODE_CFB)
     elif not enc or enc in ['None', ENC['None']]:
         o = None
     else:
         raise Exception('Invalid encryption mode "%s" !' % enc)
     #
     # Encryption operation.
     if o:
         pad_len = 16 - (len(txt) % 16)
         padding = (chr(pad_len) * pad_len)
         txt = o.encrypt(txt + padding)
     #
     # Codec operation.
     if post == 'Base64 Codec' or post == ENCODE_D['Base64 Codec']:
         if tags:
             txt = '<#>%s:%s:%s<#>%s' % \
                 (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post].replace(' Codec',''), ba.b2a_base64(txt).decode())
         else:
             txt = ba.b2a_base64(txt).decode()
     elif post == 'Base32 Codec' or post ==  ENCODE_D['Base32 Codec']:
         if tags:
             txt = '<#>%s:%s:%s<#>%s' % \
                 (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post].replace(' Codec',''), base64.b32encode(txt).decode())
         else:
             txt = base64.b32encode(txt).decode()
     elif post == 'HEX Codec'or post == ENCODE_D['HEX Codec']:
         if tags:
             txt = '<#>%s:%s:%s<#>%s' % \
                 (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post].replace(' Codec',''), ba.b2a_hex(txt).decode())
         else:
             txt = ba.b2a_hex(txt).decode()
     elif post == 'Quopri Codec' or post == ENCODE_D['Quopri Codec']:
         if tags:
             txt = '<#>%s:%s:%s<#>%s' % (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post].replace(' Codec',''), \
                 ba.b2a_qp(txt, quotetabs=True, header=True).decode())
         else:
             txt = ba.b2a_qp(txt, quotetabs=True, header=True).decode()
     elif post == 'Json' or post == ENCODE_D['Json']:
         if tags:
             # Format : {"pre": "AAA", "enc": "BBB", "post": "CCC", "data": "Blah blah blah"}
             txt = '{"pre": "%s", "enc": "%s", "post": "%s", "data": "%s"}' % \
                 (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post], ba.b2a_base64(txt).rstrip().decode())
         else:
             txt = json.dumps({'data':ba.b2a_base64(txt).rstrip().decode()})
     elif post == 'XML':
         if tags:
             # Format : <root><pre>AAA</pre> <enc>BBB</enc> <post>CCC</post> <data>Blah blah blah</data></root>
             txt = '<root>\n<pre>%s</pre><enc>%s</enc><post>%s</post>\n<data>%s</data>\n</root>' % \
                 (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post], ba.b2a_base64(txt).rstrip().decode())
         else:
             txt = '<root>\n<data>%s</data>\n</root>' % ba.b2a_base64(txt).rstrip().decode()
     else:
         raise Exception('Invalid codec "%s" !' % post)
     #
     # The final text must be String, to be used in GUI
     return txt
Exemple #39
0
def rc2_cbc_decrypt(key,iv,data):
    cryptos = ARC2.new(key, ARC2.MODE_CBC,iv)
    cipher_text = cryptos.decrypt(data)
    return cipher_text
Exemple #40
0
    def decrypt(self, txt, pre, enc, post, pwd):
        #
        if type(txt) != type('') and type(txt) != type(u''):
            raise TypeError('Invalid data type for decryption: "%s" !' % str(type(txt)))
        #
        if not (pre and enc and post):
            self.guess_pre_enc_post(txt)

            pre = self.pre
            enc = self.enc
            post = self.post

            if '{' in txt and '}' in txt and '"data":' in txt:
                temp = json.loads(txt.decode())
                txt = temp['data'].encode()
                del temp
            elif '<data>' in txt and '</data>' in txt:
                txt = re.search('<data>(.+)</data>', txt, re.S).group(1)
            else:
                txt = re.sub(NO_TAGS, '', txt)

        else:
            # If Json.
            if '{' in txt and '}' in txt and '"data":' in txt:
                pre = 'Json'
                temp = json.loads(txt.decode())
                txt = temp['data'].encode()
                del temp

            # If XML.
            elif '<data>' in txt and '</data>' in txt:
                pre = 'XML'
                txt = re.search('<data>(.+)</data>', txt, re.S).group(1)

            else:
                txt = re.sub(NO_TAGS, '', txt)
        #
        # Check RSA key path.
        if enc == 'RSA' and not os.path.exists(self.rsa_path):
            print('RSA decryption must specify a valid path !')
            self.__error(2, pre, enc, post)
            return
        #
        # Adapting password for encryption.
        pwd = self._fix_password(pwd, enc)
        #
        # Codec operation.
        if not pre:
            self.__error(1, 'None', enc, post) ; return
        elif pre == 'Base64 Codec' or pre == ENCODE_D['Base64 Codec']:
            try: txt = ba.a2b_base64(txt)
            except: self.__error(1, pre, enc, post) ; return
        elif pre == 'Base32 Codec' or pre == ENCODE_D['Base32 Codec']:
            try: txt = base64.b32decode(txt)
            except: self.__error(1, pre, enc, post) ; return
        elif pre == 'HEX Codec' or pre == ENCODE_D['HEX Codec']:
            try: txt = ba.a2b_hex(txt)
            except: self.__error(1, pre, enc, post) ; return
        elif pre == 'Quopri Codec' or pre == ENCODE_D['Quopri Codec']:
            try: txt = ba.a2b_qp(txt, header=True)
            except: self.__error(1, pre, enc, post) ; return
        elif pre == 'Json' or pre == ENCODE_D['Json']:
            try: txt = ba.a2b_base64(txt)
            except: self.__error(1, pre, enc, post) ; return
        elif pre == 'XML':
            try: txt = ba.a2b_base64(txt)
            except: self.__error(1, pre, enc, post) ; return
        else:
            raise Exception('Invalid codec "%s" !' % pre)
        #
        if enc == 'AES' or enc == ENC['AES']:
            o = AES.new(pwd, mode=3, segment_size=16)
        elif enc == 'ARC2' or enc == ENC['ARC2']:
            o = ARC2.new(pwd, mode=3, segment_size=16)
        elif enc == 'CAST' or enc == ENC['CAST']:
            o = CAST.new(pwd, mode=3, segment_size=16)
        elif enc == 'Blowfish' or enc == ENC['Blowfish']:
            o = Blowfish.new(pwd, mode=3, segment_size=16)
        elif enc == 'DES3' or enc == ENC['DES3']:
            o = DES3.new(pwd, mode=3, segment_size=16)
        elif enc == 'RSA' or enc == ENC['RSA']:
            # Using Blowfish decryption for RSA.
            o = Blowfish.new(pwd, mode=3, segment_size=16)
        elif not enc or enc in ['None', ENC['None']]:
            o = None
        else:
            raise Exception('Invalid decrypt "%s" !' % enc)
        #
        # Decryption operation.
        if o:
            try:
                temp = o.decrypt(txt)
                pad_len = ord(temp[-1])
                txt = temp[:-pad_len]
                del temp
            except: self.__error(2, pre, enc, post) ; return
        #
        # Un-scramble operation.
        if not post or post == 'N' or post == 'None':
            pass
        elif post == 'ZLIB' or post == SCRAMBLE_D['ZLIB']:
            try: txt = zlib.decompress(txt)
            except: self.__error(3, pre, enc, post) ; return
        elif post == 'BZ2' or post == SCRAMBLE_D['BZ2']:
            try: txt = bz2.decompress(txt)
            except: self.__error(3, pre, enc, post) ; return
        elif post == 'ROT13' or post == SCRAMBLE_D['ROT13']:
            txt = string.translate(txt, ROT)
        else:
            raise Exception('Invalid scramble "%s" !' % post)
        #
        return txt
Exemple #41
0
def rc2_ebc_decrypt(key,data):
    cryptos = ARC2.new(key, ARC2.MODE_ECB)
    cipher_text = cryptos.decrypt(data)
    return cipher_text
Exemple #42
0
def rc2(txt, key, iv):
    cipher = ARC2.new(key, ARC2.MODE_CBC, iv, effective_keylen=40)
    return cipher.decrypt(txt)
Exemple #43
0
def rc2_decrypt_transform(data, key, mode, iv):
	arc2 = ARC2.new(key, mode, iv)
	return arc2.decrypt(data)
Exemple #44
0
def encrypt_RC2_CBC(str, key):
    str = align(str)
    iv = Random.new().read(ARC2.block_size)
    cipher1 = ARC2.new(key, ARC2.MODE_CBC, iv)
    cipher = iv + cipher1.encrypt(str)
    return b2a_hex(cipher)