예제 #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)
예제 #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)
예제 #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')
예제 #4
0
파일: n3ds.py 프로젝트: didix16/mh4editor
 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.')
예제 #5
0
파일: n3ds.py 프로젝트: 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.")
예제 #6
0
파일: esub.py 프로젝트: crooks/aam2mail
 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')
예제 #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
예제 #8
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
예제 #9
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)
예제 #10
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)
예제 #11
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]]
예제 #12
0
파일: crypt.py 프로젝트: dnephin/FlatVault
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)
예제 #13
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
예제 #14
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)
예제 #15
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
예제 #16
0
파일: s3back.py 프로젝트: blambi/s3back
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))
예제 #17
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')
예제 #18
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
예제 #19
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
예제 #20
0
파일: n3ds.py 프로젝트: svanheulen/mhef
 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.')
예제 #21
0
파일: __init__.py 프로젝트: bwlang/galaxy
    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)
예제 #22
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
예제 #23
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
예제 #24
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)
예제 #25
0
파일: ed.py 프로젝트: 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
예제 #26
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 "---"
예제 #27
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
예제 #28
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
 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
예제 #30
0
파일: n3ds.py 프로젝트: svanheulen/mhef
 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
예제 #31
0
    def decrypt(self):
        ''' Decrypt a kwallet '''
        if not self.key:
            raise PasswordMissing('Set the password first')

        # Unfortunately, KWallet's Blowfish implementation is a little wrong
        # It seems to have the wrong endianness than of native systems,
        # this following line fixes that
        self.encrypted = util.switch_endianness(self.encrypted)

        bf = Blowfish.new(self.key)
        decrypted = bf.decrypt(self.encrypted)

        # And switch the endianness again
        return util.switch_endianness(decrypted)
예제 #32
0
 def extract(self):
     raw_resources = filter(lambda x: x.startswith('res/raw'),
                            self.zipfile.namelist())
     iv = "12345678"  # this has to be done better
     key = self.zipfile.open('res/raw/blfs.key').read()
     key = ''.join(['%x' % ord(x) for x in key])[0:50]
     cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
     decode = base64.b64decode(
         self.zipfile.open('res/raw/config.cfg').read())
     config = cipher.decrypt(decode)
     config = config[:config.find('</config>') + 9]
     config = ET.fromstring(config)
     c2 = config.findall('.//data')[0].get('url_main').split(';')
     phone = config.findall('.//data')[0].get('phone_number')
     return {'c2': c2, 'phone': phone}
예제 #33
0
    def clean_key(self):
        def validation_error():
            self.data['key'] = get_key()
            raise ValidationError(_('Incorrect key.'))

        cobj = Blowfish.new(settings.SECRET_KEY)
        text = cobj.decrypt(b64decode(self.cleaned_data['key'])).rstrip('_')
        try:
            key = float(text)
        except:
            validation_error()
        now = time()
        if now - key < 10 or now - key > 60 * 60 * 6:  # valid for 6 hours
            validation_error()
        return
예제 #34
0
 def Decrypt(self, Ciphertext: str):
     '''
     Decrypt ciphertext and return corresponding plaintext.
     Args:
         Ciphertext: A hex string that will be decrypted.
     Returns:
         Plaintext string.
     '''
     cipher1 = Blowfish.new(self.Key1, Blowfish.MODE_CBC, iv=self.IV)
     cipher2 = Blowfish.new(self.Key2, Blowfish.MODE_CBC, iv=self.IV)
     ciphered_bytes = bytes.fromhex(Ciphertext)
     if len(ciphered_bytes) <= 8:
         raise ValueError('Invalid Ciphertext.')
     padded_plain_bytes = cipher2.decrypt(
         cipher1.decrypt(ciphered_bytes)[4:-4])
     i = 0
     for i in range(0, len(padded_plain_bytes), 2):
         if padded_plain_bytes[i] == 0 and padded_plain_bytes[i + 1] == 0:
             break
     plain_bytes = padded_plain_bytes[0:i]
     try:
         return plain_bytes.decode('utf-16-le')
     except UnicodeDecodeError:
         raise (ValueError('Invalid Ciphertext.'))
