Python Crypto.Cipher.ARC4 模块,new() 实例源码

我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用Crypto.Cipher.ARC4.new()

项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
def decrypt_secret(secret, key):
    """Python implementation of SystemFunction005.

    Decrypts a block of data with DES using given key.
    Note that key can be longer than 7 bytes."""
    decrypted_data = ''
    j = 0   # key index
    for i in range(0,len(secret),8):
        enc_block = secret[i:i+8]
        block_key = key[j:j+7]
        des_key = str_to_key(block_key)

        des = DES.new(des_key, DES.MODE_ECB)
        decrypted_data += des.decrypt(enc_block)

        j += 7
        if len(key[j:j+7]) < 7:
            j = len(key[j:j+7])

    (dec_data_len,) = unpack("<L", decrypted_data[:4])
    return decrypted_data[8:8+dec_data_len]
项目:Stitch    作者:nathanlopez    | 项目源码 | 文件源码
def get_hbootkey(samaddr, bootkey):
    sam_account_path = ["SAM", "Domains", "Account"]

    root = get_root(samaddr)
    if not root: return None

    sam_account_key = open_key(root, sam_account_path)
    if not sam_account_key: return None

    F = None
    for v in values(sam_account_key):
        if v.Name == 'F':
            F = samaddr.read(v.Data.value, v.DataLength.value)
    if not F: return None

    md5 = MD5.new()
    md5.update(F[0x70:0x80] + aqwerty + bootkey + anum)
    rc4_key = md5.digest()

    rc4 = ARC4.new(rc4_key)
    hbootkey = rc4.encrypt(F[0x80:0xA0])

    return hbootkey
项目:flocker-driver    作者:CoprHD    | 项目源码 | 文件源码
def unexport_volume(self, vol):
        self.authenticate_user()
        try:
               self.exportgroup_obj.exportgroup_remove_volumes(
                True,
                self.hostexportgroup,
                self.tenant,
                self.project,
                [vol],
                None,
                None)
        except utils.SOSError as e:
         if(e.err_code == utils.SOSError.HTTP_ERR):
                raise utils.SOSError(
                    utils.SOSError.HTTP_ERR,
                    "coprhd unexport_volume http error" + e.err_text)
         elif(e.err_code == utils.SOSError.SOS_FAILURE_ERR):
                raise utils.SOSError(
                    utils.SOSError.SOS_FAILURE_ERR,
                    "coprhd unexport_volume failed" + e.err_text)
         else:
                Message.new(Debug="coprhd unexport volume failed").write(_logger)
项目:flocker-driver    作者:CoprHD    | 项目源码 | 文件源码
def export_volume(self, vol):
        self.authenticate_user()
        Message.new(Info="coprhd export_volume").write(_logger)
        try:
                self.exportgroup_obj.exportgroup_add_volumes(
                True,
                self.hostexportgroup,
                self.tenant,
                self.project,
                [vol],
                None,
                None)
        except utils.SOSError as e:
         if(e.err_code == utils.SOSError.HTTP_ERR):
                raise utils.SOSError(
                    utils.SOSError.HTTP_ERR,
                    "coprhd export_volume http error" + e.err_text)
         elif(e.err_code == utils.SOSError.SOS_FAILURE_ERR):
                raise utils.SOSError(
                    utils.SOSError.SOS_FAILURE_ERR,
                    "coprhd export_volume failed" + e.err_text)
         else:
                Message.new(Debug="coprhd export_volume failed").write(_logger)
项目:flocker-driver    作者:CoprHD    | 项目源码 | 文件源码
def delete_volume(self, vol):
        self.authenticate_user()
        try:
               self.volume_obj.delete(
                self.tenant +
                "/" +
                self.project +
                "/" +
                vol,
                volume_name_list=None,
                sync=True)
        except utils.SOSError as e:
            if e.err_code == utils.SOSError.NOT_FOUND_ERR:
                Message.new(Debug="Volume : already deleted").write(_logger)
            elif e.err_code == utils.SOSError.SOS_FAILURE_ERR:
                raise utils.SOSError(
                    utils.SOSError.SOS_FAILURE_ERR,
                    "Volume " + name + ": Delete failed\n" + e.err_text)
            else:
                Message.new(Debug="Volume : delete failed").write(_logger)
项目:flocker-driver    作者:CoprHD    | 项目源码 | 文件源码
def create_project(self,name):
        self.authenticate_user()
        Message.new(Debug="coprhd create_project").write(_logger)
        try:
            self.project_obj.project_create(
                name,
                self.tenant)
        except utils.SOSError as e:
            if e.err_code == utils.SOSError.ENTRY_ALREADY_EXISTS_ERR:
                Message.new(Debug="Project with "+self.project+" already exists").write(_logger)
            elif(e.err_code == utils.SOSError.HTTP_ERR):
                raise utils.SOSError(
                    utils.SOSError.HTTP_ERR,
                    "coprhd create project HTTP_ERR" + e.err_text)
            elif(e.err_code == utils.SOSError.SOS_FAILURE_ERR):
                raise utils.SOSError(
                    utils.SOSError.SOS_FAILURE_ERR,
                    "coprhd create project failed" + e.err_text)
            else:
                Message.new(Debug="coprhd create project failed").write(_logger)
项目:flocker-driver    作者:CoprHD    | 项目源码 | 文件源码
def create_volume(self, dataset_id, size):
        """
        Create a volume of specified size on the COPRHD.
        The size shall be rounded off to 1GB, as COPRHD
        volumes of these sizes.

        See ``IBlockDeviceAPI.create_volume`` for parameter and return type
        documentation.
        """
        Message.new(Info="coprhd create_volume size is " + str(size)).write(_logger)
        volumesdetails = self.coprhdcli.get_volume_details("flocker-{}".format(dataset_id))
        if not volumesdetails:
         self.coprhdcli.create_volume("flocker-{}".format(dataset_id),size)
         Message.new(Debug="coprhd create_volume done").write(_logger)
        return BlockDeviceVolume(
          size=size, attached_to=None, dataset_id=dataset_id, blockdevice_id=u"block-{0}".format(dataset_id)
        )
