Encode a Message to raw network data

@param Message $message  The Message to encode
@param bool $compress Enable message compression
@return string
485598
public function encode(Message $message, int $options = 0): string
    {
        $ctx = new Context($options);
        $qdCount = $anCount = $nsCount = $arCount = 0;

        foreach ($message->getQuestionRecords() as $record) {
            if (!$this->encodeQuestionRecord($ctx, $record)) {
                goto done;
            }

            $qdCount++;
        }

        foreach ($message->getAnswerRecords() as $record) {
            if (!$this->encodeResourceRecord($ctx, $record)) {
                goto done;
            }

            $anCount++;
        }

        foreach ($message->getAuthorityRecords() as $record) {
            if (!$this->encodeResourceRecord($ctx, $record)) {
                goto done;
            }

            $nsCount++;
        }

        foreach ($message->getAdditionalRecords() as $record) {
            if (!$this->encodeResourceRecord($ctx, $record)) {
                goto done;
            }

            $arCount++;
        }

        done:
        $packet = $this->encodeHeader($ctx, $message, $qdCount, $anCount, $nsCount, $arCount) . $ctx->data;

        if (!($options & EncodingOptions::FORMAT_TCP)) {
            \assert(
                \strlen($packet) <= 512,
                new \Error('UDP packet exceeds 512 byte limit: got ' . \strlen($packet) . ' bytes')
            );

            return $packet;
        }

        \assert(
            \strlen($packet) <= 65535,
            new \Error('TCP packet exceeds 65535 byte limit: got ' . \strlen($packet) . ' bytes')
        );

        return \pack('n', \strlen($packet)) . $packet;
    }
957828
protected function readSocket($compress = true)
    {
        $buffer = '';
        $overload = strlen('000000:000:000:');
        do {
            $buf = $this->socket->read($overload + self::BLOCK_SIZE, PHP_BINARY_READ);
            if (false === $buf) {
                throw new SocketReadException($this->socket->lastErrorAsString());
            }

            if (!trim($buf)) {
                return '';
            }

            if (substr_count($buf, ":") < 3) {
                throw new SignatureSocketException('error in format');
            }

            list($size, $block, $blocks) = explode(":", $buf);

            $aux = substr($buf, $overload);

            $this->sprintfIfDebug("%d/%d blocks (start of block %s)\n", $block, $blocks, substr($aux, 0, 10));

            $this->output->write('R');

            if ($size == strlen($aux)) {
                $this->send(self::ACK);
            } else {
                $this->send(self::NO_ACK);
                throw new BlockSizeSocketException(
                    sprintf(
                        'error in size (block %d of %d): informed %d vs %d read',
                        $block, $blocks, $size, strlen($aux)
                    )
                );
            }

            $buffer .= $aux;
        } while ($block < $blocks);

        $result = $compress ? $this->uncompress($buffer) : $buffer;

        if ($this->debug) {
            $aux = json_decode($result, true);
            if (isset($aux['data'])) {
                $this->output->writeln("received %d keys", count($aux['data']));
            }
        }

        return $result;
    }
619005
def encode(self, message, k=None):
        ''''''
        if not k: k = self.k
        message, _ = self.pad(message, k=k)
        if self.algo == 1:
            mesecc = self.ecc_manager.encode(message, k=k)
        elif self.algo == 2:
            mesecc = self.ecc_manager.encode_fast(message, k=k)
        elif self.algo == 3 or self.algo == 4:
            mesecc = rs_encode_msg(message, self.n-k, fcr=self.fcr, gen=self.g[self.n-k])
            #mesecc = rs_encode_msg_precomp(message, self.n-k, fcr=self.fcr, gen=self.g[self.n-k])

        ecc = mesecc[len(message):]
        return ecc
1002258
public function encodeMessage(Message $message, $level = 0)
    {
        $reflect    = new ReflectionClass($message);
        $properties = $reflect->getProperties(ReflectionProperty::IS_PROTECTED);
        $indent     = str_repeat('  ', $level);
        $stream     = Stream::create();

        foreach ($properties as $property) {

            $property->setAccessible(true);

            $name  = $property->getName();
            $value = $property->getValue($message);

            if ($value === null) {
                continue;
            }

            if ( ! is_array($value) && ! ($value instanceof Traversable)) {

                if ( ! $value instanceof Message) {
                    $item   = $this->encodeValue($value);
                    $buffer = $indent . $name . ': ' . $item . PHP_EOL;

                    $stream->write($buffer, strlen($buffer));

                    continue;
                }

                $innerStream  = $this->encodeMessage($value, $level + 1);
                $beginMessage = $indent . $name . ' {' . PHP_EOL;
                $endMessage   = $indent . '}' . PHP_EOL;

                $stream->write($beginMessage, strlen($beginMessage));
                $stream->writeStream($innerStream, $innerStream->getSize());
                $stream->write($endMessage, strlen($endMessage));

                continue;
            }

            foreach ($value as $val) {
                // Skip nullified repeated values
                if ($val == null) {
                    continue;
                }

                if ( ! $val instanceof Message) {
                    $item   = $this->encodeValue($val);
                    $buffer = $indent . $name . ': ' . $item . PHP_EOL;

                    $stream->write($buffer, strlen($buffer));

                    continue;
                }

                $innerStream  = $this->encodeMessage($val, $level + 1);
                $beginMessage = $indent . $name . ' {' . PHP_EOL;
                $endMessage   = $indent . '}' . PHP_EOL;

                $stream->write($beginMessage, strlen($beginMessage));
                $stream->writeStream($innerStream, $innerStream->getSize());
                $stream->write($endMessage, strlen($endMessage));
            }
        }

        $stream->seek(0);

        return $stream;
    }