예제 #35
0
def decrypt(source, key, dest, buffer_size=DEFAULT_BUFFER_LENGTH):
    "Decrypts the specified file and writes it to dest"
    sfh = file(source, 'rb')
    dfh = file(dest, 'wb')
    decryptor = Encryptor.new(key)
    uncompressor = bz2.BZ2Decompressor()
    while True:
        try:
            dfh.write(
                uncompressor.decompress(
                    decryptor.decrypt(sfh.read(buffer_size))))
        except EOFError:
            break
    dfh.close()
    sfh.close()
예제 #36
0
파일: pdb_figaro.py 프로젝트: a-d-j-i/kedpm
 def encrypt(self, field, field_is_password=0):
     """ Encrypt FPM encoded field """
     hash=MD5.new()
     hash.update((self._salt + self._password).encode())
     key = hash.digest()
     bf = Blowfish.new(key)
     # Allow passwords that are longer than 24 characters. Unfortunately
     # this will break fpm compatibility somewhat - fpm will not be able to
     # handle such long password correctly.
     noised = self._addNoise(field.encode('utf-8'), field_is_password and
             (len(field) // FPM_PASSWORD_LEN + 1) * FPM_PASSWORD_LEN)
     rotated = self._rotate(noised)
     encrypted = bf.encrypt(rotated)
     hexstr = self._bin_to_hex(encrypted)
     return hexstr
예제 #37
0
def decode_dataset_user(trans, dataset_hash, user_hash):
    #decode dataset id as usual
    #decode user id using the dataset create time as the key
    dataset_id = trans.security.decode_id(dataset_hash)
    dataset = trans.sa_session.query(
        trans.app.model.HistoryDatasetAssociation).get(dataset_id)
    assert dataset, "Bad Dataset id provided to decode_dataset_user"
    if user_hash in [None, 'None']:
        user = None
    else:
        cipher = Blowfish.new(str(dataset.create_time))
        user_id = cipher.decrypt(user_hash.decode('hex')).lstrip("!")
        user = trans.sa_session.query(trans.app.model.User).get(int(user_id))
        assert user, "A Bad user id was passed to decode_dataset_user"
    return dataset, user
예제 #38
0
def encrypt_key(text, salt_key):
    try:
        bs = 8
        extra_bytes = len(text) % bs
        padding_size = bs - extra_bytes
        padding = chr(padding_size) * padding_size
        padded_text = text + padding

        crypt_obj = Blowfish.new(salt_key, Blowfish.MODE_ECB)

        cipher = crypt_obj.encrypt(padded_text)

        return cipher
    except Exception as ERROR:
        return "ERROR"
예제 #39
0
def fish_secure_key_cb(data, option, value):
    global fish_secure_key, fish_secure_cipher

    fish_secure_key = weechat.config_string(
        weechat.config_get("fish.secure.key"))

    if fish_secure_key == "":
        fish_secure_cipher = None
        return weechat.WEECHAT_RC_OK

    if fish_secure_key[:6] == "${sec.":
        decrypted = weechat.string_eval_expression(fish_secure_key, {}, {}, {})
        if decrypted:
            fish_secure_cipher = Blowfish(decrypted)
            return weechat.WEECHAT_RC_OK
        else:
            weechat.config_option_set(fish_config_option["key"], "", 0)
            weechat.prnt("", "Decrypt sec.conf first\n")
            return weechat.WEECHAT_RC_OK

    if fish_secure_key != "":
        fish_secure_cipher = Blowfish(fish_secure_key)

    return weechat.WEECHAT_RC_OK
예제 #40
0
def decryption(ciphertext):
    start = datetime.now()
    iv = ciphertext[:bs]
    ciphertext = ciphertext[bs:]
    cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
    msg = cipher.decrypt(ciphertext)

    last_byte = msg[-1]
    msg = msg[:-(last_byte if type(last_byte) is int else ord(last_byte))]
    plain_text = msg
    end = datetime.now()
    total = end - start
    total = total.total_seconds()
    print("Decryption time:", total)
    return plain_text, total
예제 #41
0
파일: fish.py 프로젝트: anunna/fish-weechat
def fish_secure_genkey(buffer):
    global fish_secure_cipher, fish_config_option

    newKey = blowcrypt_b64encode(urandom(32))

    # test to see if sec.conf decrypted
    weechat.command(buffer, "/secure set fish test")
    decrypted = weechat.string_eval_expression("${sec.data.fish}", {}, {}, {})

    if decrypted == "test":
        weechat.config_option_set(
            fish_config_option["key"], "${sec.data.fish}", 0
        )
        fish_secure_cipher = Blowfish(newKey)
        weechat.command(buffer, "/secure set fish %s" % newKey)
예제 #42
0
def decrypt_key(cipher, salt_key):
    try:
        crypt_obj = Blowfish.new(salt_key, Blowfish.MODE_ECB)
        decrypted_key = crypt_obj.decrypt(cipher)
        # return decrypted_key
        # print(decrypted_key)
        padding_size = ord(decrypted_key[-1])

        text = decrypted_key[:-padding_size]

        # print "Decrypt key was made successfully"
        return str(text)

    except Exception as ERROR:
        return "ERROR"
예제 #43
0
파일: ed.py 프로젝트: tampakrap/edpwd
def decrypt(key, hash_pwd):
    """
    Decrypt a Blowfish encrypted hash
    The password is saved in the form ${LENGTH}${PASSWORD}${GARBAGE}
    so the first two chars separate the actual password from the garbage
    """
    if not key or type(key) != str:
        raise Exception("Please provide a valid secret key")
    if not hash_pwd or type(hash_pwd) != str:
        raise Exception("Please provide a valid hash")
    obj = Blowfish.new(key)
    decrypted_pwd_full = obj.decrypt(base64.b64decode(hash_pwd))
    # Remove the length and the garbage to get the actual password
    password = decrypted_pwd_full[2:int(decrypted_pwd_full[:2]) + 2]
    return password
예제 #44
0
def blowfish(key):
    try:
        from Crypto.Cipher import Blowfish
    except ImportError:
        try:
            from Cryptodome.Cipher import Blowfish
        except ImportError:
            try:
                import blowfish
            except ImportError:
                raise Exception('failed to import cryptographic module')
            return blowfish.Cipher(key, byte_order='little').encrypt_block
    bf = Blowfish.new(key, mode=Blowfish.MODE_ECB)
    swapendian = lambda data: struct.pack('<2L', *struct.unpack('>2L', data))
    return lambda data: swapendian(bf.encrypt(swapendian(data)))
예제 #45
0
def makeblowfish(args, key):
    """ Create blowfish cipher """
    from Crypto.Cipher import Blowfish
    ecb = Blowfish.new(key, mode=Blowfish.MODE_ECB)

    # XXX hack by Irae for mac os XXX
    # convert to little endian
    # original_encrypt = ecb.encrypt
    # ecb.encrypt = lambda data: bytearray(wordswap(original_encrypt(wordswap(data))))

    class T():
        def encrypt(self, data):
            return bytearray(wordswap(ecb.encrypt(wordswap(data))))

    return T()
예제 #46
0
파일: database.py 프로젝트: udif/pysafe
    def changePassword(self, newpwd, progress=None):
        if self.__readonly:
            return False

        # cria o blowfish para a nova senha
        newbf = Blowfish.new(newpwd)

        c = self.__connection.cursor()
        ret = True
        try:
            rows = c.execute(
                "select id, parent, label, value from info").fetchall()

            for r in rows:
                if progress is not None:
                    if progress.updateProgressBar(len(rows)):
                        ret = False
                        break
                (id, parent, label, value) = r
                l1 = self.__decrypt(label)
                l2 = self.__encrypt(l1, newbf)
                if parent == self.__FIELD_PASSWORD:
                    # o caso da senha deve ser diferente, pois não devo criptografar
                    # a senha antiga, mas sim a nova!!
                    v2 = self.__encrypt(newpwd, newbf)
                else:
                    v1 = self.__decrypt(value)
                    v2 = self.__encrypt(v1, newbf)
                c.execute("update info set label = ?, value = ? where id = ?",
                          (l2, v2, id))

            if ret:
                self.__connection.commit()
            else:
                self.__connection.rollback()
        except:
            # se deu qualquer erro, cancela tudo!
            print "Error:", sys.exc_info()
            self.__connection.rollback()
            ret = False
        c.close()

        # se alterou com sucesso, fecha o banco e abre de novo
        if ret:
            self.close()
            self.open(newpwd)

        return ret
예제 #47
0
def blowfish_encryption(file, val):
    key_str = id_generator()
    key = key_str.encode("utf8")
    bs = Blowfish.block_size
    plaintext = file
    cipher = Blowfish.new(key, Blowfish.MODE_CBC)
    plen = bs - len(plaintext) % bs
    padding = [plen] * plen
    padding = pack('b' * plen, *padding)
    msg = cipher.iv + cipher.encrypt(plaintext + padding)
    if val == 1:
        outputFileKey = 'first_blowfish_key-' + datetime.now().strftime(
            '%d-%m-%Y_%I-%M-%S_%p') + '.txt'
        outputFileObj = open("/home/ubuntu/encryption/MultipleKeys/" +
                             outputFileKey,
                             'wb')  #wb to make sure bytes are written
        outputFileObj.write(key)
        outputFileObj.close()
        return msg, outputFileKey
    elif val == 2:
        outputFile = 'final_encrypted_file-' + datetime.now().strftime(
            '%d-%m-%Y_%I-%M-%S_%p') + '.txt'
        outputFileKey = 'second_blowfish_key-' + datetime.now().strftime(
            '%d-%m-%Y_%I-%M-%S_%p') + '.txt'
        outputFileObj = open(
            "/home/ubuntu/encryption/MultipleEncryption/" + outputFile, 'wb')
        outputFileObj.write(msg)
        outputFileObj.close()
        outputFileObj = open("/home/ubuntu/encryption/MultipleKeys/" +
                             outputFileKey,
                             'wb')  #wb to make sure bytes are written
        outputFileObj.write(key)
        outputFileObj.close()
        return outputFile, outputFileKey
    else:
        outputFile = 'blowfish_encryption-' + datetime.now().strftime(
            '%d-%m-%Y_%I-%M-%S_%p') + '.txt'
        outputFileKey = 'blowfish_key-' + datetime.now().strftime(
            '%d-%m-%Y_%I-%M-%S_%p') + '.txt'
        outputFileObj = open(
            "/home/ubuntu/encryption/EncryptionFiles/" + outputFile, 'wb')
        outputFileObj.write(msg)
        outputFileObj.close()
        outputFileObj = open("/home/ubuntu/encryption/Keys/" + outputFileKey,
                             'wb')  #wb to make sure bytes are written
        outputFileObj.write(key)
        outputFileObj.close()
        return outputFile, outputFileKey
예제 #48
0
def fish_modifier_in_privmsg_cb(data, modifier, server_name, string):
    global fish_keys, fish_cyphers

    match = re.match(
        r"^(:(.*?)!.*? PRIVMSG (.*?) :)(\x01ACTION )?((\+OK |mcps )?.*?)(\x01)?$",
        string)
    #match.group(0): message
    #match.group(1): msg without payload
    #match.group(2): source
    #match.group(3): target
    #match.group(4): action
    #match.group(5): msg
    #match.group(6): +OK |mcps
    if not match:
        return string

    if match.group(3) == weechat.info_get("irc_nick", server_name):
        dest = match.group(2)
    else:
        dest = match.group(3)
    target = "%s/%s" % (server_name, dest)
    targetl = ("%s/%s" % (server_name, dest)).lower()
    buffer = weechat.info_get("irc_buffer", "%s,%s" % (server_name, dest))

    if not match.group(6):
        fish_announce_unencrypted(buffer, target)

        return string

    if targetl not in fish_keys:
        fish_announce_unencrypted(buffer, target)

        return string

    fish_announce_encrypted(buffer, target)

    if targetl not in fish_cyphers:
        b = Blowfish(fish_keys[targetl])
        fish_cyphers[targetl] = b
    else:
        b = fish_cyphers[targetl]
    clean = blowcrypt_unpack(match.group(5), b)

    if not match.group(4):
        return "%s%s" % (match.group(1), fish_msg_w_marker(clean))

    return "%s%s%s\x01" % (match.group(1), match.group(4),
                           fish_msg_w_marker(clean))
예제 #49
0
def encrypt(plaintext, password):
    "Encrypts a data stream"

    # right-pad data
    padlen = 8 - len(plaintext) % 8

    if padlen == 0:
        padlen = 8

    plaintext += chr(padlen) * padlen

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

    return cipher.encrypt(plaintext)
예제 #50
0
def encrypt(buff, key):
    nonce = array.array('I', [random.getrandbits(32)])
    buff += hashlib.sha1(buff).digest()
    length = len(buff)
    buff = array.array('I', buff + b'\x00' * (8 - length % 8))
    buff.byteswap()
    counter = Counter.new(32,
                          prefix=nonce.tostring(),
                          initial_value=0,
                          little_endian=True)
    cipher = Blowfish.new(key, Blowfish.MODE_CTR, counter=counter)
    buff = array.array('I', cipher.encrypt(buff.tostring()))
    buff.byteswap()
    buff = buff.tostring()[:length]
    nonce.byteswap()
    return buff + nonce.tostring()
예제 #51
0
def decryptString(secret, cipher):
    '''只有CM在使用,以后不要再使用'''
    obj = Blowfish.new(secret, Blowfish.MODE_ECB)
    try:
        ciph = b32decode(cipher)
    except NameError:
        ciph = decodestring(cipher)
    except TypeError:
        return None

    plaintext = obj.decrypt(ciph)
    try:
        (c1, plain, c2) = plaintext.split(":valid:")
    except ValueError:
        return None
    return plain
예제 #52
0
    def encrypt(self, filePath, path=None, _file=None):

        file_data = self.readFileBytes(filePath)
        BFcipher = BF.new(self.key)
        cipherData = BFcipher.encrypt(self.pad(file_data))

        if path:
            if _file:
                f_name = os.path.join(path,
                                      os.path.basename(filePath) + '.enc')
            else:
                f_name = path + '.enc'
        else:
            f_name = filePath + '.enc'

        self.writeFileBytes(f_name, cipherData)
def Blowfish_decrypt(s):
    bs = Blowfish.block_size  # 8 BYTEs
    key = bytes.fromhex(Blowfish_KEY)
    ciphertext = s
    iv = ciphertext[:bs]  # first 8 bytes
    ciphertext = ciphertext[bs:]  # the rest of data
    cipher = Blowfish.new(key, Blowfish.MODE_ECB)  #blowfish cipher
    msg = bytearray(cipher.decrypt(iv))  #decrypt first 8 bytes
    last_block = msg  #save first decrypted data

    for i in range(0, len(ciphertext), 8):
        sub_str = cipher.decrypt(ciphertext[i:i + 8])  #decrypt next 8 bytes
        last_block = decrypt_xor(
            last_block, sub_str)  #xor with saved last decrypted 8 bytes
        msg.extend(last_block)
    return msg
예제 #54
0
def encrypt(key_file, message_file, ciphertext_file):
    """
    Encrypt a file using Blowfish.
    
    :param key_file: path to the file containing key
    :param message_file: path to the message file which we want to encrypt
    :param ciphertext_file: path where the encrypted file shall be saved.
    :return: nothing
    """
    block_size = Blowfish.block_size
    key = utils.read_file_b(key_file)
    message = utils.read_file_s(message_file)
    data = utils.message_to_data(message, block_size)
    cipher = Blowfish.new(key, Blowfish.MODE_CBC)
    ciphertext = cipher.iv + cipher.encrypt(data)
    utils.write_to_file_b(ciphertext_file, ciphertext)
예제 #55
0
def generate_testhash(password, random):
	"Generates a testhash based on a password and a random string"

	key	= SHA(random + "\x00\x00" + password).digest()
	cipher	= Blowfish.new(key)

	for i in range(1000):
		random = encrypt_block(cipher, random)

	h = SHA()
	h.init(0L, 0L, 0L, 0L, 0L)
	h.update(random)
	h.update("\x00\x00")
	testhash = h.digest()

	return testhash
예제 #56
0
파일: database.py 프로젝트: udif/pysafe
 def createDB(self, pwd):
     connection = sqlite3.connect(self.__databaseFile)
     c = connection.cursor()
     c.execute("create table V%i (nothing integer primary key)" %
               self.__VERSION)
     c.execute(
         "create table info (id integer primary key, parent integer, type text, pos long, label text, value text, timestamp integer)"
     )
     self.__blowfish = Blowfish.new(pwd)
     c.execute(
         "insert into info (parent, value) values (?, ?)",
         (self.__FIELD_PASSWORD, self.__encrypt(pwd, self.__blowfish)))
     self.__blowfish = None
     connection.commit()
     c.close()
     connection.close()
예제 #57
0
def main():
    #result = "\n"
    #for appid in allowedApps:
    #    result = str( result+"\""+rot13(appid)+"\", // "+appid+"\n" )
    #print result

    #Blowflish
    key = "Copyright 2009 Palm Inc."
    filename = "/usr/lib/lib_id.so"
    __cipher = Blowfish.new(key, Blowfish.MODE_CBC)
    result = __cipher.encrypt(__pad_file(kApps))

    writefile("/tmp/apps", result)

    print str("File written to " + "/tmp/apps")
    print str("Key is \"" + rot13(key) + "\"")
    print str("filename is \"" + rot13(filename) + "\" (" + filename + ")")
예제 #58
0
def decrypt_blowfish_CBC(key, ciphertext):
    """
        Decrypts ciphertext encrypted using Blowfish Algorithm. Mode : CBC
        Returns : plaintext
    """
    bs = Blowfish.block_size
    iv = ciphertext[:bs]
    ciphertext = ciphertext[bs:]

    cipher = Blowfish.new(key, 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))]
    return plaintext
