Ejemplo n.º 1
0
  def __init__(
      self, cipher_mode=None, initialization_vector=None, key=None, **kwargs):
    """Initializes the decrypter object.

    Args:
      cipher_mode (Optional[str]): cipher mode.
      initialization_vector (Optional[bytes]): initialization vector.
      key (Optional[bytes]): key.
      kwargs (dict): keyword arguments depending on the decrypter.

    Raises:
      ValueError: when key is not set, block cipher mode is not supported,
                  or initialization_vector is required and not set.
    """
    if not key:
      raise ValueError(u'Missing key.')

    cipher_mode = self.ENCRYPTION_MODES.get(cipher_mode, None)
    if cipher_mode is None:
      raise ValueError(u'Unsupported cipher mode: {0!s}'.format(cipher_mode))

    if cipher_mode != Blowfish.MODE_ECB and not initialization_vector:
      # Pycrypto does not create a meaningful error when initialization vector
      # is missing. Therefore, we report it ourselves.
      raise ValueError(u'Missing initialization vector.')

    super(BlowfishDecrypter, self).__init__()
    if cipher_mode == Blowfish.MODE_ECB:
      self._blowfish_cipher = Blowfish.new(key, mode=cipher_mode)
    else:
      self._blowfish_cipher = Blowfish.new(
          key, IV=initialization_vector, mode=cipher_mode)
Ejemplo n.º 2
0
  def __init__(self, key=None, mode=None, initialization_vector=None, **kwargs):
    """Initializes the decrypter object.

    Args:
      key: optional binary string containing the key.
      mode: optional mode of operation.
      initialization_vector: optional initialization vector.
      kwargs: a dictionary of keyword arguments depending on the decrypter.

    Raises:
      ValueError: when key is not set, block cipher mode is not supported,
                  or initialization_vector is required and not set.
    """
    if not key:
      raise ValueError(u'Missing key.')

    if mode not in self.ENCRYPTION_MODES:
      raise ValueError(u'Unsupported mode of operation: {0!s}'.format(mode))

    mode = self.ENCRYPTION_MODES[mode]

    if mode != Blowfish.MODE_ECB and not initialization_vector:
      # Pycrypto does not create a meaningful error when initialization vector
      # is missing. Therefore, we report it ourselves.
      raise ValueError(u'Missing initialization vector.')

    super(BlowfishDecrypter, self).__init__()
    if mode == Blowfish.MODE_ECB:
      self._blowfish_cipher = Blowfish.new(key, mode=mode)
    else:
      self._blowfish_cipher = Blowfish.new(
          key, mode=mode, IV=initialization_vector)
Ejemplo n.º 3
0
def decrypt(password) :
    c1 = Blowfish.new('5F B0 45 A2 94 17 D9 16 C6 C6 A2 FF 06 41 82 B7'.replace(' ','').decode('hex'), Blowfish.MODE_CBC, '\x00'*8)
    c2 = Blowfish.new('24 A6 3D DE 5B D3 B3 82 9C 7E 06 F4 08 16 AA 07'.replace(' ','').decode('hex'), Blowfish.MODE_CBC, '\x00'*8)
    padded = c1.decrypt(c2.decrypt(password.decode('hex'))[4:-4])
    p = ''
    while padded[:2] != '\x00\x00' :
        p += padded[:2]
        padded = padded[2:]
    return p.decode('UTF-16')
Ejemplo n.º 4
0
 def __init__(self, game):
     if game == MH4G_NA or game == MH4G_EU:
         self._cipher = Blowfish.new(b'AgK2DYheaCjyHGPB')
     elif game == MH4G_JP:
         self._cipher = Blowfish.new(b'AgK2DYheaCjyHGP8')
     elif game == MH4G_KR:
         self._cipher = Blowfish.new(b'AgK2DYheaOjyHGP8')
     else:
         raise ValueError('Ivalid game selected.')
Ejemplo n.º 5
0
Archivo: n3ds.py Proyecto: zorc/mhef
 def __init__(self, game):
     if game == MH4G_NA or game == MH4G_EU:
         self._cipher = Blowfish.new(b"AgK2DYheaCjyHGPB")
     elif game == MH4G_JP:
         self._cipher = Blowfish.new(b"AgK2DYheaCjyHGP8")
     elif game == MH4G_KR:
         self._cipher = Blowfish.new(b"AgK2DYheaOjyHGP8")
     elif game == MH4G_TW:
         self._cipher = Blowfish.new(b"Capcom123 ")
     else:
         raise ValueError("Ivalid game selected.")
Ejemplo n.º 6
0
 def bf(self, text, key, iv=None):
     """Produce a 192bit Encrypted Subject. The first 64 bits are the
     Initialization vector used in the Blowfish CFB Mode.  The Subject text
     is MD5 hashed and then encrypted using an MD5 hash of the Key."""
     texthash = md5(text).digest()
     keyhash = md5(key).digest()
     if iv is None:
         iv = urandom(8)
     crypt1 = Blowfish.new(keyhash,
                           Blowfish.MODE_OFB, iv).encrypt(texthash)[:8]
     crypt2 = Blowfish.new(keyhash,
                           Blowfish.MODE_OFB, crypt1).encrypt(texthash[8:])
     return (iv + crypt1 + crypt2).encode('hex')