项目:flocker-driver    作者:CoprHD    | 项目源码 | 文件源码
def create_volume_with_profile(self,dataset_id, size, profile_name):
        """
        Create a volume of specified size and profile on the COPRHD.
        The size shall be rounded off to 1GB, as COPRHD
        volumes of these sizes.

        profile can either 'PLATINUM' or 'GOLD' or 'SILVER' or 'BRONZE'

        See `IProfiledBlockDeviceAPI.create_volume_with_profile` for parameter and return type
        documentation.
        """

        Message.new(Info="coprhd create_volume size is " + str(size)).write(_logger)
        Message.new(Info="coprhd create_volume profile is " + str(profile_name)).write(_logger)

        volumesdetails = self.coprhdcli.get_volume_details("flocker-{}".format(dataset_id))
        if not volumesdetails:
           self.coprhdcli.create_volume("flocker-{}".format(dataset_id),size,profile_name=profile_name)
           Message.new(Debug="coprhd create_volume_with_profile done").write(_logger)
        return BlockDeviceVolume(size=size, attached_to=None, dataset_id=dataset_id, blockdevice_id=u"block-{0}".format(dataset_id))
项目:flocker-driver    作者:CoprHD    | 项目源码 | 文件源码
def detach_volume(self, blockdevice_id):
        """
        :param: volume id = blockdevice_id
        :raises: unknownvolume exception if not found
        """
        try:
         dataset_id = UUID(blockdevice_id[6:])
        except ValueError:
         raise UnknownVolume(blockdevice_id)
        volumesdetails = self.coprhdcli.get_volume_details("flocker-{}".format(dataset_id))
        if not volumesdetails:
         raise UnknownVolume(blockdevice_id)
        if volumesdetails[volumesdetails.keys()[0]]['attached_to'] is not None:
         Message.new(Info="coprhd detach_volume" + str(blockdevice_id)).write(_logger)
         dataset_id = UUID(blockdevice_id[6:])
         self.coprhdcli.unexport_volume("flocker-{}".format(dataset_id))
        else:
            Message.new(Info="Volume" + blockdevice_id + "not attached").write(_logger)
            raise UnattachedVolume(blockdevice_id)
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
def get_hbootkey(samaddr, bootkey):
    sam_account_path = ["SAM", "Domains", "Account"]

    root = get_root(samaddr)
    if not root: return None

    sam_account_key = open_key(root, sam_account_path)
    if not sam_account_key: return None

    F = None
    for v in values(sam_account_key):
        if v.Name == 'F':
            F = samaddr.read(v.Data.value, v.DataLength.value)
    if not F: return None

    md5 = MD5.new()
    md5.update(F[0x70:0x80] + aqwerty + bootkey + anum)
    rc4_key = md5.digest()

    rc4 = ARC4.new(rc4_key)
    hbootkey = rc4.encrypt(F[0x80:0xA0])

    return hbootkey
项目:djangoStatusPanel    作者:okar1    | 项目源码 | 文件源码
def encryptPassword(plaintext):
        try:
            letters = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890????????????????????????????????????????????????????????????????'
            SALT_SIZE = 8
            salt = urandom(SALT_SIZE)
            randomText = ''.join([random.choice(letters) for i in range(8)])
            plaintext = "%3d" % len(plaintext) + plaintext + randomText
            plaintext = plaintext.encode('utf-8')
            arc4 = ARC4.new(salt)
            crypted = arc4.encrypt(plaintext)
            res = salt + crypted
            # print('salt=',salt)
            # print('cr=',crypted)
            return b64encode(res).decode('ascii')
        except:
            return ""
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
def decrypt_secret(secret, key):
    """Python implementation of SystemFunction005.

    Decrypts a block of data with DES using given key.
    Note that key can be longer than 7 bytes."""
    decrypted_data = ''
    j = 0   # key index
    for i in range(0,len(secret),8):
        enc_block = secret[i:i+8]
        block_key = key[j:j+7]
        des_key = str_to_key(block_key)

        des = DES.new(des_key, DES.MODE_ECB)
        decrypted_data += des.decrypt(enc_block)

        j += 7
        if len(key[j:j+7]) < 7:
            j = len(key[j:j+7])

    (dec_data_len,) = unpack("<L", decrypted_data[:4])
    return decrypted_data[8:8+dec_data_len]
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
def decrypt_aes(secret, key):
    sha = SHA256.new()
    sha.update(key)
    for _i in range(1, 1000+1):
        sha.update(secret[28:60])
    aeskey = sha.digest()

    data = ""
    for i in range(60, len(secret), 16):
        aes = AES.new(aeskey, AES.MODE_CBC, "\x00"*16)
        buf = secret[i : i + 16]
        if len(buf) < 16:
            buf += (16-len(buf)) * "\00"

        data += aes.decrypt(buf)

    return data
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
def get_hbootkey(samaddr, bootkey):
    sam_account_path = ["SAM", "Domains", "Account"]

    root = get_root(samaddr)
    if not root: return None

    sam_account_key = open_key(root, sam_account_path)
    if not sam_account_key: return None

    F = None
    for v in values(sam_account_key):
        if v.Name == 'F':
            F = samaddr.read(v.Data.value, v.DataLength.value)
    if not F: return None

    md5 = MD5.new()
    md5.update(F[0x70:0x80] + aqwerty + bootkey + anum)
    rc4_key = md5.digest()

    rc4 = ARC4.new(rc4_key)
    hbootkey = rc4.encrypt(F[0x80:0xA0])

    return hbootkey
