This method is used to encrypt and flush to socket channel

@param outAppBuf Plaintext message
@return writen length
@throws IOException sslEngine error during data write
168141
@Override
    public int write(ByteBuffer outAppBuf, Callback callback) throws IOException {
        if (!initialHSComplete) {
            IllegalStateException ex = new IllegalStateException("The initial handshake is not complete.");
            callback.failed(ex);
            throw ex;
        }

        int ret = 0;
        if (!outAppBuf.hasRemaining()) {
            callback.succeeded();
            return ret;
        }

        final int remain = outAppBuf.remaining();
        int packetBufferSize = sslEngine.getSession().getPacketBufferSize();
        List<ByteBuffer> pocketBuffers = new ArrayList<>();
        boolean closeOutput = false;

        outer:
        while (ret < remain) {
            ByteBuffer packetBuffer = newBuffer(packetBufferSize);

            wrap:
            while (true) {
                SSLEngineResult result = wrap(outAppBuf, packetBuffer);
                ret += result.bytesConsumed();

                switch (result.getStatus()) {
                    case OK: {
                        if (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_TASK) {
                            doTasks();
                        }

                        packetBuffer.flip();
                        if (packetBuffer.hasRemaining()) {
                            pocketBuffers.add(packetBuffer);
                        }
                    }
                    break wrap;

                    case BUFFER_OVERFLOW: {
                        packetBufferSize = sslEngine.getSession().getPacketBufferSize();
                        ByteBuffer b = newBuffer(packetBuffer.position() + packetBufferSize);
                        packetBuffer.flip();
                        b.put(packetBuffer);
                        packetBuffer = b;
                    }
                    break; // retry the operation.

                    case CLOSED: {
                        log.info("Session {} SSLEngine will close", session.getSessionId());
                        packetBuffer.flip();
                        if (packetBuffer.hasRemaining()) {
                            pocketBuffers.add(packetBuffer);
                        }
                        closeOutput = true;
                    }
                    break outer;

                    default: {
                        SecureNetException ex = new SecureNetException(StringUtils.replace("Session {} SSLEngine writes data exception. status -> {}", session.getSessionId(), result.getStatus()));
                        callback.failed(ex);
                        throw ex;
                    }
                }
            }
        }

        session.write(pocketBuffers, callback);
        if (closeOutput) {
            closeOutbound();
        }
        return ret;
    }
583708
@Override
  public boolean processBytesFromPeer(ByteBuffer bytes) throws GeneralSecurityException {
    // If we're the client and we haven't given an output frame, we shouldn't be processing any
    // bytes.
    if (outputFrame == null && isClient) {
      return true;
    }
    // If we already have bytes to write, just return.
    if (outputFrame != null && outputFrame.hasRemaining()) {
      return true;
    }
    int remaining = bytes.remaining();
    // Call handshaker service to proceess the bytes.
    if (outputFrame == null) {
      checkState(!isClient, "Client handshaker should not process any frame at the beginning.");
      outputFrame = handshaker.startServerHandshake(bytes);
    } else {
      outputFrame = handshaker.next(bytes);
    }
    // If handshake has finished or we already have bytes to write, just return true.
    if (handshaker.isFinished() || outputFrame.hasRemaining()) {
      return true;
    }
    // We have done processing input bytes, but no bytes to write. Thus we need more data.
    if (!bytes.hasRemaining()) {
      return false;
    }
    // There are still remaining bytes. Thus we need to continue processing the bytes.
    // Prevent infinite loop by checking some bytes are consumed by handshaker.
    checkState(bytes.remaining() < remaining, "Handshaker did not consume any bytes.");
    return processBytesFromPeer(bytes);
  }