Ejemplo n.º 7
0
def decryptLicense(system_id, license_str):
    license_key = None
    try:
        tmpKey = license_str.decode("hex")
        tmpSystemKey = getBlowfishKey(system_id.encode("hex"))
        tmpClientKey = getBlowfishKey(CLIENT_KEY.encode("hex"))
        tmpCipher = Blowfish.new(tmpClientKey, Blowfish.MODE_CBC, DEFAULT_IV)
        tmpKey = tmpCipher.decrypt(tmpKey)
        tmpCipher = Blowfish.new(tmpSystemKey, Blowfish.MODE_CBC, DEFAULT_IV)
        tmpKey = tmpCipher.decrypt(tmpKey)
        tmpLength = ord(tmpKey[len(tmpKey)-1])
        tmpKey = tmpKey[:len(tmpKey)-tmpLength]
        license_key = tmpKey.decode("hex")
    except Exception, msg:
        print msg
Ejemplo n.º 8
0
def decode(cDataStr, token, n):
    if (len(cDataStr) < 32):
        return False

    crc = cDataStr[0:32]
    cData = b64decode(cDataStr[32:])
    hasher = MD5.new()
    hasher.update(token)
    key = hasher.hexdigest()
    cipher = Blowfish.new(key)

    try:
        dataStr = cipher.decrypt(cData)
    except:
        return False
    checkCrc = MD5.new()
    checkCrc.update(cData)
    if (crc != checkCrc.hexdigest()):
        return False

    data = dataStr.split('|')
    if (len(data) != 6):
        return False

    tLen = len(data[5])
    pLen = ord(data[5][tLen-1])
    nStr = data[5][0:tLen-pLen]
    if (nStr != str(n)):
        return False

    return [data[0], data[1], data[2], data[3], data[4]]
Ejemplo n.º 9
0
def encrypt(source, key):
    assert 4 <= len(key) <= 56
    iv                  = Random.new().read(BLOCK)
    cipher              = Blowfish.new(key, MODE, iv)
    source_length       = len(source)
    padding             = get_padding(source_length)
    return iv + cipher.encrypt(source + padding)
Ejemplo n.º 10
0
 def _loop(self):
     self.cipher = Blowfish.new(settings.SECRET_KEY)
     while True:
         data = self._queue.get(True)
         if self.cipher_enabled:
             data = self._encrypt(data)
         self.socket.send_pyobj(data)
Ejemplo n.º 11
0
def EncryptWithSessionKey(session_key, inp, session_key_type=SessionKeyType()):
    """
    Encrypt input string with Session Key.

    :param session_key: randomly generated session key
    :param inp: input string to encrypt
    """
    if session_key_type == 'DES3':
        SessionKey = DES3.new(session_key)
        from lib import misc
        data = misc.RoundupString(inp, 24)
        ret = SessionKey.encrypt(data)
        del data
    elif session_key_type == 'AES':
        # TODO: AES is not tested yet
        SessionKey = AES.new(session_key)
        from lib import misc
        data = misc.RoundupString(inp, 24)
        ret = SessionKey.encrypt(data)
        del data
    elif session_key_type == 'Blowfish':
        # TODO: BlowFish is not done yet!
        SessionKey = Blowfish.new(session_key)
        ret = ''
    return ret
Ejemplo n.º 12
0
    def _set_metadata(self):
        print
        self.data["metadata"] = OrderedDict([("version", 1)])
        self._print("""I can encrypt passwords stored in your config file in
                       addition to preventing other users on your system from
                       reading the file. Encryption is recommended if the bot
                       is to run on a public computer like the Toolserver, but
                       otherwise the need to enter a key everytime you start
                       the bot may be annoying.""")
        if self._ask_bool("Encrypt stored passwords?"):
            self.data["metadata"]["encryptPasswords"] = True
            key = getpass(self.PROMPT + "Enter an encryption key: ")
            msg = "Running {0} rounds of bcrypt...".format(self.BCRYPT_ROUNDS)
            self._print_no_nl(msg)
            signature = bcrypt.hashpw(key, bcrypt.gensalt(self.BCRYPT_ROUNDS))
            self.data["metadata"]["signature"] = signature
            self._cipher = Blowfish.new(sha256(key).digest())
            print " done."
        else:
            self.data["metadata"]["encryptPasswords"] = False

        print
        self._print("""The bot can temporarily store its logs in the logs/
                       subdirectory. Error logs are kept for a month whereas
                       normal logs are kept for a week. If you disable this,
                       the bot will still print logs to stdout.""")
        logging = self._ask_bool("Enable logging?")
        self.data["metadata"]["enableLogging"] = logging