项目:PiBunny    作者:tholum    | 项目源码 | 文件源码
def decrypt_secret(secret, key):
    """Python implementation of SystemFunction005.

    Decrypts a block of data with DES using given key.
    Note that key can be longer than 7 bytes."""
    decrypted_data = ''
    j = 0   # key index
    for i in range(0,len(secret),8):
        enc_block = secret[i:i+8]
        block_key = key[j:j+7]
        des_key = str_to_key(block_key)

        des = DES.new(des_key, DES.MODE_ECB)
        decrypted_data += des.decrypt(enc_block)

        j += 7
        if len(key[j:j+7]) < 7:
            j = len(key[j:j+7])

    (dec_data_len,) = unpack("<L", decrypted_data[:4])
    return decrypted_data[8:8+dec_data_len]
项目:PiBunny    作者:tholum    | 项目源码 | 文件源码
def get_hbootkey(samaddr, bootkey):
    sam_account_path = ["SAM", "Domains", "Account"]

    root = get_root(samaddr)
    if not root: return None

    sam_account_key = open_key(root, sam_account_path)
    if not sam_account_key: return None

    F = None
    for v in values(sam_account_key):
        if v.Name == 'F':
            F = samaddr.read(v.Data.value, v.DataLength.value)
    if not F: return None

    md5 = MD5.new()
    md5.update(F[0x70:0x80] + aqwerty + bootkey + anum)
    rc4_key = md5.digest()

    rc4 = ARC4.new(rc4_key)
    hbootkey = rc4.encrypt(F[0x80:0xA0])

    return hbootkey
项目:PiBunny    作者:tholum    | 项目源码 | 文件源码
def GSS_GetMIC(self, sessionKey, data, sequenceNumber, direction = 'init'):
        GSS_GETMIC_HEADER = '\x60\x23\x06\x09\x2a\x86\x48\x86\xf7\x12\x01\x02\x02'
        token = self.MIC()

        # Let's pad the data
        pad = (4 - (len(data) % 4)) & 0x3
        padStr = chr(pad) * pad
        data += padStr

        token['SGN_ALG'] = GSS_HMAC
        if direction == 'init':
            token['SND_SEQ'] = struct.pack('>L', sequenceNumber) + '\x00'*4
        else:
            token['SND_SEQ'] = struct.pack('>L', sequenceNumber) + '\xff'*4

        Ksign = HMAC.new(sessionKey.contents, 'signaturekey\0', MD5).digest()
        Sgn_Cksum = MD5.new( struct.pack('<L',15) + str(token)[:8] + data).digest()
        Sgn_Cksum = HMAC.new(Ksign, Sgn_Cksum, MD5).digest()
        token['SGN_CKSUM'] = Sgn_Cksum[:8]

        Kseq = HMAC.new(sessionKey.contents, struct.pack('<L',0), MD5).digest()
        Kseq = HMAC.new(Kseq, token['SGN_CKSUM'], MD5).digest()
        token['SND_SEQ'] = ARC4.new(Kseq).encrypt(token['SND_SEQ'])
        finalData = GSS_GETMIC_HEADER + token.getData()
        return finalData
项目:PiBunny    作者:tholum    | 项目源码 | 文件源码
def decrypt(cls, key, keyusage, ciphertext):
        if len(ciphertext) < 24:
            raise ValueError('ciphertext too short')
        cksum, basic_ctext = ciphertext[:16], ciphertext[16:]
        ki = HMAC.new(key.contents, cls.usage_str(keyusage), MD5).digest()
        ke = HMAC.new(ki, cksum, MD5).digest()
        basic_plaintext = ARC4.new(ke).decrypt(basic_ctext)
        exp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest()
        ok = _mac_equal(cksum, exp_cksum)
        if not ok and keyusage == 9:
            # Try again with usage 8, due to RFC 4757 errata.
            ki = HMAC.new(key.contents, pack('<I', 8), MD5).digest()
            exp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest()
            ok = _mac_equal(cksum, exp_cksum)
        if not ok:
            raise InvalidChecksum('ciphertext integrity failure')
        # Discard the confounder.
        return basic_plaintext[8:]
项目:PiBunny    作者:tholum    | 项目源码 | 文件源码
def ComputeSessionKeyStrongKey(sharedSecret, clientChallenge, serverChallenge, sharedSecretHash = None):
    # added the ability to receive hashes already

    if sharedSecretHash is None:
        M4SS = ntlm.NTOWFv1(sharedSecret)
    else:
        M4SS = sharedSecretHash

    md5 = hashlib.new('md5')
    md5.update('\x00'*4)
    md5.update(clientChallenge)
    md5.update(serverChallenge)
    finalMD5 = md5.digest()
    hm = hmac.new(M4SS) 
    hm.update(finalMD5)
    return hm.digest()
项目:PiBunny    作者:tholum    | 项目源码 | 文件源码
def DecryptAttributeValue(dce, attribute):
    sessionKey = dce.get_session_key()
    # Is it a Kerberos Session Key?
    if isinstance(sessionKey, crypto.Key):
        # Extract its contents and move on
        sessionKey = sessionKey.contents

    encryptedPayload = ENCRYPTED_PAYLOAD(attribute)

    md5 = hashlib.new('md5')
    md5.update(sessionKey)
    md5.update(encryptedPayload['Salt'])
    finalMD5 = md5.digest()

    cipher = ARC4.new(finalMD5)
    plainText = cipher.decrypt(attribute[16:])

    #chkSum = (binascii.crc32(plainText[4:])) & 0xffffffff
    #if unpack('<L',plainText[:4])[0] != chkSum:
    #    print "RECEIVED 0x%x" % unpack('<L',plainText[:4])[0]
    #    print "CALCULATED 0x%x" % chkSum

    return plainText[4:]