1246856
public byte[] toByteArray() throws IOException {
		ByteArrayWriter baw = new ByteArrayWriter();

		try {
			baw.writeInt(flags);

			if (version > 3)
				baw.write(type);

			if (isFlagSet(SSH_FILEXFER_ATTR_SIZE)) {
				baw.write(size.toByteArray());
			}

			if (version <= 3 && isFlagSet(SSH_FILEXFER_ATTR_UIDGID)) {
				if (uid != null) {
					try {
						baw.writeInt(Long.parseLong(uid));
					} catch (NumberFormatException ex) {
						baw.writeInt(0);
					}
				} else {
					baw.writeInt(0);
				}

				if (gid != null) {
					try {
						baw.writeInt(Long.parseLong(gid));
					} catch (NumberFormatException ex) {
						baw.writeInt(0);
					}
				} else {
					baw.writeInt(0);
				}
			} else if (version > 3 && isFlagSet(SSH_FILEXFER_ATTR_OWNERGROUP)) {
				if (uid != null)
					baw.writeString(uid, sftp.getCharsetEncoding());
				else
					baw.writeString("");

				if (gid != null)
					baw.writeString(gid, sftp.getCharsetEncoding());
				else
					baw.writeString("");
			}

			if (isFlagSet(SSH_FILEXFER_ATTR_PERMISSIONS)) {
				baw.writeInt(permissions.longValue());
			}

			if (version <= 3 && isFlagSet(SSH_FILEXFER_ATTR_ACCESSTIME)) {
				baw.writeInt(atime.longValue());
				baw.writeInt(mtime.longValue());
			} else if (version > 3) {

				if (isFlagSet(SSH_FILEXFER_ATTR_ACCESSTIME)) {
					baw.writeUINT64(atime);
				}

				if (isFlagSet(SSH_FILEXFER_ATTR_SUBSECOND_TIMES)) {
					baw.writeUINT32(atime_nano);
				}

				if (isFlagSet(SSH_FILEXFER_ATTR_CREATETIME)) {
					baw.writeUINT64(createtime);
				}

				if (isFlagSet(SSH_FILEXFER_ATTR_SUBSECOND_TIMES)) {
					baw.writeUINT32(createtime_nano);
				}

				if (isFlagSet(SSH_FILEXFER_ATTR_MODIFYTIME)) {
					baw.writeUINT64(mtime);
				}

				if (isFlagSet(SSH_FILEXFER_ATTR_SUBSECOND_TIMES)) {
					baw.writeUINT32(mtime_nano);
				}

			}

			if (isFlagSet(SSH_FILEXFER_ATTR_ACL)) {
				ByteArrayWriter tmp = new ByteArrayWriter();

				try {
					Enumeration<ACL> e = acls.elements();
					tmp.writeInt(acls.size());
					while (e.hasMoreElements()) {
						ACL acl = e.nextElement();
						tmp.writeInt(acl.getType());
						tmp.writeInt(acl.getFlags());
						tmp.writeInt(acl.getMask());
						tmp.writeString(acl.getWho());
					}

					baw.writeBinaryString(tmp.toByteArray());
				} finally {
					tmp.close();
				}
			}

			if (isFlagSet(SSH_FILEXFER_ATTR_EXTENDED)) {
				baw.writeInt(extendedAttributes.size());
				Enumeration<String> e = extendedAttributes.keys();
				while (e.hasMoreElements()) {
					String key = e.nextElement();
					baw.writeString(key);
					baw.writeBinaryString(extendedAttributes.get(key));
				}
			}

			return baw.toByteArray();
		} finally {
			try {
				baw.close();
			} catch (IOException e) {
			}
		}
	}
785813
private IoBuffer encodeServerBW(ServerBW serverBW) {
        final IoBuffer out = IoBuffer.allocate(4);
        out.putInt(serverBW.getBandwidth());
        return out;
    }
1214905
public void encrypt(ByteBuffer src) throws SSLException {
        if (!handshakeComplete) {
            throw new IllegalStateException();
        }

        if (!src.hasRemaining()) {
            if (outNetBuffer == null) {
                outNetBuffer = emptyBuffer;
            }
            return;
        }

        createOutNetBuffer(src.remaining());

        // Loop until there is no more data in src
        while (src.hasRemaining()) {

            SSLEngineResult result = sslEngine.wrap(src, outNetBuffer.buf());
            if (result.getStatus() == SSLEngineResult.Status.OK) {
                if (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_TASK) {
                    doTasks();
                }
            } else if (result.getStatus() == SSLEngineResult.Status.BUFFER_OVERFLOW) {
                outNetBuffer.capacity(outNetBuffer.capacity() << 1);
                outNetBuffer.limit(outNetBuffer.capacity());
            } else {
                throw new SSLException("SSLEngine error during encrypt: "
                        + result.getStatus() + " src: " + src
                        + "outNetBuffer: " + outNetBuffer);
            }
        }

        outNetBuffer.flip();
    }
368568
public void toRfc5425SyslogMessage(Writer out) throws IOException {

        String rfc5424Message = toRfc5424SyslogMessage();
        int length = rfc5424Message.getBytes(StandardCharsets.UTF_8).length;
        out.write(String.valueOf(length));
        out.write(SP);
        out.write(rfc5424Message);
    }
722939
public void write(io.netty.buffer.ByteBuf buf) throws IOException {
    write(buf, 0, buf.readableBytes());
  }