Ejemplo n.º 13
0
def login(username,
          password,
          region_code='NE',
          initial_app_strings='geORNtsZe5I4lRGjG9GZiA'):
    baseprm = 'uyI5Dj9g8VCOFDnBRUbr3g'
    c1 = Blowfish.new(baseprm, Blowfish.MODE_ECB)
    packingLength = 8 - len(password) % 8
    packedPassword = password + chr(packingLength) * packingLength
    encryptedPassword = c1.encrypt(packedPassword)
    encodedPassword = base64.standard_b64encode(encryptedPassword)
    url = "https://gdcportalgw.its-mo.com/api_v181217_NE/gdc/UserLoginRequest.php"
    data = {
        "RegionCode": region_code,
        "UserId": username,
        "initial_app_strings": initial_app_strings,
        "Password": encodedPassword,
    }
    headers = {'User-Agent': 'Mozilla/5.0'}

    r = requests.post(url, data=data, headers=headers)
    r.raise_for_status()
    if not r.json()['status'] == 200:
        raise Exception(
            'Cannot login.  Probably username & password are wrong. ' + r.text)

    custom_sessionid = r.json(
    )['VehicleInfoList']['vehicleInfo'][0]['custom_sessionid']
    VIN = r.json()['CustomerInfo']['VehicleInfo']['VIN']

    return custom_sessionid, VIN
Ejemplo n.º 14
0
    def runTest(self):
        # Encrypt/Decrypt data and test output parameter

        cipher = Blowfish.new(b'4'*16, Blowfish.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)
Ejemplo n.º 15
0
    def decrypt(self, encryptedFile, key, output):
        """ Return a decrypted chunk. """
        chunk_size = 720
        bs = Blowfish.block_size
        if (os.path.isfile):
            key = open(key).read()
        else:
            pass

        ifile = open(encryptedFile, 'rb')
        ofile = open(output, 'wb')

        iv = ifile.read(bs)
        cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)

        while True:
            chunk = ifile.read(chunk_size)
            encode = ''
            if not chunk:
                break
            elif len(chunk) != chunk_size:
                encode = self.__del_pad(cipher.decrypt(chunk))
            else:
                encode = cipher.decrypt(chunk)
            ofile.write(encode)

        ifile.close()
        ofile.close()
Ejemplo n.º 16
0
    def encrypt(self, originalFile, key, output):
        infile = open(originalFile, 'rb')
        outfile = open(output, 'wb')
        if (os.path.isfile):
            key = open(key).read()
        else:
            pass

        chunk_size = 720
        iv = Random.new().read(Blowfish.block_size)
        cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)

        chunk = infile.read(chunk_size)
        if len(chunk) != chunk_size:
            encode = iv + cipher.encrypt(self.__add_pad(chunk))
        else:
            encode = iv + cipher.encrypt(chunk)
        outfile.write(encode)

        while True:
            chunk = infile.read(chunk_size)
            if not chunk:
                break
            elif len(chunk) != chunk_size:
                encode = cipher.encrypt(self.__add_pad(chunk))
            else:
                encode = cipher.encrypt(chunk)
            outfile.write(encode)

        infile.close()
        outfile.close()
Ejemplo n.º 17
0
def decrypt_blowfish(key, filename):
    bs = Blowfish.block_size
    
    #key = literal_eval("b'{}'".format(key))
    #print("nilai key : ", key)
    # read file hasil ekstraksi dari file audio
    f = open(filename, "r")
    encrypt_msg = f.read()

    #print("\n\nnilai encrypt_msg : ", encrypt_msg)

    # convert to propery bytes format
    encrypt_msg = literal_eval("b'{}'".format(encrypt_msg))

    iv = encrypt_msg[:bs]
    decrypt_msg = encrypt_msg[bs:]

    #print("\n\nnilai iv : ", iv)
    #print("\n\nniai decrypt_msg : ", decrypt_msg)
    #print("\n\nnilai type(decrypt_msg) : ", type(decrypt_msg))

    cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
    msg = cipher.decrypt(decrypt_msg)
    #print("\n\nhasil decrypt Blowfish : ", type(msg))
    #print("\n\nhasil decrypt : ", msg)

    f = open("textBlowfish.txt", "w")
    f.write(str(msg.decode()))
    f.close()

    return "textBlowfish.txt"
Ejemplo n.º 18
0
def encrypt_blowfish(key, filename):
    bs = Blowfish.block_size
    iv = Random.new().read(bs)

    #print("\n\nnilai iv - encrypt : ", iv)
    #print("len iv : ", len(iv))
    key = literal_eval("b'{}'".format(key))
    cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
    
    # read file ciphertextRC6
    f = open(filename, "r")
    plaintext = f.readline()

    add_digit = 0
    if len(plaintext.encode()) % 8 != 0:
        add_digit = 8 - len(plaintext.encode()) % 8
        plaintext = plaintext + " " * add_digit

    encrypt_msg = iv + cipher.encrypt(plaintext)

    # create file ciphertext Blowfish
    f = open("ciphertextBlowfish.txt", "w")
    f.write(str(encrypt_msg)[2:-1])
    f.close()

    return "ciphertextBlowfish.txt", add_digit