# 5.16.4 ATTRTYP-to-OID Conversion
项目:PiBunny    作者:tholum    | 项目源码 | 文件源码
def __decryptSecret(self, key, value):
        # [MS-LSAD] Section 5.1.2
        plainText = ''

        encryptedSecretSize = unpack('<I', value[:4])[0]
        value = value[len(value)-encryptedSecretSize:]

        key0 = key
        for i in range(0, len(value), 8):
            cipherText = value[:8]
            tmpStrKey = key0[:7]
            tmpKey = self.__cryptoCommon.transformKey(tmpStrKey)
            Crypt1 = DES.new(tmpKey, DES.MODE_ECB)
            plainText += Crypt1.decrypt(cipherText)
            key0 = key0[7:]
            value = value[8:]
            # AdvanceKey
            if len(key0) < 7:
                key0 = key[len(key0):]

        secret = LSA_SECRET_XP(plainText)
        return secret['Secret']
项目:PiBunny    作者:tholum    | 项目源码 | 文件源码
def __decryptLSA(self, value):
        if self.__vistaStyle is True:
            # ToDo: There could be more than one LSA Keys
            record = LSA_SECRET(value)
            tmpKey = self.__sha256(self.__bootKey, record['EncryptedData'][:32])
            plainText = self.__cryptoCommon.decryptAES(tmpKey, record['EncryptedData'][32:])
            record = LSA_SECRET_BLOB(plainText)
            self.__LSAKey = record['Secret'][52:][:32]

        else:
            md5 = hashlib.new('md5')
            md5.update(self.__bootKey)
            for i in range(1000):
                md5.update(value[60:76])
            tmpKey = md5.digest()
            rc4 = ARC4.new(tmpKey)
            plainText = rc4.decrypt(value[12:60])
            self.__LSAKey = plainText[0x10:0x20]
项目:PiBunny    作者:tholum    | 项目源码 | 文件源码
def computeResponseNTLMv1(flags, serverChallenge, clientChallenge, serverName, domain, user, password, lmhash='',
                          nthash='', use_ntlmv2=USE_NTLMv2):
    if user == '' and password == '':
        # Special case for anonymous authentication
        lmResponse = ''
        ntResponse = ''
    else:
        lmhash = LMOWFv1(password, lmhash, nthash)
        nthash = NTOWFv1(password, lmhash, nthash)
        if flags & NTLMSSP_NEGOTIATE_LM_KEY:
           ntResponse = ''
           lmResponse = get_ntlmv1_response(lmhash, serverChallenge)
        elif flags & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:
           md5 = hashlib.new('md5')
           chall = (serverChallenge + clientChallenge)
           md5.update(chall)
           ntResponse = ntlmssp_DES_encrypt(nthash, md5.digest()[:8])
           lmResponse = clientChallenge + '\x00'*16
        else:
           ntResponse = get_ntlmv1_response(nthash,serverChallenge)
           lmResponse = get_ntlmv1_response(lmhash, serverChallenge)

    sessionBaseKey = generateSessionKeyV1(password, lmhash, nthash)
    return ntResponse, lmResponse, sessionBaseKey