925302
public function compress($buffer)
    {
        $dictionary = array();
        $data       = str_split($buffer . '');
        $out        = array();
        $phrase     = $data[0];
        $code       = 256;
        $countData  = count($data);

        for ($i = 1; $i < $countData; ++$i) {
            $currentCharacter = $data[$i];

            if (isset($dictionary[$phrase.$currentCharacter])) {
                $phrase .= $currentCharacter;

            } else {
                $out[] = strlen($phrase) > 1 ? $dictionary[$phrase] : $this->charCodeAt($phrase,0);
                $dictionary[$phrase.$currentCharacter] = $code;
                $code++;
                $phrase = $currentCharacter;
            }
        }

        $out[]    = strlen($phrase) > 1 ? $dictionary[$phrase] : $this->charCodeAt($phrase,0);
        $countOut = count($out);

        for ($i = 0; $i < $countOut; ++$i) {
            $out[$i] = $this->unichr($out[$i]);
        }

        return implode('', $out);
    }
876267
protected function writeToFile($message)
    {
        $message = $message . PHP_EOL;
        return @file_put_contents($this->logFile, $message, FILE_APPEND);
    }
131907
public function decrypt(Message $message): Message
    {
        $gnupg = new \Crypt_GPG($this->options);

        try {
            $gnupg->addDecryptKey($this->serverKeyFingerprint);
            // Replace the message with its encrypted counterpart
            $decrypted = $gnupg->decrypt($message->getBodyText());
            return (clone $message)->setBody($decrypted);
        } catch (\PEAR_Exception $ex) {
            throw new GPGMailerException(
                'Could not decrypt message: ' . $ex->getMessage(),
                $ex->getCode(),
                $ex
            );
        }
    }
918354
public function decryptMessage($message)
    {
        $calgo = $this->config->getCipherAlgorithm();
        $cmode = $this->config->getCipherMode();
        $malgo = $this->config->getHmacAlgorithm();
        
        $size = mcrypt_get_iv_size($calgo, $cmode);
        $keySize = mcrypt_get_key_size($calgo, $cmode);
        $hmacSize = strlen(hash_hmac($malgo, '', 'foo-key', true));

        $cmac = substr($message, -1 * $hmacSize);
        $iv = substr($message, 0, $size);
        $cipherText = substr($message, $size, -1 * $hmacSize);
        $hmac = hash_hmac($malgo, $iv . $cipherText, $this->computeCipherKey($this->config->getHmacKey(), $hmacSize, $iv), true);
        
        if(!SecurityUtil::timingSafeEquals($hmac, $cmac))
        {
            throw new IntegrityCheckFailedException('Invalid encrypted input message detected');
        }
        
        $key = $this->computeCipherKey($this->config->getCipherKey(), $keySize, $iv);
        $data = mcrypt_decrypt($calgo, $key, $cipherText, $cmode, $iv);
        
        // PKCS7 Padding
        $pad = ord($data[strlen($data) - 1]);
        $data = substr($data, 0, -1 * $pad);
        
        // Remove zero-byte padding from the string.
        return $data;
    }
201343
private function build_message($part) {
    $message = $part[ "message"];
    // #### only base64 encoding supported
    // #### other encodings you have to encode yourself
    if ($part[ "encode"] == "base64"){
      $message = chunk_split(base64_encode($message));
    }else if ($part[ "encode"] == "quoted-printable"){
      $message = $this->encode_qp($message);
    }
    return  "Content-Type: ".$part[ "ctype"].
            ($part[ "charset"]? "; charset = \"".$part[ "charset"]. "\"" :  "").
            ($part[ "name"]? "; name = \"".$part[ "name"]. "\"" :  "").
            (empty($part[ "encode"])? "" : "\nContent-Transfer-Encoding: ".$part[ "encode"] ).
            (empty($part[ "contentid"])? "" : "\nContent-ID: ".$part[ "contentid"] ).
            ((empty($part["contentid"])&&($part["name"]))? "\nContent-Disposition: attachment; filename=\"".$part["name"].'"' : '' ).
            "\n\n$message\n";
  }