Ejemplo n.º 19
0
 def _init(self, encrkey):
     if self.encrkey != encrkey:
         from Crypto.Cipher import Blowfish
         from random import randrange
         self.randrange = randrange
         self.c = Blowfish.new(encrkey,mode=Blowfish.MODE_ECB)
         self.encrkey = encrkey
Ejemplo n.º 20
0
    def __call__(self, queue):
        print "Running WorkerProcessor thread..."

        self.logrotate_interval = int(getattr(settings, "LOGSTREAM_LOGROTATE_INTERVAL", 60))
        self.secure_mode = bool(getattr(settings, "LOGSTREAM_SECURE_MODE", False))

        self.queue = queue
        self.storage = storage.Storage(interval=self.logrotate_interval)
        self.cipher = Blowfish.new(settings.SECRET_KEY)

        while True:
            qobj = self.queue.get(block=True)
            if not self._analyze_object(qobj):
                continue

            is_encrypted = bool(qobj.pop("encrypt", False))
            valid = False
            if is_encrypted:
                valid, qobj = self._decrypt(qobj)
                if not valid:
                    continue

            # skip all unencrtypted logs on secure
            # mode is activated
            if self.secure_mode and not valid:
                continue

            self._process_object(qobj)
Ejemplo n.º 21
0
def decrypt(key, ct_path="ciphertext.enc", savePT="plaintext.dec"):
    with open(ct_path, 'rb') as input:
        u = dill.load(input)
        ciphertext = dill.load(input)
    v = modexp(u, key.x, key.p)

    uv = str(u)+str(v)
    k = SHA224.new(uv.encode('utf-8')).hexdigest().encode('utf-8') #symmetric key for compute the ciphertext with AES
    print("K: "+str(k))

    bs = Blowfish.block_size
    iv = ciphertext[:bs]
    # Remove IV
    ciphertext = ciphertext[bs:]
    print("CT-LEN:"+str(len(ciphertext)))
    cipher = Blowfish.new(k, Blowfish.MODE_CBC, iv)
    plaintext = cipher.decrypt(ciphertext)
    # Remove padding
    last_byte = plaintext[-1]
    plaintext = plaintext[:- (last_byte if type(last_byte) is int else ord(last_byte))]

    # Write to file the plaintext decrypted
    #plaintext = plaintext.decode(plaintext, key.iNumBits)
    io.open(savePT,"wb").write(plaintext)

    return plaintext
Ejemplo n.º 22
0
    def __init__(self, **config):
        id_secret = config['id_secret']
        self.id_secret = id_secret
        self.id_cipher = Blowfish.new(smart_str(self.id_secret), mode=Blowfish.MODE_ECB)

        per_kind_id_secret_base = config.get('per_kind_id_secret_base', self.id_secret)
        self.id_ciphers_for_kind = _cipher_cache(per_kind_id_secret_base)
Ejemplo n.º 23
0
 def __init__(self, game):
     if game in (MH4G_JP, MH4G_NA, MH4G_EU, MH4G_KR, MH4G_TW):
         self._cipher = Blowfish.new(b'blowfish key iorajegqmrna4itjeangmb agmwgtobjteowhv9mope')
     elif game == MH4_JP:
         self._cipher = None
     else:
         raise ValueError('Invalid game selected.')
Ejemplo n.º 24
0
def get_meta(callsign, key, iv, video_url):
    url = "callsign/%s/meta.json" % (callsign)
    
    try:
        bs = Blowfish.block_size
        cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
        plen = bs - divmod(len(url),bs)[1]
        padding = [plen]*plen
        padding = pack('b'*plen, *padding)
        msg = cipher.encrypt(url + padding)
    except Exception as e:
        sys.stderr.write("Could not mangle url %s; got: %s" % (url, e))
        return -1
    url =  video_url + msg.encode('hex_codec')
    cmd = 'curl "%s"' % (url)
    p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell = True)
    ret = p.wait()
    stdoutdata, stderrdata = p.communicate()
    if ret:
        sys.stderr.write("Error: could not get duration for channel %s; got error %s\n" % (callsign, stderrdata))
    try:
        meta = json.loads(stdoutdata)
        return  int(meta["duration"])
    except Exception:
        sys.stderr.write("Error: could not get duration for channel %s; meta json output: %s\n" % (callsign, stdoutdata))
        return -1
 def _init(self,encrkey):
     if self.encrkey!=encrkey:
         from Crypto.Cipher import Blowfish
         from random import randrange
         self.randrange=randrange
         self.c=Blowfish.new(encrkey)
         self.encrkey=encrkey
Ejemplo n.º 26
0
def _decrypt_code(code):
    """Decrypt code encrypted by _encrypt_code"""
    # In some blowfish implementations, > 56 char keys can cause problems
    secret_key = settings.SECRET_KEY[:56]
    encryption_object = Blowfish.new(secret_key)
    # strip padding from decrypted credit card number
    return encryption_object.decrypt(base64.b64decode(code)).rstrip('X')