项目:PiBunny    作者:tholum    | 项目源码 | 文件源码
def SEALKEY(flags, randomSessionKey, mode = 'Client'):
   if flags & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:
       if flags & NTLMSSP_NEGOTIATE_128:
           sealKey = randomSessionKey
       elif flags & NTLMSSP_NEGOTIATE_56:
           sealKey = randomSessionKey[:7]
       else:
           sealKey = randomSessionKey[:5]

       if mode == 'Client':
               md5 = hashlib.new('md5')
               md5.update(sealKey + 'session key to client-to-server sealing key magic constant\x00')
               sealKey = md5.digest()
       else:
               md5 = hashlib.new('md5')
               md5.update(sealKey + 'session key to server-to-client sealing key magic constant\x00')
               sealKey = md5.digest()

   elif flags & NTLMSSP_NEGOTIATE_56:
       sealKey = randomSessionKey[:7] + '\xa0'
   else:
       sealKey = randomSessionKey[:5] + '\xe5\x38\xb0'

   return sealKey
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def decrypt_secret(secret, key):
    """Python implementation of SystemFunction005.

    Decrypts a block of data with DES using given key.
    Note that key can be longer than 7 bytes."""
    decrypted_data = ''
    j = 0   # key index
    for i in range(0,len(secret),8):
        enc_block = secret[i:i+8]
        block_key = key[j:j+7]
        des_key = str_to_key(block_key)

        des = DES.new(des_key, DES.MODE_ECB)
        decrypted_data += des.decrypt(enc_block)

        j += 7
        if len(key[j:j+7]) < 7:
            j = len(key[j:j+7])

    (dec_data_len,) = unpack("<L", decrypted_data[:4])
    return decrypted_data[8:8+dec_data_len]
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def decrypt_aes(secret, key):
    sha = SHA256.new()
    sha.update(key)
    for _i in range(1, 1000+1):
        sha.update(secret[28:60])
    aeskey = sha.digest()

    data = ""
    for i in range(60, len(secret), 16):
        aes = AES.new(aeskey, AES.MODE_CBC, "\x00"*16)
        buf = secret[i : i + 16]
        if len(buf) < 16:
            buf += (16-len(buf)) * "\00"

        data += aes.decrypt(buf)

    return data
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def get_hbootkey(samaddr, bootkey):
    sam_account_path = ["SAM", "Domains", "Account"]

    root = get_root(samaddr)
    if not root: return None

    sam_account_key = open_key(root, sam_account_path)
    if not sam_account_key: return None

    F = None
    for v in values(sam_account_key):
        if v.Name == 'F':
            F = samaddr.read(v.Data.value, v.DataLength.value)
    if not F: return None

    md5 = MD5.new()
    md5.update(F[0x70:0x80] + aqwerty + bootkey + anum)
    rc4_key = md5.digest()

    rc4 = ARC4.new(rc4_key)
    hbootkey = rc4.encrypt(F[0x80:0xA0])

    return hbootkey
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def decrypt_secret(secret, key):
    """Python implementation of SystemFunction005.

    Decrypts a block of data with DES using given key.
    Note that key can be longer than 7 bytes."""
    decrypted_data = ''
    j = 0   # key index
    for i in range(0,len(secret),8):
        enc_block = secret[i:i+8]
        block_key = key[j:j+7]
        des_key = str_to_key(block_key)

        des = DES.new(des_key, DES.MODE_ECB)
        decrypted_data += des.decrypt(enc_block)

        j += 7
        if len(key[j:j+7]) < 7:
            j = len(key[j:j+7])

    (dec_data_len,) = unpack("<L", decrypted_data[:4])
    return decrypted_data[8:8+dec_data_len]
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def decrypt_aes(secret, key):
    sha = SHA256.new()
    sha.update(key)
    for _i in range(1, 1000+1):
        sha.update(secret[28:60])
    aeskey = sha.digest()

    data = ""
    for i in range(60, len(secret), 16):
        aes = AES.new(aeskey, AES.MODE_CBC, "\x00"*16)
        buf = secret[i : i + 16]
        if len(buf) < 16:
            buf += (16-len(buf)) * "\00"

        data += aes.decrypt(buf)

    return data
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def get_hbootkey(samaddr, bootkey):
    sam_account_path = ["SAM", "Domains", "Account"]

    root = get_root(samaddr)
    if not root: return None

    sam_account_key = open_key(root, sam_account_path)
    if not sam_account_key: return None

    F = None
    for v in values(sam_account_key):
        if v.Name == 'F':
            F = samaddr.read(v.Data.value, v.DataLength.value)
    if not F: return None

    md5 = MD5.new()
    md5.update(F[0x70:0x80] + aqwerty + bootkey + anum)
    rc4_key = md5.digest()

    rc4 = ARC4.new(rc4_key)
    hbootkey = rc4.encrypt(F[0x80:0xA0])

    return hbootkey
项目:easyATT    作者:InfiniteSamuel    | 项目源码 | 文件源码
def authenticate_owner_password(self, password):
        # Algorithm 3.7
        password = (password + self.PASSWORD_PADDING)[:32]
        hash = md5.md5(password)
        if self.r >= 3:
            for _ in range(50):
                hash = md5.md5(hash.digest())
        n = 5
        if self.r >= 3:
            n = self.length // 8
        key = hash.digest()[:n]
        if self.r == 2:
            user_password = ARC4.new(key).decrypt(self.o)
        else:
            user_password = self.o
            for i in range(19, -1, -1):
                k = b''.join(chr(ord(c) ^ i) for c in key)
                user_password = ARC4.new(k).decrypt(user_password)
        return self.authenticate_user_password(user_password)
项目:easyATT    作者:InfiniteSamuel    | 项目源码 | 文件源码
def authenticate(self, password):
        password = password.encode('utf-8')[:127]
        hash = SHA256.new(password)
        hash.update(self.o_validation_salt)
        hash.update(self.u)
        if hash.digest() == self.o_hash:
            hash = SHA256.new(password)
            hash.update(self.o_key_salt)
            hash.update(self.u)
            return AES.new(hash.digest(), mode=AES.MODE_CBC, IV=b'\x00' * 16).decrypt(self.oe)
        hash = SHA256.new(password)
        hash.update(self.u_validation_salt)
        if hash.digest() == self.u_hash:
            hash = SHA256.new(password)
            hash.update(self.u_key_salt)
            return AES.new(hash.digest(), mode=AES.MODE_CBC, IV=b'\x00' * 16).decrypt(self.ue)
        return None
项目:PyMal    作者:cysinfo    | 项目源码 | 文件源码
def decrypt_secret(secret, key):
    """Python implementation of SystemFunction005.

    Decrypts a block of data with DES using given key.
    Note that key can be longer than 7 bytes."""
    decrypted_data = ''
    j = 0   # key index
    for i in range(0, len(secret), 8):
        enc_block = secret[i:i + 8]
        block_key = key[j:j + 7]
        des_key = hashdump.str_to_key(block_key)

        des = DES.new(des_key, DES.MODE_ECB)
        decrypted_data += des.decrypt(enc_block)

        j += 7
        if len(key[j:j + 7]) < 7:
            j = len(key[j:j + 7])

    (dec_data_len,) = struct.unpack("<L", decrypted_data[:4])
    return decrypted_data[8:8 + dec_data_len]
