Read plaintext data from the OpenSSL internal BIO
186941
private int readPlaintextData(final ByteBuffer dst) {
        final int sslRead;
        final int pos = dst.position();
        if (dst.isDirect()) {
            sslRead = SSL.readFromSSL(ssl, bufferAddress(dst) + pos, dst.limit() - pos);
            if (sslRead > 0) {
                dst.position(pos + sslRead);
            }
        } else {
            final int limit = dst.limit();
            final int len = min(maxEncryptedPacketLength0(), limit - pos);
            final ByteBuf buf = alloc.directBuffer(len);
            try {
                sslRead = SSL.readFromSSL(ssl, memoryAddress(buf), len);
                if (sslRead > 0) {
                    dst.limit(pos + sslRead);
                    buf.getBytes(buf.readerIndex(), dst);
                    dst.limit(limit);
                }
            } finally {
                buf.release();
            }
        }

        return sslRead;
    }
770183
def decode_pc23_message(raw_string):
    

    data = {}
    wcy = raw_string.split("^")
    data[const.R] = int(wcy[1])
    data[const.expk] = int(wcy[2])
    data[const.CALLSIGN] = wcy[3]
    data[const.A] = wcy[4]
    data[const.SFI] = wcy[5]
    data[const.K] = wcy[6]
    data[const.AURORA] = wcy[7]
    data["node"] = wcy[7]
    data["ip"] = wcy[8]
    data["raw_data"] = raw_string
    return data
996395
def read(self, encoding="utf8"):
        
        with open(self._filename, "rb") as f:
            if self.key:
                return get_module("mo_math.crypto").decrypt(f.read(), self.key)
            else:
                content = f.read().decode(encoding)
                return content
242993
private static void exploreExtensions(ByteBuffer input, List<String> alpnProtocols, ByteArrayOutputStream out)
            throws SSLException {
        ByteArrayOutputStream extensionOut = out == null ? null : new ByteArrayOutputStream();
        int length = getInt16(input);           // length of extensions
        writeInt16(extensionOut, 0); //placeholder
        while (length > 0) {
            int extType = getInt16(input);      // extenson type
            writeInt16(extensionOut, extType);
            int extLen = getInt16(input);       // length of extension data
            writeInt16(extensionOut, extLen);
            if (extType == 16) {      // 0x00: ty
                if(out == null) {
                    exploreALPNExt(input, alpnProtocols);
                } else {
                    throw new ALPNPresentException();
                }
            } else {                    // ignore other extensions
                processByteVector(input, extLen, extensionOut);
            }

            length -= extLen + 4;
        }
        if(out != null) {
            byte[] alpnBits = generateAlpnExtension(alpnProtocols);
            extensionOut.write(alpnBits,0 ,alpnBits.length);
            byte[] extensionsData = extensionOut.toByteArray();
            int newLength = extensionsData.length - 2;
            extensionsData[0] = (byte) ((newLength >> 8) & 0xFF);
            extensionsData[1] = (byte) (newLength & 0xFF);
            out.write(extensionsData, 0, extensionsData.length);
        }

    }
908872
def read_bytes(fo, writer_schema=None, reader_schema=None):
    """"""
    size = read_long(fo)
    return fo.read(size)
1254302
def main_encrypt(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]
    # First key is considered "main"
    userKey = localKeys[0]
    print("User ID:", userKey.userID)
    if not os.path.exists(A.path):
        error_out("File or directory '{}' does not exist.".format(A.path))
    # Create, fetch or error out for recipient list:
    recipients = resolve_recipients(profile, A.recipient)
    recipients.append(userKey)
    print("Recipients:", *set(k.userID if isinstance(k, crypto.UserLock) else k for k in recipients))
    # Do files OR folders
    if os.path.isfile(A.path):
        crypted = encrypt_file(A.path, userKey, recipients)
    elif os.path.isdir(A.path):
        crypted = encrypt_folder(A.path, userKey, recipients)
    else:
        error_out("Specified path '{}' is neither a file nor a folder.".format(A.path))
    if A.base64:
        crypted = crypto.b64encode(crypted)
    if not A.output:
        A.output = hex(int.from_bytes(os.urandom(6),'big'))[2:] + ".minilock"
    print("Saving output to", A.output)
    with open(A.output, "wb") as O:
        O.write(crypted)