613977
protected function encodeMessage(Protobuf\Message $message)
    {
        $descriptor = Protobuf::getRegistry()->getDescriptor($message);
        $data = [];

        foreach ($descriptor->getFields() as $tag => $field) {
            $empty = !$message->_has($tag);
            if ($field->isRequired() && $empty) {
                throw new \UnexpectedValueException(
                    sprintf(
                        'Message %s\'s field tag %s(%s) is required but has no value',
                        get_class($message),
                        $tag,
                        $field->getName()
                    )
                );
            }

            if ($empty) {
                continue;
            }

            $key = $this->useTagNumber ? $field->getNumber() : $field->getName();
            $v = $message->_get($tag);

            if ($field->isRepeated()) {
                // Make sure the value is an array of values
                $v = is_array($v) ? $v : array($v);
                $arr = [];

                foreach ($v as $k => $vv) {
                    // Skip nullified repeated values
                    if (null === $vv) {
                        continue;
                    }

                    $filteredValue = $this->filterValue($vv, $field);

                    if ($this->isKeyValueMessage($vv)) {
                        $arr[key($filteredValue)] = current($filteredValue);
                    } else {
                        $arr[$k] = $filteredValue;
                    }

                    $v = $arr;
                }
            } else {
                $v = $this->filterValue($v, $field);
            }

            $key = ($this->useCamelCase) ? $this->toCamelCase($key) : $key;

            if (isset($this->customFilters[$key])) {
                $v = call_user_func($this->customFilters[$key], $v);
            }

            $data[$key] = $v;
        }

        return $data;
    }
692407
public static function emailEncode($sEmail)
	{
		$sEmail = bin2hex($sEmail);
		$sEmail = chunk_split($sEmail, 2, '%');
		$sEmail = '%' . substr($sEmail, 0, strlen($sEmail) - 1);
		return $sEmail;
	}
241663
protected function isValidMessage($message): Message
    {
        if ($message instanceof Message) {
            return $message;
        }

        if (\is_string($message) || $message instanceof Attachment) {
            return Message::create($message);
        }

        throw new MessengerException(sprintf(
            'message must be a string or an instance of %s or %s.',
            Message::class,
            Attachment::class
        ));
    }
1040999
def encode(self, message, final=True, masking_key=None,
               opcode=None, rsv1=0, rsv2=0, rsv3=0):
        '''
        '''
        fin = 1 if final else 0
        opcode, masking_key, data = self._info(message, opcode, masking_key)
        return self._encode(data, opcode, masking_key, fin,
                            rsv1, rsv2, rsv3)
206831
public static function decodeMessage(string $message): Message
    {
        $offset = 0;
        $header = self::decodeHeader($message, $offset);
        $messageObject = new Message($header);
        $messageObject->setQuestions(self::decodeResourceRecords($message, $header->getQuestionCount(), $offset, true));
        $messageObject->setAnswers(self::decodeResourceRecords($message, $header->getAnswerCount(), $offset));
        $messageObject->setAuthoritatives(self::decodeResourceRecords($message, $header->getNameServerCount(), $offset));
        $messageObject->setAdditionals(self::decodeResourceRecords($message, $header->getAdditionalRecordsCount(), $offset));

        return $messageObject;
    }
167875
protected static function _processMessage( &$message )
    {
        $_newIndent = 0;

        foreach ( static::$_indentTokens as $_key => $_token )
        {
            if ( $_token == substr( $message, 0, $_length = strlen( $_token ) ) )
            {
                $_newIndent = ( false === $_key ? -1 : 1 );
                $message = substr( $message, $_length );
            }
        }

        return $_newIndent;
    }
816094
protected function getDecoratedMessage($message, $params = [])
    {
        $result = '';
        $prefix = '';
        foreach ($params as $option => $value) {
            if ($value) {
                $result .= $prefix . $this->decorations[$option][$value];
                $prefix = ';';
            }
        }

        if ($prefix) {
            $message = 'm' . $message;
        }

        return $result . $message;
    }
359507
private void _decompressMessageData(Message msg) {
		if((msg.flags & Message.FLAGS_COMPRESSED) == 0) {
			throw new IllegalArgumentException("message data is not compressed");
		}
		Inflater decompresser = new Inflater();
		decompresser.setInput(msg.data);
		ByteArrayOutputStream bos = new ByteArrayOutputStream(msg.data.length);
		byte[] buffer = new byte[8192];
		try {
			while (!decompresser.finished()) {
				int size = decompresser.inflate(buffer);
				bos.write(buffer, 0, size);
			}
			msg.data = bos.toByteArray();
			msg.flags &= ~Message.FLAGS_COMPRESSED;
			decompresser.end();
		} catch (DataFormatException e) {
			throw new PyroException("invalid compressed data: ", e);
		}
	}