项目:CVE-2017-7494    作者:joxeankoret    | 项目源码 | 文件源码
def GSS_GetMIC(self, sessionKey, data, sequenceNumber, direction = 'init'):
        GSS_GETMIC_HEADER = '\x60\x23\x06\x09\x2a\x86\x48\x86\xf7\x12\x01\x02\x02'
        token = self.MIC()

        # Let's pad the data
        pad = (4 - (len(data) % 4)) & 0x3
        padStr = chr(pad) * pad
        data += padStr

        token['SGN_ALG'] = GSS_HMAC
        if direction == 'init':
            token['SND_SEQ'] = struct.pack('>L', sequenceNumber) + '\x00'*4
        else:
            token['SND_SEQ'] = struct.pack('>L', sequenceNumber) + '\xff'*4

        Ksign = HMAC.new(sessionKey.contents, 'signaturekey\0', MD5).digest()
        Sgn_Cksum = MD5.new( struct.pack('<L',15) + str(token)[:8] + data).digest()
        Sgn_Cksum = HMAC.new(Ksign, Sgn_Cksum, MD5).digest()
        token['SGN_CKSUM'] = Sgn_Cksum[:8]

        Kseq = HMAC.new(sessionKey.contents, struct.pack('<L',0), MD5).digest()
        Kseq = HMAC.new(Kseq, token['SGN_CKSUM'], MD5).digest()
        token['SND_SEQ'] = ARC4.new(Kseq).encrypt(token['SND_SEQ'])
        finalData = GSS_GETMIC_HEADER + token.getData()
        return finalData
项目:CVE-2017-7494    作者:joxeankoret    | 项目源码 | 文件源码
def decrypt(cls, key, keyusage, ciphertext):
        if len(ciphertext) < 24:
            raise ValueError('ciphertext too short')
        cksum, basic_ctext = ciphertext[:16], ciphertext[16:]
        ki = HMAC.new(key.contents, cls.usage_str(keyusage), MD5).digest()
        ke = HMAC.new(ki, cksum, MD5).digest()
        basic_plaintext = ARC4.new(ke).decrypt(basic_ctext)
        exp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest()
        ok = _mac_equal(cksum, exp_cksum)
        if not ok and keyusage == 9:
            # Try again with usage 8, due to RFC 4757 errata.
            ki = HMAC.new(key.contents, pack('<I', 8), MD5).digest()
            exp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest()
            ok = _mac_equal(cksum, exp_cksum)
        if not ok:
            raise InvalidChecksum('ciphertext integrity failure')
        # Discard the confounder.
        return basic_plaintext[8:]
项目:CVE-2017-7494    作者:joxeankoret    | 项目源码 | 文件源码
def ComputeSessionKeyStrongKey(sharedSecret, clientChallenge, serverChallenge, sharedSecretHash = None):
    # added the ability to receive hashes already

    if sharedSecretHash is None:
        M4SS = ntlm.NTOWFv1(sharedSecret)
    else:
        M4SS = sharedSecretHash

    md5 = hashlib.new('md5')
    md5.update('\x00'*4)
    md5.update(clientChallenge)
    md5.update(serverChallenge)
    finalMD5 = md5.digest()
    hm = hmac.new(M4SS) 
    hm.update(finalMD5)
    return hm.digest()
项目:CVE-2017-7494    作者:joxeankoret    | 项目源码 | 文件源码
def DecryptAttributeValue(dce, attribute):
    sessionKey = dce.get_session_key()
    # Is it a Kerberos Session Key?
    if isinstance(sessionKey, crypto.Key):
        # Extract its contents and move on
        sessionKey = sessionKey.contents

    encryptedPayload = ENCRYPTED_PAYLOAD(attribute)

    md5 = hashlib.new('md5')
    md5.update(sessionKey)
    md5.update(encryptedPayload['Salt'])
    finalMD5 = md5.digest()

    cipher = ARC4.new(finalMD5)
    plainText = cipher.decrypt(attribute[16:])

    #chkSum = (binascii.crc32(plainText[4:])) & 0xffffffff
    #if unpack('<L',plainText[:4])[0] != chkSum:
    #    print "RECEIVED 0x%x" % unpack('<L',plainText[:4])[0]
    #    print "CALCULATED 0x%x" % chkSum

    return plainText[4:]

# 5.16.4 ATTRTYP-to-OID Conversion
项目:CVE-2017-7494    作者:joxeankoret    | 项目源码 | 文件源码
def __decryptSecret(self, key, value):
        # [MS-LSAD] Section 5.1.2
        plainText = ''

        encryptedSecretSize = unpack('<I', value[:4])[0]
        value = value[len(value)-encryptedSecretSize:]

        key0 = key
        for i in range(0, len(value), 8):
            cipherText = value[:8]
            tmpStrKey = key0[:7]
            tmpKey = self.__cryptoCommon.transformKey(tmpStrKey)
            Crypt1 = DES.new(tmpKey, DES.MODE_ECB)
            plainText += Crypt1.decrypt(cipherText)
            key0 = key0[7:]
            value = value[8:]
            # AdvanceKey
            if len(key0) < 7:
                key0 = key[len(key0):]

        secret = LSA_SECRET_XP(plainText)
        return secret['Secret']
项目:CVE-2017-7494    作者:joxeankoret    | 项目源码 | 文件源码
def __decryptLSA(self, value):
        if self.__vistaStyle is True:
            # ToDo: There could be more than one LSA Keys
            record = LSA_SECRET(value)
            tmpKey = self.__sha256(self.__bootKey, record['EncryptedData'][:32])
            plainText = self.__cryptoCommon.decryptAES(tmpKey, record['EncryptedData'][32:])
            record = LSA_SECRET_BLOB(plainText)
            self.__LSAKey = record['Secret'][52:][:32]

        else:
            md5 = hashlib.new('md5')
            md5.update(self.__bootKey)
            for i in range(1000):
                md5.update(value[60:76])
            tmpKey = md5.digest()
            rc4 = ARC4.new(tmpKey)
            plainText = rc4.decrypt(value[12:60])
            self.__LSAKey = plainText[0x10:0x20]