예제 #59
0
def decrypt(key_file, ciphertext_file, output_file):
    """
    Decrypt a file using Blowfish.
    
    :param key_file: path to the file containing key
    :param ciphertext_file: path to the file which we want to decrypt
    :param output_file: path where the decrypted file shall be saved.
    :return: nothing
    """
    bs = Blowfish.block_size
    key = utils.read_file_b(key_file)
    ciphertext = utils.read_file_b(ciphertext_file)
    iv = ciphertext[:bs]
    ciphertext = ciphertext[bs:]
    cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
    plaintext = cipher.decrypt(ciphertext)
    utils.write_to_file_s(output_file, plaintext.decode('utf-8'))
예제 #60
0
    def __decrypt_data(self, dirty_data):
        previous_block = None  # type: str
        blowfish = Blowfish.new(BLOWFISH_KEY, Blowfish.MODE_ECB)
        decrypted_data = io.BytesIO()

        for index, chunk in self.__chunkify_string(dirty_data):
            if index == 0:
                continue

            decrypted_block, = struct.unpack('q', blowfish.decrypt(chunk))
            if previous_block:
                decrypted_block ^= previous_block
            previous_block = decrypted_block

            decrypted_data.write(struct.pack('q', decrypted_block))

        return decrypted_data.getvalue()