Attempt decryption of header with a private key; returns decryptInfo.
        Returns a dictionary, not a new MiniLockHeader!
778468
def decrypt(self, recipient_key):
        
        ephem = UserLock.from_b64(self.dict['ephemeral'])
        ephem_box = nacl.public.Box(recipient_key.private_key, ephem.public_key)
        # Scan available entries in decryptInfo and try to decrypt each; break when
        # successful with any.
        for nonce, crypted_decryptInfo in self.dict['decryptInfo'].items():
            raw_nonce = b64decode(nonce)
            crypted_decryptInfo = b64decode(crypted_decryptInfo)
            try:
                decryptInfo_raw = ephem_box.decrypt(crypted_decryptInfo, raw_nonce)
                decryptInfo = json.loads(decryptInfo_raw.decode('utf8'))
                success_nonce = raw_nonce
                break
            except Exception as E:
                #print("Decoding exception: '{}' - with ciphertext '{}'".format(E, crypted_decryptInfo))
                pass
        else:
            raise ValueError("No decryptInfo block found for this recipient Key.")
        if not recipient_key.userID == decryptInfo['recipientID']:
            raise ValueError("Decrypted a meta block but stated recipient is not this private key!")
        # Now work with decryptInfo and success_nonce to extract file data.
        senderKey = UserLock.from_id(decryptInfo['senderID'])
        senderBox = nacl.public.Box(recipient_key.private_key, senderKey.public_key)
        fileInfo_raw = b64decode(decryptInfo['fileInfo'])
        fileInfo_decrypted = senderBox.decrypt(fileInfo_raw, success_nonce).decode('utf8')
        fileInfo = json.loads(fileInfo_decrypted)
        # Overwrite decryptInfo's fileInfo key
        decryptInfo['fileInfo'] = fileInfo
        return decryptInfo
545973
async def get_decryption_aes_key(self, key: bytes, material_description: Dict[str, Any]) -> bytes:
        
        raise NotImplementedError()
1234233
def decrypt(self, token, key, cek=None):
        
        if not isinstance(token, JWEnc):
            jwe = JWEnc().unpack(token)
        else:
            jwe = token

        self.jwt = jwe.encrypted_key()
        jek = jwe.encrypted_key()

        _decrypt = RSAEncrypter(self.with_digest).decrypt

        _alg = jwe.headers["alg"]
        if cek:
            pass
        elif _alg == "RSA-OAEP":
            cek = _decrypt(jek, key, 'pkcs1_oaep_padding')
        elif _alg == "RSA-OAEP-256":
            cek = _decrypt(jek, key, 'pkcs1_oaep_256_padding')
        elif _alg == "RSA1_5":
            cek = _decrypt(jek, key)
        else:
            raise NotSupportedAlgorithm(_alg)

        self["cek"] = cek
        enc = jwe.headers["enc"]
        if enc not in SUPPORTED["enc"]:
            raise NotSupportedAlgorithm(enc)

        auth_data = jwe.b64_protected_header()

        msg = self._decrypt(enc, cek, jwe.ciphertext(),
                            auth_data=auth_data,
                            iv=jwe.initialization_vector(),
                            tag=jwe.authentication_tag())

        if "zip" in jwe.headers and jwe.headers["zip"] == "DEF":
            msg = zlib.decompress(msg)

        return msg
555930
def get_private_key(key_path, password_path=None):
    """"""

    assert key_path, key_path
    if not os.path.exists(key_path):
        log.fatal('%s: no such file', key_path)
        return None

    if not check_permission_safety(key_path):
        log.fatal('Private key file %s must be readable only by its owner.', key_path)
        return None

    if password_path and not check_permission_safety(password_path):
        log.fatal('Password file %s must be readable only by its owner.', password_path)
        return None

    with open(key_path) as keyfile:
        private_key = keyfile.readline().strip()

        if is_hex(private_key) and len(decode_hex(private_key)) == 32:
            log.warning('Private key in raw format. Consider switching to JSON-encoded')
        else:
            keyfile.seek(0)
            try:
                json_data = json.load(keyfile)
                if password_path:
                    with open(password_path) as password_file:
                        password = password_file.readline().strip()
                else:
                    password = getpass.getpass('Enter the private key password: ')
                if json_data['crypto']['kdf'] == 'pbkdf2':
                    password = password.encode()  # type: ignore
                private_key = encode_hex(decode_keyfile_json(json_data, password))
            except ValueError:
                log.fatal('Invalid private key format or password!')
                return None

    return private_key