Ejemplo n.º 27
0
 def decrypt(self, buff):
     md = SHA256.new(buff[:-0x100])
     verifier = PKCS1_v1_5.new(self._static_pubkey)
     if verifier.verify(md, buff[-0x100:]) == False:
         raise ValueError('Invalid signature in footer.')
     if self._pubkey is not None:
         md = SHA256.new(buff[:-0x200])
         verifier = PKCS1_v1_5.new(self._pubkey)
         if verifier.verify(md, buff[-0x200:-0x100]) == False:
             raise ValueError('Invalid signature in footer.')
     buff = buff[:-0x200]
     nonce = array.array('I', buff[-4:])
     nonce.byteswap()
     length = len(buff) - 4
     buff = array.array('I', buff[:-4] + b'\x00' * (8 - length % 8))
     buff.byteswap()
     counter = Counter.new(32, prefix=nonce.tostring(), initial_value=0, little_endian=True)
     cipher = Blowfish.new(self._key, Blowfish.MODE_CTR, counter=counter)
     buff = array.array('I', cipher.decrypt(buff.tostring()))
     buff.byteswap()
     buff = buff.tostring()[:length]
     md = buff[-20:]
     buff = buff[:-20]
     if md != hashlib.sha1(buff).digest():
         raise ValueError('Invalid SHA1 hash in footer.')
     return buff
Ejemplo n.º 28
0
def encrypt(key, path="message.txt", saveCT="ciphertext.enc"):
    b = random.randrange(2, (key.p)-1)
    u = modexp(key.g, b, key.p)
    v = modexp(key.h, b, key.p)

    uv = str(u)+str(v)
    k = SHA224.new(uv.encode('utf-8')).hexdigest().encode('utf-8') #symmetric key for compute the ciphertext with AES
    print("K: "+str(k))

    # Open file plaintext to cipher
    plaintext = open(path,"rb").read()
    #plaintext = encode(plaintext, key.iNumBits)

    bs = Blowfish.block_size
    iv = Random.new().read(bs)
    cipher = Blowfish.new(k, Blowfish.MODE_CBC, iv)
    plen = bs - divmod(len(plaintext),bs)[1]
    padding = [plen]*plen
    padding = struct.pack('b'*plen,*padding)
    ciphertext = iv + cipher.encrypt(plaintext+padding)

    # Save ciphertext to file:
    print("CT-LEN:"+str(len(ciphertext)))
    with open(saveCT, 'wb') as output:
        dill.dump(u, output)
        dill.dump(ciphertext, output)

    return plaintext, ciphertext
Ejemplo n.º 29
0
 def _decryptCC(self):
     secret_key = settings.SECRET_KEY
     encryption_object = Blowfish.new(secret_key)
     # strip padding from decrypted credit card number
     ccnum = encryption_object.decrypt(base64.b64decode(
         self.encryptedCC)).rstrip('X')
     return (ccnum)
Ejemplo n.º 30
0
def decrypt(ciphertext, password, magic = None):
	"Decrypts a data stream"

	# decrypt data
	if len(ciphertext) % 8 != 0:
		raise base.FormatError

	key		= SHA.new(password).digest()
	cipher		= Blowfish.new(key, Blowfish.MODE_CBC, IV)

	plaintext	= cipher.decrypt(ciphertext)

	# check magic string
	if magic != None:
		if plaintext[:len(magic)] != magic:	
			raise base.PasswordError

		else:
			plaintext = plaintext[len(magic):]

	# remove padding
	padchar = plaintext[-1]
	npadchar = ord(padchar)

	if (npadchar > 0):
		if plaintext[-npadchar:] != padchar * npadchar:
			raise base.FormatError

		plaintext = plaintext[:-npadchar]

	return plaintext
Ejemplo n.º 31
0
    def generate_expiring_request(lifetime, plaintext):
        """
        Generate the parameters needed for an expiring email request with the given payload.
        Payload should be comma-delimited, and the consumer should expect to find and verify
        a timestamp and nonce appended to the given plaintext.
        """

        # Add nonce
        rng = Random.new()
        nonce = ''.join(choice(string.ascii_uppercase + string.digits) for _ in range(256))

        expiry = str(time.time() + lifetime)

        plaintext = (plaintext + "," + expiry + "," + nonce).encode('utf-8')

        # Pad the plaintext to the next full block with commas, because I can't be arsed to
        # write an actually clever parser.
        bs = Blowfish.block_size
        paddinglen = bs - (len(plaintext) % bs)
        plaintext += b',' * paddinglen

        # Generate random IV of size one block.
        iv = rng.read(bs)
        cipher = Blowfish.new(VERIFICATION_SECRET_KEY, Blowfish.MODE_CBC, iv)
        ciphertext = cipher.encrypt(plaintext)

        # Generate the verification hash.
        verification = hashlib.sha256()
        verification.update(plaintext + VERIFICATION_HASH_SECRET.encode('utf-8'))
        verify_hex = verification.hexdigest()

        return base64.urlsafe_b64encode(iv), base64.urlsafe_b64encode(ciphertext), verify_hex