项目:CVE-2017-7494    作者:joxeankoret    | 项目源码 | 文件源码
def test_MimiCommand(self):
        dce, rpctransport, pHandle, key = self.connect()
        from Crypto.Cipher import ARC4
        cipher = ARC4.new(key[::-1])
        command = cipher.encrypt('token::whoami\x00'.encode('utf-16le'))
        #command = cipher.encrypt('sekurlsa::logonPasswords\x00'.encode('utf-16le'))
        #command = cipher.encrypt('process::imports\x00'.encode('utf-16le'))
        request = mimilib.MimiCommand()
        request['phMimi'] = pHandle
        request['szEncCommand'] = len(command)
        request['encCommand'] = list(command)
        resp = dce.request(request)
        cipherText = ''.join(resp['encResult'])
        cipher = ARC4.new(key[::-1])
        plain = cipher.decrypt(cipherText)
        print '='*80
        print plain
        #resp.dump()
项目:CVE-2017-7494    作者:joxeankoret    | 项目源码 | 文件源码
def SEALKEY(flags, randomSessionKey, mode = 'Client'):
   if flags & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:
       if flags & NTLMSSP_NEGOTIATE_128:
           sealKey = randomSessionKey
       elif flags & NTLMSSP_NEGOTIATE_56:
           sealKey = randomSessionKey[:7]
       else:
           sealKey = randomSessionKey[:5]

       if mode == 'Client':
               md5 = hashlib.new('md5')
               md5.update(sealKey + 'session key to client-to-server sealing key magic constant\x00')
               sealKey = md5.digest()
       else:
               md5 = hashlib.new('md5')
               md5.update(sealKey + 'session key to server-to-client sealing key magic constant\x00')
               sealKey = md5.digest()

   elif flags & NTLMSSP_NEGOTIATE_56:
       sealKey = randomSessionKey[:7] + '\xa0'
   else:
       sealKey = randomSessionKey[:5] + '\xe5\x38\xb0'

   return sealKey
项目:Stitch    作者:nathanlopez    | 项目源码 | 文件源码
def decrypt_single_hash(rid, hbootkey, enc_hash, lmntstr):
    (des_k1,des_k2) = sid_to_key(rid)
    d1 = DES.new(des_k1, DES.MODE_ECB)
    d2 = DES.new(des_k2, DES.MODE_ECB)

    md5 = MD5.new()
    md5.update(hbootkey[:0x10] + pack("<L",rid) + lmntstr)
    rc4_key = md5.digest()
    rc4 = ARC4.new(rc4_key)
    obfkey = rc4.encrypt(enc_hash)
    hash = d1.decrypt(obfkey[:8]) + d2.decrypt(obfkey[8:])

    return hash
项目:flocker-driver    作者:CoprHD    | 项目源码 | 文件源码
def authenticate_user(self):

        # we should check to see if we are already authenticated before blindly
        # doing it again
        if CoprHDCLIDriver.AUTHENTICATED is False:
            utils.COOKIE = None
            objauth = auth.Authentication(
                self.coprhdhost,
                self.port)
            cookiedir = self.cookiedir
            if( (self.coprhdcli_security_file is not '')
               and (self.coprhdcli_security_file is not None)):
                from Crypto.Cipher import ARC4
                import getpass
                objarc = ARC4.new(getpass.getuser())
                security_file = open(self.coprhdcli_security_file, 'r')
                cipher_text = security_file.readline().rstrip()
                self.username = objarc.decrypt(cipher_text)
                cipher_text = security_file.readline().rstrip()
                self.password = objarc.decrypt(cipher_text)
                security_file.close()
            objauth.authenticate_user(self.username,
                                  self.password,
                                  cookiedir,
                                  None)
            CoprHDCLIDriver.AUTHENTICATED = True
项目:flocker-driver    作者:CoprHD    | 项目源码 | 文件源码
def get_volume_lunid(self, vol):
        self.authenticate_user()
        Message.new(Info="coprhd-get_volume_lunid" + vol).write(_logger)
        try:
           volumeuri = self.volume_obj.volume_query(
                         self.tenant +
                         "/" +
                         self.project
                         + "/" + vol)
           if not volumeuri:
            return
           volumedetails = self.volume_obj.show_by_uri(volumeuri)
           groupdetails = self.exportgroup_obj.exportgroup_show(
                         self.hostexportgroup,
                         self.project,
                         self.tenant)
           exportedvolumes =  groupdetails['volumes'] 
           Message.new(Info="coprhd-get_volume_lunid for loop").write(_logger)
           for evolumes in exportedvolumes:
              if volumeuri == evolumes['id']:
               return evolumes['lun']
           return 
        except utils.SOSError as e:
            if e.err_code == utils.SOSError.NOT_FOUND_ERR:
                Message.new(Debug="Volume : doesnot exist").write(_logger)
            elif(e.err_code == utils.SOSError.HTTP_ERR):
                raise utils.SOSError(
                    utils.SOSError.HTTP_ERR,
                    "coprhd get volume lunid http error" + e.err_text)
            elif(e.err_code == utils.SOSError.SOS_FAILURE_ERR):
                raise utils.SOSError(
                    utils.SOSError.SOS_FAILURE_ERR,
                    "coprhd get volume lunid failed" + e.err_text)
            else:
                Message.new(Debug="coprhd-get_volume_lunid failed").write(_logger)