436664
@Override
  public int write(OutputStreamWithBuffer os, char []cbuf, int off, int len)
    throws IOException
  {
    byte []buffer = os.buffer();
    int length = os.offset();
    int capacity = buffer.length;
    int tail = off + len;
    int head = off;

    while (off < tail) {
      while (capacity - length <= 4) {
        buffer = os.nextBuffer(length);
        length = os.offset();
      }
      
      char ch = cbuf[off++];

      if (ch < 0x80) {
        buffer[length++] = (byte) ch;
      }
      else if (ch < 0x800) {
        buffer[length++] = (byte) (0xc0 + (ch >> 6));
        buffer[length++] = (byte) (0x80 + (ch & 0x3f));
      }
      else if (ch < 0xd800 || 0xdfff < ch) {
        // server/0815
        buffer[length++] = (byte) (0xe0 + (ch >> 12));
        buffer[length++] = (byte) (0x80 + ((ch >> 6) & 0x3f));
        buffer[length++] = (byte) (0x80 + (ch & 0x3f));
      }
      else if (off == tail) {
        off--;
        break;
      }
      else {
        char ch2 = cbuf[off++];
        
        int v = 0x10000 + (ch & 0x3ff) * 0x400 + (ch2 & 0x3ff);
          
        buffer[length++] = (byte) (0xf0 + (v >> 18));
        buffer[length++] = (byte) (0x80 + ((v >> 12) & 0x3f));
        buffer[length++] = (byte) (0x80 + ((v >> 6) & 0x3f));
        buffer[length++] = (byte) (0x80 + (v & 0x3f));
      }
    }

    os.offset(length);
    
    return off - head;
  }
568732
synchronized public int encodeIntoByteBuffer(final ByteBuffer buffer) {
        final long maxValue = getMaxValue();
        final int relevantLength = countsArrayIndex(maxValue) + 1;
        if (buffer.capacity() < getNeededByteBufferCapacity(relevantLength)) {
            throw new ArrayIndexOutOfBoundsException("buffer does not have capacity for " +
                    getNeededByteBufferCapacity(relevantLength) + " bytes");
        }
        int initialPosition = buffer.position();
        buffer.putInt(getEncodingCookie());
        buffer.putInt(0); // Placeholder for payload length in bytes.
        buffer.putInt(getNormalizingIndexOffset());
        buffer.putInt(numberOfSignificantValueDigits);
        buffer.putLong(lowestDiscernibleValue);
        buffer.putLong(highestTrackableValue);
        buffer.putDouble(getIntegerToDoubleValueConversionRatio());

        int payloadStartPosition = buffer.position();
        fillBufferFromCountsArray(buffer);
        buffer.putInt(initialPosition + 4, buffer.position() - payloadStartPosition); // Record the payload length


        return buffer.position() - initialPosition;
    }
676397
private int write(ByteBuffer outbuf)
    {
        int nbytes;
        try {
            nbytes = fd.write(outbuf);
            if (nbytes == 0) {
                errno.set(ZError.EAGAIN);
            }
        }
        catch (IOException e) {
            errno.set(ZError.ENOTCONN);
            nbytes = -1;
        }

        return nbytes;
    }
165459
public static SSLEngine getOutboundSSLEngine(SSLContext context,
                                                 SSLLinkConfig config, String host, int port, SSLConnectionLink connLink) {
        // PK46069 - use engine that allows session id re-use
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "getOutboundSSLEngine, host=" + host + ", port=" + port);
        }
        SSLEngine engine = context.createSSLEngine(host, port);

        configureEngine(engine, FlowType.OUTBOUND, config, connLink);
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "getOutboundSSLEngine, hc=" + engine.hashCode());
        }
        return engine;
    }
159933
@Override
    public VirtualConnectionFactory getOutboundVCFactory(Map<Object, Object> sslProps, boolean overwriteExisting) throws IllegalStateException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "getOutboundVCFactory(ssl)");
        }

        // Ensure the SSL channel factory exists in the outbound channel
        // definitions.
        if (-1 == this.sslChannelIndex) {
            throw new IllegalStateException("The SSL channel factory does not exist in this CFEndPoint.");
        }

        // Create a new OutboundChannelDefintion with new properties.
        OutboundChannelDefinition existingDef = this.outboundChannelDefs.get(this.sslChannelIndex);
        OutboundChannelDefinition newChannelDef = new OutboundChannelDefinitionImpl(existingDef, sslProps, overwriteExisting);
        // Overlay the new definition into the array managed by this endpoint.
        this.outboundChannelDefs.add(this.sslChannelIndex, newChannelDef);
        // Now that the properties are folded in, call the basic implementation.
        VirtualConnectionFactory localVCF = getOutboundVCFactory();

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "getOutboundVCFactory(ssl)");
        }
        return localVCF;
    }