Ejemplo n.º 32
0
Archivo: ed.py Proyecto: mgorny/edpwd
def encrypt(key, password):
    """
    Encrypt the password in Blowfish encryption
    The password is saved in the form: ${NUMBER}${PASSWORD}${GARBAGE}
    ${LENGTH} is the length of the password, used from the decrypt()
    function to separate it from the garbage.
    If the password is multiple of 8, then no ${GARBAGE} is appended
    """
    if not key or type(key) != str:
        raise Exception("Please provide a valid secret key")
    if not password or type(password) != str:
        raise Exception("Please provide a valid password")
    obj = Blowfish.new(key)
    length = str(len(password))
    if len(password) <= 9:
        # In case the length of the password is less than 10, then
        # add a zero in the front (eg 06), so we can produce a hash that
        # is always a multiple of 8
        length = '0' + length
    new_password = length + password
    if len(new_password) % 8 != 0:
        # Append random strings to satisfy Blowfish
        new_password += random_string(-len(new_password) % 8)
    hash_password = base64.b64encode(obj.encrypt(new_password))
    return hash_password
Ejemplo n.º 33
0
    def __init__(self):
        self.factory = EchoClientFactory()
        self.factory.handler = self
        reactor.connectTCP('localhost', 8000, self.factory)

        self.crypt = Blowfish.new('lostfrontier', 1)
        self.crypt_blocksize = 8
Ejemplo n.º 34
0
def encrypt(key, infile, outfile):
    """Takes key and input file object and output file object"""
    iv = Random.new().read(Blowfish.block_size)
    if verbose:
        print "iv: ", bytes_to_hexstr(iv)
    outfile.write(iv) # Write iv to outfile

    # calc max size to see if last chunk need padding (and number of padding bytes)
    file_size = os.fstat(infile.fileno()).st_size
    pad_len = 8-(file_size%8)

    if pad_len == 8:
        if verbose:
            print "wow no padding needed"
        outfile.write(chr(0))
    else:
        if verbose:
            print "Padding: {}".format(pad_len)
        outfile.write(chr(pad_len))

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

    while True:
        plain_data = infile.read(CHUNK_SIZE)

        if not plain_data:
            break # Nothing more to read

        if len(plain_data) != 4096 and pad_len != 8:
            # last package so pad it
            padding = Random.new().read(pad_len)
            outfile.write(cipher.encrypt(plain_data + padding))
        else:
            outfile.write(cipher.encrypt(plain_data))
Ejemplo n.º 35
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
Ejemplo n.º 36
0
 def scryptinfo(self):
     print "[+] Nb key           : 0x%08X (%d)" % (len(self.key), len(self.key))
     for k in self.key:
         print "    Plaintext key    : \"%s\"" % k
         print "    Sha-1            : %s" % hashlib.sha1(k).digest().encode('hex')
         print "    IV               : %s" % Blowfish.new(k, Blowfish.MODE_ECB).encrypt('0000000000000000'.decode('hex')).encode('hex')
         print "---"
Ejemplo n.º 37
0
def encryptLicense(system_id, license_key):
    license_str = None
    try:
        tmpSystemKey = getBlowfishKey(system_id.encode("hex"))
        tmpClientKey = getBlowfishKey(CLIENT_KEY.encode("hex"))
        tmpLicenseKey = license_key.encode("hex")
        tmpLength = BLOCK_SIZE - len(tmpLicenseKey)%BLOCK_SIZE
        for i in range(tmpLength):
            tmpLicenseKey = tmpLicenseKey + chr(tmpLength)
        tmpCipher = Blowfish.new(tmpSystemKey, Blowfish.MODE_CBC, DEFAULT_IV)
        tmpStr = tmpCipher.encrypt(tmpLicenseKey)
        tmpCipher = Blowfish.new(tmpClientKey, Blowfish.MODE_CBC, DEFAULT_IV)
        tmpStr = tmpCipher.encrypt(tmpStr)
        license_str = tmpStr.encode("hex")
    except Exception, msg:
        print msg
Ejemplo n.º 38
0
	def encrypt(self, key, mode, data, IV):
		if(mode == 1):
			obj = Blowfish.new(key, Blowfish.MODE_ECB, str(IV))
			return obj.encrypt(data)

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

		elif(mode == 3):
			obj = Blowfish.new(key, Blowfish.MODE_CFB, str(IV))
			return obj.encrypt(data)
			
		elif(mode == 4):
			obj = Blowfish.new(key, Blowfish.MODE_OFB, str(IV))
			return obj.encrypt(data)