1363176
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
            knowledge_base):
    """"""
    _ = stderr, time_taken, args, knowledge_base  # Unused.
    self.CheckReturn(cmd, return_val)
    output = iter(stdout.decode("utf-8").splitlines())

    # Compile all regexes in advance.
    sys_info_re = re.compile(r"\s*System Information")
    sys_regexes = {
        "system_manufacturer": self._re_compile("Manufacturer"),
        "serial_number": self._re_compile("Serial Number"),
        "system_product_name": self._re_compile("Product Name"),
        "system_uuid": self._re_compile("UUID"),
        "system_sku_number": self._re_compile("SKU Number"),
        "system_family": self._re_compile("Family"),
        "system_assettag": self._re_compile("Asset Tag")
    }

    bios_info_re = re.compile(r"\s*BIOS Information")
    bios_regexes = {
        "bios_vendor": self._re_compile("Vendor"),
        "bios_version": self._re_compile("Version"),
        "bios_release_date": self._re_compile("Release Date"),
        "bios_rom_size": self._re_compile("ROM Size"),
        "bios_revision": self._re_compile("BIOS Revision")
    }

    # Initialize RDF.
    dmi_info = rdf_client.HardwareInfo()

    for line in output:
      if sys_info_re.match(line):
        # Collect all System Information until we hit a blank line.
        while line:
          for attr, regex in iteritems(sys_regexes):
            match = regex.match(line)
            if match:
              setattr(dmi_info, attr, match.group(1).strip())
              break
          line = next(output)

      elif bios_info_re.match(line):
        # Collect all BIOS Information until we hit a blank line.
        while line:
          for attr, regex in iteritems(bios_regexes):
            match = regex.match(line)
            if match:
              setattr(dmi_info, attr, match.group(1).strip())
              break
          line = next(output)

    yield dmi_info
510258
function (command) {
    command.option('--opensslbin <file>',
      'Location of the OpenSSL executable that the command uses. If not ' +
      'specified, the command attempts to find an OpenSSL executable in ' +
      'the current environment path.')
    command.option('-s, --san [value]',
      'add Subject Alternative Name(s) to the CSR', sanOption, [])
    command.option('-P, --passphrase [pass]',
      'Password for the private key. If specified with no value, prompts ' +
      'for the value.')
    Object.keys(pki.SUBJECT_ATTRIBUTES).forEach(function (key) {
      var attributeInfo = pki.SUBJECT_ATTRIBUTES[key]
      var optionName = fieldAsOption(key)
      var optionValue = attributeInfo.optionValue || optionName.toLowerCase()
      command.option('--' + fieldAsOption(key) + ' <' + optionValue + '>',
        attributeInfo.description)
    })
    return command
  }
1102771
def decrypt_message_data(self, body):
        
        if len(body) < 8:
            raise InvalidBufferError(body)

        # TODO Check salt, session_id and sequence_number
        key_id = struct.unpack('<Q', body[:8])[0]
        if key_id != self.auth_key.key_id:
            raise SecurityError('Server replied with an invalid auth key')

        msg_key = body[8:24]
        aes_key, aes_iv = self._calc_key(self.auth_key.key, msg_key, False)
        body = AES.decrypt_ige(body[24:], aes_key, aes_iv)

        # https://core.telegram.org/mtproto/security_guidelines
        # Sections "checking sha256 hash" and "message length"
        our_key = sha256(self.auth_key.key[96:96 + 32] + body)
        if msg_key != our_key.digest()[8:24]:
            raise SecurityError(
                "Received msg_key doesn't match with expected one")

        reader = BinaryReader(body)
        reader.read_long()  # remote_salt
        if reader.read_long() != self.id:
            raise SecurityError('Server replied with a wrong session ID')

        remote_msg_id = reader.read_long()
        remote_sequence = reader.read_int()
        reader.read_int()  # msg_len for the inner object, padding ignored

        # We could read msg_len bytes and use those in a new reader to read
        # the next TLObject without including the padding, but since the
        # reader isn't used for anything else after this, it's unnecessary.
        obj = reader.tgread_object()

        return TLMessage(remote_msg_id, remote_sequence, obj)