1212915
synchronized public int encodeIntoByteBuffer(final ByteBuffer buffer) {
        long maxValue = integerValuesHistogram.getMaxValue();
        int relevantLength = integerValuesHistogram.getLengthForNumberOfBuckets(
                integerValuesHistogram.getBucketsNeededToCoverValue(maxValue));
        if (buffer.capacity() < getNeededByteBufferCapacity(relevantLength)) {
            throw new ArrayIndexOutOfBoundsException("buffer does not have capacity for " +
                    getNeededByteBufferCapacity(relevantLength) + " bytes");
        }
        buffer.putInt(DHIST_encodingCookie);
        buffer.putInt(getNumberOfSignificantValueDigits());
        buffer.putLong(configuredHighestToLowestValueRatio);
        return integerValuesHistogram.encodeIntoByteBuffer(buffer) + 16;
    }
854384
def encrypt(self, text, app_id):
        
        text = b"".join(
            [
                to_binary(self.get_random_string()),
                struct.pack(b"I", socket.htonl(len(to_binary(text)))),
                to_binary(text),
                to_binary(app_id)
            ]
        )
        text = pkcs7.encode(text)
        encryptor = self.cipher.encryptor()
        ciphertext = to_binary(encryptor.update(text) + encryptor.finalize())
        return base64.b64encode(ciphertext)
321231
public String encryptBytes(byte[] credentials) {
        checkNotNull(credentials, "credentials");

        try {
            int length = credentials.length;
            byte[] plaintextBytes = ByteBuffer.wrap(new byte[Math.max(length + 4, MINIMUM_LENGTH)])
                    .putInt(credentials.length)
                    .put(credentials)
                    .array();

            Cipher cipher = Cipher.getInstance(CIPHER);
            cipher.init(Cipher.ENCRYPT_MODE, _key, _iv);
            byte[] encryptedApiKey = cipher.doFinal(plaintextBytes);
            return BaseEncoding.base64().omitPadding().encode(encryptedApiKey);
        } catch (Throwable t) {
            // This shouldn't happen since AES is supported by all JVMs.
            throw Throwables.propagate(t);
        }
    }
1135037
private void getEncryptedAppBuffer(int requested_size) throws IOException {

        final int size = Math.max(getConnLink().getPacketBufferSize(), requested_size);

        synchronized (closeSync) {
            if (closeCalled) {
                IOException up = new IOException("Operation failed due to connection close detected");
                throw up;
            }

            if (null != this.encryptedAppBuffer) {
                if (size <= this.encryptedAppBuffer.capacity()) {
                    // current buffer exists and is big enough
                    this.encryptedAppBuffer.clear();
                    return;
                }
                // exists but is too small
                this.encryptedAppBuffer.release();
                this.encryptedAppBuffer = null;
            }
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Tr.event(tc, "Allocating encryptedAppBuffer, size=" + size);
            }
            // Allocate the encrypted data buffer
            this.encryptedAppBuffer = SSLUtils.allocateByteBuffer(
                                                                  size, getConfig().getEncryptBuffersDirect());
        }
    }
872236
protected void increaseEncryptedBuffer() throws IOException {
        final int packetSize = getConnLink().getPacketBufferSize();
        if (null == this.encryptedAppBuffer) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Tr.event(tc, "Allocating encryptedAppBuffer, size=" + packetSize);
            }
            this.encryptedAppBuffer = SSLUtils.allocateByteBuffer(
                                                                  packetSize, getConfig().getEncryptBuffersDirect());
        } else {
            // The existing buffer isn't big enough, add another packet size to it
            final int cap = this.encryptedAppBuffer.capacity();
            final int newsize = cap + packetSize;
            if (0 > newsize) {
                // wrapped over max-int
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                    Tr.event(tc, "Unable to increase encrypted buffer beyond " + cap);
                }
                throw new IOException("Unable to increase buffer beyond " + cap);
            }
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Increasing encryptedAppBuffer to " + newsize);
            }
            WsByteBuffer temp = SSLUtils.allocateByteBuffer(
                                                            newsize, this.encryptedAppBuffer.isDirect());
            this.encryptedAppBuffer.flip();
            SSLUtils.copyBuffer(this.encryptedAppBuffer, temp, this.encryptedAppBuffer.remaining());
            this.encryptedAppBuffer.release();
            this.encryptedAppBuffer = temp;
        }
    }