项目:flocker-driver    作者:CoprHD    | 项目源码 | 文件源码
def get_volume_wwn(self, vol):
        self.authenticate_user()
        Message.new(Info="coprhd-get_volume_wwn" + vol).write(_logger)
        try:
           volumeuri = self.volume_obj.volume_query(
                         self.tenant +
                         "/" +
                         self.project
                         + "/" + vol)
           if not volumeuri:
            return
           volumedetails = self.volume_obj.show_by_uri(volumeuri)
           groupdetails = self.exportgroup_obj.exportgroup_show(
                         self.hostexportgroup,
                         self.project,
                         self.tenant)
           exportedvolumes =  groupdetails['volumes'] 
           Message.new(Info="coprhd-get_volume_wwn for loop").write(_logger)
           for evolumes in exportedvolumes:
              if volumeuri == evolumes['id']:
               return volumedetails['wwn']
           return 
        except utils.SOSError as e:
            if e.err_code == utils.SOSError.NOT_FOUND_ERR:
                Message.new(Debug="Volume : doesnot exist").write(_logger)
                return None
            elif(e.err_code == utils.SOSError.HTTP_ERR):
                raise utils.SOSError(
                    utils.SOSError.HTTP_ERR,
                    "coprhd get volume wwn http error" + e.err_text)
            elif(e.err_code == utils.SOSError.SOS_FAILURE_ERR):
                raise utils.SOSError(
                    utils.SOSError.SOS_FAILURE_ERR,
                    "coprhd get volume wwn details failed" + e.err_text)
            else:
                Message.new(Debug="coprhd-get_volume_wwn failed").write(_logger)
项目:flocker-driver    作者:CoprHD    | 项目源码 | 文件源码
def get_volume_details(self, vol):
        self.authenticate_user()
        volume_dict = {}
        Message.new(Info="coprhd-get-volume-details" + vol).write(_logger)
        try:
           volumeuri = self.volume_obj.volume_query(
                         self.tenant +
                         "/" +
                         self.project
                         + "/" + vol)
           if not volumeuri:
            return
           volumedetails = self.volume_obj.show_by_uri(volumeuri)
           groupdetails = self.exportgroup_obj.exportgroup_show(
                         self.hostexportgroup,
                         self.project,
                         self.tenant)
           exportedvolumes =  groupdetails['volumes'] 
           Message.new(Info="coprhd-get-volume-details for loop").write(_logger)
           for evolumes in exportedvolumes:
              if volumeuri == evolumes['id']:
               volume_dict[volumedetails['name'][8:]]={'size':volumedetails['provisioned_capacity_gb'],'attached_to':self.host}
               return volume_dict
           volume_dict[volumedetails['name'][8:]]={'size':volumedetails['provisioned_capacity_gb'],'attached_to':None}
           return volume_dict
        except utils.SOSError as e:
            if e.err_code == utils.SOSError.NOT_FOUND_ERR:
                Message.new(Debug="Volume : doesnot exist").write(_logger)
            elif(e.err_code == utils.SOSError.HTTP_ERR):
                raise utils.SOSError(
                    utils.SOSError.HTTP_ERR,
                    "coprhd get volume http error" + e.err_text)
            elif(e.err_code == utils.SOSError.SOS_FAILURE_ERR):
                raise utils.SOSError(
                    utils.SOSError.SOS_FAILURE_ERR,
                    "coprhd get volume details failed" + e.err_text)
            else:
                Message.new(Debug="coprhd get volume details failed").write(_logger)
项目:flocker-driver    作者:CoprHD    | 项目源码 | 文件源码
def add_initiators(self,sync, hostlabel, protocol, portwwn,initname):
        self.authenticate_user()
        portwwn = None
        try:
           f = open ('/etc/iscsi/initiatorname.iscsi','r')
           for line in f:
              if ( line[0] != '#' ):
                s1=line.split('=')
                portwwn = str(s1[1])
                if "\n" in portwwn:
                   portwwn = portwwn.split('\n')[0]
                break
           initname = portwwn
           initiatorwwn = None
           self.hostinitiator_obj.create(sync,hostlabel,protocol,initiatorwwn,portwwn)
        except utils.SOSError as e:
            if(e.err_code == utils.SOSError.HTTP_ERR):
                if(e.err_text.find('same Initiator Port already exists') != -1):
                 Message.new(Debug="coprhd add initiators already added").write(_logger)
                else:
                 raise utils.SOSError(
                    utils.SOSError.HTTP_ERR,
                    "coprhd add initiators HTTP_ERR" + e.err_text)
            elif(e.err_code == utils.SOSError.SOS_FAILURE_ERR):
                raise utils.SOSError(
                    utils.SOSError.SOS_FAILURE_ERR,
                    "coprhd add initiators failed" + e.err_text)
            else:
                Message.new(Debug="coprhd add initiators failed").write(_logger)
项目:flocker-driver    作者:CoprHD    | 项目源码 | 文件源码
def create_network(self,name,nwtype):
        self.authenticate_user()
        try:
            networkid = self.network_obj.query_by_name(name)
            if networkid:
             Message.new(Debug="Network Already Exists").write(_logger)
            else: 
             self.network_obj.create(name,nwtype)

            "Adding Host Ports to Network"
            f = open ('/etc/iscsi/initiatorname.iscsi','r')
            for line in f:
               if line[0] != '#':
                  current_line=line.split('=')
                  host_port = current_line[1]
                  if "\n" in host_port[1]:
                    host_port = host_port.split('\n')[0]
                  tz = self.network_obj.show(name)
                  if ("endpoints" in tz):
                   endpoints = tz['endpoints']
                   if host_port not in endpoints:
                    self.network_obj.add_endpoint(name,endpoint=host_port)
                  break
        except utils.SOSError as e:
            if(e.err_code == utils.SOSError.HTTP_ERR):
                raise utils.SOSError(
                    utils.SOSError.HTTP_ERR,
                    "coprhd create network HTTP_ERR" + e.err_text)
            elif(e.err_code == utils.SOSError.SOS_FAILURE_ERR):
                raise utils.SOSError(
                    utils.SOSError.SOS_FAILURE_ERR,
                    "coprhd create network failed" + e.err_text)
            else:
                Message.new(Debug="coprhd create network failed").write(_logger)