121946
def parse_as_header(class_, f):
        
        version, previous_block_hash, merkle_root, height = parse_struct("L##L", f)
        # https://github.com/BTCGPU/BTCGPU/wiki/Technical-Spec
        f.read(28)  # reserved area
        (timestamp, difficulty, nonce, solution) = parse_struct("LL#S", f)
        return class_(version, previous_block_hash, merkle_root, timestamp,
                      difficulty, nonce, height, solution)
247958
def load_key(self, key, key_type, key_encoding):
        
        if key_type not in (EncryptionKeyType.PRIVATE, EncryptionKeyType.PUBLIC):
            raise ValueError(
                'Invalid key type "{key_type}" for cipher "{cipher}"'.format(key_type=key_type, cipher=self.java_name)
            )

        if key_encoding not in (KeyEncodingType.DER, KeyEncodingType.PEM):
            raise ValueError(
                'Invalid key encoding "{key_encoding}" for cipher "{cipher}"'.format(
                    key_encoding=key_encoding, cipher=self.java_name
                )
            )

        return _KEY_LOADERS[self.cipher](key, key_type, key_encoding)
223949
def parse_PRIK(chunk, encryption_key):
    """"""
    decrypted = decode_aes256('cbc',
                              encryption_key[:16],
                              decode_hex(chunk.payload),
                              encryption_key)

    hex_key = re.match(br'^LastPassPrivateKey<(?P<hex_key>.*)>LastPassPrivateKey$', decrypted).group('hex_key')
    rsa_key = RSA.importKey(decode_hex(hex_key))

    rsa_key.dmp1 = rsa_key.d % (rsa_key.p - 1)
    rsa_key.dmq1 = rsa_key.d % (rsa_key.q - 1)
    rsa_key.iqmp = number.inverse(rsa_key.q, rsa_key.p)

    return rsa_key
1109603
def __get_basic_auth_header(self):
        
        if self.secret_key is None:
            return {}

        # encode/decode for py2/py3 compatibility
        auth_b64 = "%s:%s" % (self.client_id, self.secret_key)
        auth_b64 = base64.b64encode(auth_b64.encode('utf-8'))
        auth_b64 = auth_b64.decode('utf-8')

        return {'Authorization': 'Basic %s' % auth_b64}
907622
def get_uncompressed_private_and_public_keys( privkey_str ):
    
    if not isinstance(privkey_str, (str, unicode)):
        raise ValueError("private key given is not a string")

    pk = ecdsa_private_key(str(privkey_str))
    pk_hex = pk.to_hex()

    # force uncompressed
    if len(pk_hex) > 64:
        if pk_hex[-2:] != '01':
            raise ValueError("private key does not end in '01'")

        pk_hex = pk_hex[:64]

    pubk_hex = ecdsa_private_key(pk_hex).public_key().to_hex()
    return pk_hex, pubk_hex
574247
def read_header
      @pos = 0

      # Read first block and check for the header
      buf = @ios.read(@buffer_size, @output_buffer ||= ''.b)

      # Use cipher specified in header, or global cipher if it has no header
      iv, key, cipher_name, cipher = nil
      header                       = Header.new
      if header.parse!(buf)
        @header_present = true
        @compressed     = header.compressed?
        @version        = header.version
        cipher          = header.cipher
        cipher_name     = header.cipher_name || cipher.cipher_name
        key             = header.key
        iv              = header.iv
      else
        @header_present = false
        @compressed     = nil
        cipher          = SymmetricEncryption.cipher(@version)
        cipher_name     = cipher.cipher_name
      end

      @stream_cipher = ::OpenSSL::Cipher.new(cipher_name)
      @stream_cipher.decrypt
      @stream_cipher.key = key || cipher.send(:key)
      @stream_cipher.iv  = iv || cipher.iv

      decrypt(buf)
    end