47532
def read_data(self, offsets):
        # type: (Descriptor, Offsets) -> Tuple[bytes, Offsets]
        
        newoffset = None
        if not self.local_path.use_stdin:
            if offsets.num_bytes == 0:
                return None, None
            # compute start from view
            start = self.local_path.view.fd_start + offsets.range_start
            # encrypted offsets will read past the end of the file due
            # to padding, but will be accounted for after encryption+padding
            with self.local_path.absolute_path.open('rb') as fd:
                fd.seek(start, 0)
                data = fd.read(offsets.num_bytes)
        else:
            data = blobxfer.STDIN.read(self._chunk_size)
            if not data:
                with self._meta_lock:
                    self._offset -= offsets.num_bytes
                    self._ase.size -= offsets.num_bytes
                    self._total_chunks -= 1
                    self._chunk_num -= 1
                    self._outstanding_ops -= 1
            else:
                num_bytes = len(data)
                with self._meta_lock:
                    self._offset -= offsets.num_bytes
                    self._ase.size -= offsets.num_bytes
                    newoffset = Offsets(
                        chunk_num=self._chunk_num - 1,
                        num_bytes=num_bytes,
                        range_start=self._offset,
                        range_end=self._offset + num_bytes - 1,
                        pad=False,
                    )
                    self._total_chunks += 1
                    self._outstanding_ops += 1
                    self._offset += num_bytes
                    self._ase.size += num_bytes
        if self.must_compute_md5 and data:
            with self._hasher_lock:
                self.md5.update(data)
                if self.is_resumable:
                    self._md5_cache[self._chunk_num - 1] = self.md5.hexdigest()
        return data, newoffset
136314
def read(self, cnt=None):
        """"""
        if cnt > 8 * 1024:
            raise BadRarFile('Bad count to header decrypt - wrong password?')

        # consume old data
        if cnt <= len(self.buf):
            res = self.buf[:cnt]
            self.buf = self.buf[cnt:]
            return res
        res = self.buf
        self.buf = EMPTY
        cnt -= len(res)

        # decrypt new data
        blklen = 16
        while cnt > 0:
            enc = self.f.read(blklen)
            if len(enc) < blklen:
                break
            dec = self.ciph.decrypt(enc)
            if cnt >= len(dec):
                res += dec
                cnt -= len(dec)
            else:
                res += dec[:cnt]
                self.buf = dec[cnt:]
                cnt = 0

        return res
1303403
def data(self):
        
        # Check if signatire is detached
        if self.detached:
            return None
        bio = Membio()
        if not libcrypto.CMS_verify(self.ptr, None, None, None, bio.bio,
                                    Flags.NO_VERIFY):
            raise CMSError("extract data")
        return str(bio)
219669
def read(cls, source):
        
        if hasattr(source, "read"):
            return cls.fromfile(source)
        if os.path.exists(source):
            return cls.fromfile(source)
        if isinstance(source, six.string_types):
            source = source.encode("utf8")
        return cls.fromstring(source)
934723
def _read_ascii(self):
        """"""
        # NOTE: ascii files store binned data using C-like ordering.
        # Dimensions are iterated like x, y, z (so z changes fastest)

        header_str = ''
        with open(self.path) as f:
            for line in f:
                if line.startswith('#'):
                    header_str += line
        self._read_header(header_str)

        data = np.loadtxt(self.path, delimiter=',', unpack=True, ndmin=1)

        # separate data by statistic (neglecting bin columns when necessary)
        n_dim = len(self.dimensions)
        data = {stat: data[n_dim+i] for i, stat in enumerate(self.statistics)}

        # reshape data according to binning
        data_shape = [dim.n_bins for dim in self.dimensions]
        data = {k: v.reshape(data_shape) for k, v in data.items()}

        self.data = data