Ejemplo n.º 39
0
    def __init__(self, **config):
        id_secret = config['id_secret']
        self.id_secret = id_secret
        self.id_cipher = Blowfish.new(self.id_secret)

        per_kind_id_secret_base = config.get('per_kind_id_secret_base', self.id_secret)
        self.id_ciphers_for_kind = _cipher_cache(per_kind_id_secret_base)
Ejemplo n.º 40
0
 def decrypt(self):
     with open(self.src_filepath, "rb") as f:
         enc = f.read()
     iv = enc[:self.bs]
     cipher = Blowfish.new(self.key, Blowfish.MODE_CBC, iv)
     with open(self.dst_filepath, "wb") as f:
         decrypted_base64 = cipher.decrypt(enc[self.bs:])
         f.write(base64.b64decode(bytes(self._unpad(str(decrypted_base64, "latin-1")), "latin-1")))
Ejemplo n.º 41
0
def pycrypto_tests():
    # https://pycrypto.readthedocs.io/en/latest/
    from Crypto.Cipher import DES, CAST, DES3, ARC2, Blowfish, AES, PKCS1_OAEP, PKCS1_v1_5

    DES.new(key, DES.MODE_ECB)  # Noncompliant
    DES.new(mode=DES.MODE_ECB, key=key)  # Noncompliant
    DES.new(key, DES.MODE_CBC, IV=iv)  # Noncompliant
    DES.new(key, DES.MODE_CFB, IV=iv)  # Compliant
    DES.new(key, DES.MODE_OFB, IV=iv)  # Compliant
    DES.new(key, DES.MODE_CTR, IV=iv, counter=ctr)  # Compliant
    CAST.new(key, CAST.MODE_ECB)  # Noncompliant
    DES3.new(key, DES3.MODE_ECB)  # Noncompliant
    ARC2.new(key, ARC2.MODE_CBC, IV=iv)  # Noncompliant
    Blowfish.new(key, Blowfish.MODE_ECB)  # Noncompliant
    AES.new(key, AES.MODE_CBC, IV=iv)  # Noncompliant
    PKCS1_OAEP.new(key)  # Compliant
    PKCS1_v1_5.new(key)  # Noncompliant
Ejemplo n.º 42
0
def decrypt_pycrypto_bf(encrypted):
    bs = Blowfish.block_size
    iv = encrypted[:bs]
    encrypted = encrypted[bs:]
    cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
    decrypted = cipher.decrypt(encrypted)
    plaintext = _unpad_text(decrypted)
    return plaintext
Ejemplo n.º 43
0
 def encrypt(message):
     cipher = Blowfish.new(Config.get('encrypt_passphrase'),
                           Blowfish.MODE_CBC, Config.get('encrypt_iv'))
     pad = 8 - (len(message) % 8)
     for x in range(pad):  # @UnusedVariable
         message += " "
     encrypted = cipher.encrypt(message)
     return base64.urlsafe_b64encode(encrypted)
Ejemplo n.º 44
0
    def getpassword(self, key, default=None):
        tmp = self.get(key, default)
        if not tmp:
            return default

        tmp = base64.b64decode(tmp.encode('ascii'))
        crypt_obj = Blowfish.new(self._cipher_key, Blowfish.MODE_ECB)
        return crypt_obj.decrypt(tmp).decode('ascii').split('\0')[0]
Ejemplo n.º 45
0
 def __init__(self, target, key, cipher=None):
     self.target = target
     if cipher is None:
         self.cipher = Blowfish.new(key, mode=Blowfish.MODE_ECB)
     else:
         self.cipher = cipher
     self.stored = b""
     self._closed = False
Ejemplo n.º 46
0
 def _set_password(self, value):
     if not value:
         self.encrypted_password = u""
     else:
         enc_obj = Blowfish.new(settings.SECRET_KEY)
         repeat = 8 - (len(value) % 8)
         value = value + " " * repeat
         self.encrypted_password = binascii.b2a_hex(enc_obj.encrypt(value))
Ejemplo n.º 47
0
def save(filename):
    crypt = crypto.new(
        _get_passphrase(confirm=True, prompt="Save config passphrase"),
        crypto.MODE_ECB)
    s = json.dumps(_config)
    padded_size = len(s) + (crypto.block_size - len(s) % crypto.block_size)
    with open(filename, 'w') as cfg_file:
        cfg_file.write(crypt.encrypt(s.ljust(padded_size)))
Ejemplo n.º 48
0
def _decrypt_code(code):
    """Decrypt code encrypted by _encrypt_code
    """
    secret_key = app_settings.PAY_SECRET_KEY
    encryption_object = Blowfish.new(secret_key)
    # strip padding from decrypted credit card number
    return encryption_object.decrypt(
        base64.b64decode(code)).decode().rstrip('X')
Ejemplo n.º 49
0
def encryptCBC(key, iv, plain):
    from Crypto.Cipher import Blowfish
    obj = Blowfish.new(key, Blowfish.MODE_CBC, iv)
    m = len(plain)
    n = 8 - divmod(m, 8)[-1]
    plain += '\0' * n
    print len(plain)
    return obj.encrypt(plain)