642524
def main_decrypt(A):
    ""
    profile = get_profile(A)
    localKeys = profile.get('local keys', [])
    if not localKeys:
        localKeys = [make_lock_securely(warn_only = A.ignore_entropy)]
    else:
        localKeys = [crypto.UserLock.private_from_b64(k['private_key']) for k in localKeys]
    if not os.path.exists(A.path):
        error_out("File or directory '{}' does not exist.".format(A.path))
    if os.path.isfile(A.path):
        for k in localKeys:
            print("Attempting decryption with:", k.userID)
            try:
                filename, senderID, decrypted = decrypt_file(A.path, k, base64 = A.base64)
                break
            except ValueError as E:
                pass
        else:
            error_out("Failed to decrypt with all available keys.")
    else:
        error_out("Specified path '{}' is not a file.".format(A.path))
    print("Decrypted file from", senderID)
    print("Saving output to", filename)
    with open(filename, "wb") as O:
        O.write(decrypted)
1075364
def get_hmac(self, key):
        
        h = HMAC.new(key, None, SHA256)
        h.update(self.iv)
        h.update(str(self.chunks).encode())
        h.update(self.f_key)
        h.update(self.alpha_key)
        h.update(str(self.encrypted).encode())
        return h.digest()
229167
def decrypt(self, data):
        
        if False in six.itervalues(self.ready):
            raise CipherError(data)
        decryptor = self._cipher.decryptor()
        tmp = decryptor.update(data) + decryptor.finalize()
        self.iv = data[-self.block_size:]
        return tmp
545993
def decrypt(self, binary):
        '''
        
        '''
        try:
            encrypted = self.verify_key.verify(binary)
        except BadSignatureError:
            log.error('Signature was forged or corrupt', exc_info=True)
            raise BadSignatureException('Signature was forged or corrupt')
        try:
            packed = self.priv_key.decrypt(encrypted)
        except CryptoError:
            log.error('Unable to decrypt', exc_info=True)
            raise CryptoException('Unable to decrypt')
        return umsgpack.unpackb(packed)
211413
def get_privatekey(keydata):
    """"""
    key = serialization.load_pem_private_key(
        keydata,
        password=None,
        backend=default_backend(),
    )
    return key
1265995
def decrypt password = nil, ciphertext = nil
      return @raw_content if @deferred_encryption && @raw_content

      # Given a private key and a nil password OpenSSL::PKey::RSA.new() will
      # *prompt* for a password, we default to an empty string to avoid that.
      ciphertext ||= @instance[@name]
      unless @deferred_encryption
        return nil if ciphertext.nil?
        return "" if ciphertext.empty?
      end

      return "*encrypted*" if password.nil?
      unless @private_key
        raise StrongboxError.new("#{@instance.class} model does not have private key_file")
      end

      if ciphertext
        ciphertext = Base64.decode64(ciphertext) if @base64
        private_key = get_rsa_key(@private_key,password)
        if @symmetric == :always
          random_key = @instance[@symmetric_key]
          random_iv = @instance[@symmetric_iv]
          if @base64
            random_key = Base64.decode64(random_key)
            random_iv = Base64.decode64(random_iv)
          end
          cipher = Cipher.new(@symmetric_cipher)
          cipher.decrypt
          cipher.key = private_key.private_decrypt(random_key,@padding)
          cipher.iv = private_key.private_decrypt(random_iv,@padding)
          plaintext = cipher.update(ciphertext)
          plaintext << cipher.final
        else
          plaintext = private_key.private_decrypt(ciphertext,@padding)
        end
      else
        nil
      end
    end
287110
def get_from_headers(request, key):
    
    value = request.headers.get(key)
    return to_native(value)