44513
def _read_bytes_from_framed_body(self, b):
        
        plaintext = b""
        final_frame = False
        _LOGGER.debug("collecting %d bytes", b)
        while len(plaintext) < b and not final_frame:
            _LOGGER.debug("Reading frame")
            frame_data, final_frame = deserialize_frame(
                stream=self.source_stream, header=self._header, verifier=self.verifier
            )
            _LOGGER.debug("Read complete for frame %d", frame_data.sequence_number)
            if frame_data.sequence_number != self.last_sequence_number + 1:
                raise SerializationError("Malformed message: frames out of order")
            self.last_sequence_number += 1
            aad_content_string = aws_encryption_sdk.internal.utils.get_aad_content_string(
                content_type=self._header.content_type, is_final_frame=frame_data.final_frame
            )
            associated_data = assemble_content_aad(
                message_id=self._header.message_id,
                aad_content_string=aad_content_string,
                seq_num=frame_data.sequence_number,
                length=len(frame_data.ciphertext),
            )
            plaintext += decrypt(
                algorithm=self._header.algorithm,
                key=self._derived_data_key,
                encrypted_data=frame_data,
                associated_data=associated_data,
            )
            plaintext_length = len(plaintext)
            _LOGGER.debug("bytes collected: %d", plaintext_length)
        if final_frame:
            _LOGGER.debug("Reading footer")
            self.footer = deserialize_footer(stream=self.source_stream, verifier=self.verifier)

        return plaintext
615121
def unwrap(self, encrypted_data):
        
        length = self.tls_connection.bio_write(encrypted_data)
        data = b''
        counter = 0

        while True:
            try:
                data_chunk = self.tls_connection.recv(self.BIO_BUFFER_SIZE)
            except SSL.WantReadError:
                break
            data += data_chunk

            counter += self.BIO_BUFFER_SIZE
            if counter > length:
                break

        return data
478057
def _parse_openssl_crl(crl_filename):
    '''
    
    '''
    if not salt.utils.path.which('openssl'):
        raise salt.exceptions.SaltInvocationError(
            'openssl binary not found in path'
        )
    cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))

    output = __salt__['cmd.run_stdout'](cmd)

    crl = {}
    for line in output.split('\n'):
        line = line.strip()
        if line.startswith('Version '):
            crl['Version'] = line.replace('Version ', '')
        if line.startswith('Signature Algorithm: '):
            crl['Signature Algorithm'] = line.replace(
                'Signature Algorithm: ', '')
        if line.startswith('Issuer: '):
            line = line.replace('Issuer: ', '')
            subject = {}
            for sub_entry in line.split('/'):
                if '=' in sub_entry:
                    sub_entry = sub_entry.split('=')
                    subject[sub_entry[0]] = sub_entry[1]
            crl['Issuer'] = subject
        if line.startswith('Last Update: '):
            crl['Last Update'] = line.replace('Last Update: ', '')
            last_update = datetime.datetime.strptime(
                crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
            crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
        if line.startswith('Next Update: '):
            crl['Next Update'] = line.replace('Next Update: ', '')
            next_update = datetime.datetime.strptime(
                crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
            crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
        if line.startswith('Revoked Certificates:'):
            break

    if 'No Revoked Certificates.' in output:
        crl['Revoked Certificates'] = []
        return crl

    output = output.split('Revoked Certificates:')[1]
    output = output.split('Signature Algorithm:')[0]

    rev = []
    for revoked in output.split('Serial Number: '):
        if not revoked.strip():
            continue

        rev_sn = revoked.split('\n')[0].strip()
        revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
        rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
        # pylint: disable=unused-variable
        for rev_item, rev_values in six.iteritems(rev_yaml):
            # pylint: enable=unused-variable
            if 'Revocation Date' in rev_values:
                rev_date = datetime.datetime.strptime(
                    rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
                rev_values['Revocation Date'] = rev_date.strftime(
                    "%Y-%m-%d %H:%M:%S")

        rev.append(rev_yaml)

    crl['Revoked Certificates'] = rev

    return crl