Ejemplo n.º 50
0
def encrypt(plain):
    obj = Blowfish.new(key, Blowfish.MODE_CBC,iv)
    plain=addPadding(plain)

    # prepend the iv to the encrypted string
    encr = iv + obj.encrypt(plain)
    encr64=base64.encodestring(encr)    
    return encr64;
Ejemplo n.º 51
0
def encrypt(plaintext, key):
    from Crypto.Cipher import Blowfish as blow

    b = blow.new(key)
    LIM = 8  #might have to change if we chose to use a different cipher or block size
    #nice pad soln: https://stackoverflow.com/a/32311090
    pad = lambda s: s + (LIM - len(s) % LIM) * chr(LIM - len(s) % LIM)
    return b.encrypt(pad(plaintext))
Ejemplo n.º 52
0
 def decrypt(self, ciphertext):
     unbased = base64.b64decode(ciphertext)
     iv = unbased[:self.block_size]
     encrypted = unbased[self.block_size:]
     key = self.key.digest()
     blowfishinit = Blowfish.new(key, Blowfish.MODE_CBC, iv)
     msg = blowfishinit.decrypt(encrypted).decode()
     return msg.rstrip(self.padding)
Ejemplo n.º 53
0
    def Encrypt(self, Plaintext : str):
        '''
        Encrypt plaintext and return corresponding ciphertext.

        Args:
            Plaintext: A string that will be encrypted.

        Returns:
            Hexlified ciphertext string.
        '''
        plain_bytes = Plaintext.encode('utf-16-le')
        plain_bytes += b'\x00\x00'
        padded_plain_bytes = plain_bytes + os.urandom(Blowfish.block_size - len(plain_bytes) % Blowfish.block_size)

        cipher1 = Blowfish.new(self.Key1, Blowfish.MODE_CBC, iv = self.IV)
        cipher2 = Blowfish.new(self.Key2, Blowfish.MODE_CBC, iv = self.IV)
        return cipher1.encrypt(os.urandom(4) + cipher2.encrypt(padded_plain_bytes) + os.urandom(4)).hex()
Ejemplo n.º 54
0
def encode_id( config_id_secret, obj_id ):
    id_cipher = Blowfish.new( config_id_secret )
    # Convert to string
    s = str( obj_id )
    # Pad to a multiple of 8 with leading "!" 
    s = ( "!" * ( 8 - len(s) % 8 ) ) + s
    # Encrypt
    return id_cipher.encrypt( s ).encode( 'hex' )
Ejemplo n.º 55
0
def  descifraLinea(linea):
	content=""
	bs = Blowfish.block_size
	buff=struct.unpack(str(bs)+'s',linea[0:bs])[0]
	blowfish = Blowfish.new(key, Blowfish.MODE_CBC, buff)
	buff=struct.unpack(str(len(linea[bs:]))+'s',linea[bs:])[0]
	content=blowfish.decrypt(struct.unpack(str(len(buff))+'s',buff)[0])
	return content.decode('utf-8')
Ejemplo n.º 56
0
 def encode(self, key, text):
     iv = "%s" % "".join(
         [random.choice(string.printable) for x in range(8)])
     cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
     length = len(text)
     text += "\0" * abs((length % 8) - 8)
     binary = cipher.encrypt(text)
     return base64.b64encode("%s%s" % (iv, binary))
Ejemplo n.º 57
0
    def decode(self, key, text):
        binary = base64.b64decode(text)
        iv = binary[:8]
        encrypted = binary[8:]
        cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)

        decrypted = cipher.decrypt(encrypted)
        return decrypted.rstrip("\0")
Ejemplo n.º 58
0
 def __init__(self, game):
     if game in (MH4G_JP, MH4G_NA, MH4G_EU, MH4G_KR, MH4G_TW):
         self._cipher = Blowfish.new(
             b'blowfish key iorajegqmrna4itjeangmb agmwgtobjteowhv9mope')
     elif game == MH4_JP:
         self._cipher = None
     else:
         raise ValueError('Invalid game selected.')
Ejemplo n.º 59
0
 def encrypt(self):
     with open(self.src_filepath, "rb") as f:
         plaintext_base64 = base64.b64encode(f.read())
         raw = self._pad(str(plaintext_base64, "latin-1"))
     iv = Random.new().read(self.bs)
     cipher = Blowfish.new(self.key, Blowfish.MODE_CBC, iv)
     with open(self.dst_filepath, "wb") as f:
         f.write(iv + cipher.encrypt(bytes(raw, "latin-1")))
Ejemplo n.º 60
0
def encrypt(plaintext, key):
    crypto = Blowfish.new(key, Blowfish.MODE_ECB)
    ciphertext = crypto.encrypt(plaintext)
    fprint = fingerprint(plaintext)
    recovered_plaintext = decrypt(ciphertext, fprint, key)
    assert (recovered_plaintext == plaintext)
    assert (fprint == fingerprint(recovered_plaintext))
    return ciphertext