Implementation for encryption using ByteBuffers. Used for both
engineUpdate() and engineDoFinal().
514934
private int bufferCrypt(ByteBuffer input, ByteBuffer output,
            boolean isUpdate) throws ShortBufferException,
            IllegalBlockSizeException, BadPaddingException {
        if ((input == null) || (output == null)) {
            throw new NullPointerException
                ("Input and output buffers must not be null");
        }
        int inPos = input.position();
        int inLimit = input.limit();
        int inLen = inLimit - inPos;
        if (isUpdate && (inLen == 0)) {
            return 0;
        }
        int outLenNeeded = engineGetOutputSize(inLen);
        if (output.remaining() < outLenNeeded) {
            throw new ShortBufferException("Need at least " + outLenNeeded
                + " bytes of space in output buffer");
        }

        boolean a1 = input.hasArray();
        boolean a2 = output.hasArray();

        if (a1 && a2) {
            byte[] inArray = input.array();
            int inOfs = input.arrayOffset() + inPos;
            byte[] outArray = output.array();
            int outPos = output.position();
            int outOfs = output.arrayOffset() + outPos;
            int n;
            if (isUpdate) {
                n = engineUpdate(inArray, inOfs, inLen, outArray, outOfs);
            } else {
                n = engineDoFinal(inArray, inOfs, inLen, outArray, outOfs);
            }
            input.position(inLimit);
            output.position(outPos + n);
            return n;
        } else if (!a1 && a2) {
            int outPos = output.position();
            byte[] outArray = output.array();
            int outOfs = output.arrayOffset() + outPos;
            byte[] inArray = new byte[getTempArraySize(inLen)];
            int total = 0;
            do {
                int chunk = Math.min(inLen, inArray.length);
                if (chunk > 0) {
                    input.get(inArray, 0, chunk);
                }
                int n;
                if (isUpdate || (inLen != chunk)) {
                    n = engineUpdate(inArray, 0, chunk, outArray, outOfs);
                } else {
                    n = engineDoFinal(inArray, 0, chunk, outArray, outOfs);
                }
                total += n;
                outOfs += n;
                inLen -= chunk;
            } while (inLen > 0);
            output.position(outPos + total);
            return total;
        } else { // output is not backed by an accessible byte[]
            byte[] inArray;
            int inOfs;
            if (a1) {
                inArray = input.array();
                inOfs = input.arrayOffset() + inPos;
            } else {
                inArray = new byte[getTempArraySize(inLen)];
                inOfs = 0;
            }
            byte[] outArray = new byte[getTempArraySize(outLenNeeded)];
            int outSize = outArray.length;
            int total = 0;
            boolean resized = false;
            do {
                int chunk =
                    Math.min(inLen, (outSize == 0? inArray.length : outSize));
                if (!a1 && !resized && chunk > 0) {
                    input.get(inArray, 0, chunk);
                    inOfs = 0;
                }
                try {
                    int n;
                    if (isUpdate || (inLen != chunk)) {
                        n = engineUpdate(inArray, inOfs, chunk, outArray, 0);
                    } else {
                        n = engineDoFinal(inArray, inOfs, chunk, outArray, 0);
                    }
                    resized = false;
                    inOfs += chunk;
                    inLen -= chunk;
                    if (n > 0) {
                        output.put(outArray, 0, n);
                        total += n;
                    }
                } catch (ShortBufferException e) {
                    if (resized) {
                        // we just resized the output buffer, but it still
                        // did not work. Bug in the provider, abort
                        throw (ProviderException)new ProviderException
                            ("Could not determine buffer size").initCause(e);
                    }
                    // output buffer is too small, realloc and try again
                    resized = true;
                    outSize = engineGetOutputSize(chunk);
                    outArray = new byte[outSize];
                }
            } while (inLen > 0);
            if (a1) {
                input.position(inLimit);
            }
            return total;
        }
    }
762463
async function encryptPBES1(binKey, passphrase, algorithm, iterationCount){
  // pbkdf1
  const pBuffer = jseu.encoder.stringToArrayBuffer(passphrase);
  const salt = await jscrandom.getRandomBytes(8); // defined as 8 octet
  const hash = params.passwordBasedEncryptionSchemes[algorithm].hash;
  const keyIv = await pbkdf.pbkdf1(pBuffer, salt, iterationCount, 16, hash);
  const key = keyIv.slice(0, 8);
  const iv = keyIv.slice(8, 16);

  // decryption
  const encrypt = params.passwordBasedEncryptionSchemes[algorithm].encrypt;
  let out;
  // TODO: Other Encryption Scheme
  if(encrypt === 'DES-CBC') {
    const CBC = des.CBC.instantiate(des.DES);
    const ct = CBC.create({type: 'encrypt', key, iv});
    out = Buffer.from(ct.update(binKey).concat(ct.final()));
  }
  else throw new Error('UnsupportedEncryptionAlgorithm');

  return {
    encryptionAlgorithm: {
      algorithm,
      parameters: {
        salt: Buffer.from(salt),
        iterationCount: new BN(iterationCount)
      }
    },
    encryptedData: out
  };
}
1092659
public byte[] decrypt(byte[] iv, byte[] cipherText) throws RuntimeException {

        AEADParameters aeadParams = new AEADParameters(
                new KeyParameter(key), TAG_LENGTH,
                iv,
                authData);

        cipher.init(false, aeadParams);
        byte[] buffer = newByteArray(cipherText);
        byte[] plainText = newBuffer(cipher.getOutputSize(cipherText.length));
        int outputOffset = cipher.processBytes(buffer, 0, buffer.length, plainText, 0);

        try {
            cipher.doFinal(plainText, outputOffset);
        } catch (InvalidCipherTextException e) {
            throw new RuntimeException("Error: ", e);
        }

        return plainText;
    }
968475
function ByteBuffer(arg) {
    var initial_size;
    if (arg == null) {
        initial_size = 1024 * 1024;
    } else if (typeof arg === "number") {
        initial_size = arg;
    } else if (arg instanceof Uint8Array) {
        this.buffer = arg;
        this.position = 0;  // Overwrite
        return;
    } else {
        // typeof arg -> String
        throw typeof arg + " is invalid parameter type for ByteBuffer constructor";
    }
    // arg is null or number
    this.buffer = new Uint8Array(initial_size);
    this.position = 0;
}
530180
private DataBuffer withDataBufferFactory(ByteBufHttpData data) {
        final byte[] dataArray = ByteBufUtil.getBytes(data.content());
        data.release();
        return delegate.wrap(dataArray);
    }
48470
private void packageH264Keyframe(ByteBuffer encodedData, MediaCodec.BufferInfo bufferInfo) {
        mH264Keyframe.position(mH264MetaSize);
        mH264Keyframe.put(encodedData); // BufferOverflow
    }
595613
public static String encrypt(String input, String key, String algorithm, byte[] ivOrSalt, int iterations, String encoding, String charset) throws PageException {

	try {

	    if (charset == null) charset = DEFAULT_CHARSET;
	    if (encoding == null) encoding = DEFAULT_ENCODING;

	    byte[] baInput = input.getBytes(charset);
	    byte[] encrypted = encrypt(baInput, key, algorithm, ivOrSalt, iterations);

	    return Coder.encode(encoding, encrypted);
	}
	catch (Throwable t) {
	    ExceptionUtil.rethrowIfNecessary(t);
	    throw Caster.toPageException(t);
	}
    }
959993
@Override
    public EncryptedData encrypt(byte[] plainBytes, KeyParameter aesKey) throws KeyCrypterException {
        checkNotNull(plainBytes);
        checkNotNull(aesKey);

        try {
            // Generate iv - each encryption call has a different iv.
            byte[] iv = new byte[BLOCK_LENGTH];
            secureRandom.nextBytes(iv);

            ParametersWithIV keyWithIv = new ParametersWithIV(aesKey, iv);

            // Encrypt using AES.
            BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
            cipher.init(true, keyWithIv);
            byte[] encryptedBytes = new byte[cipher.getOutputSize(plainBytes.length)];
            final int length1 = cipher.processBytes(plainBytes, 0, plainBytes.length, encryptedBytes, 0);
            final int length2 = cipher.doFinal(encryptedBytes, length1);

            return new EncryptedData(iv, Arrays.copyOf(encryptedBytes, length1 + length2));
        } catch (Exception e) {
            throw new KeyCrypterException("Could not encrypt bytes.", e);
        }
    }
893022
public static byte[] encrypt(byte[] data, byte[] key) throws InvalidCipherTextException {
        checkNotNull(data);
        checkNotNull(key);
        AESFastEngine aesEngine = new AESFastEngine();
        PaddedBufferedBlockCipher cipher =
                new PaddedBufferedBlockCipher(aesEngine, new PKCS7Padding());
        cipher.init(true, new KeyParameter(key));
        byte[] outBuf = new byte[cipher.getOutputSize(data.length)];
        int l1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
        int l2 = cipher.doFinal(outBuf, l1);
        byte[] result;
        if (outBuf.length != l1 + l2) {
            result = new byte[l1 + l2];
            System.arraycopy(outBuf, 0, result, 0, result.length);
        } else
            result = outBuf;
        return result;
    }
803551
static void E ( byte[] key, byte[] data, byte[] e ) throws ShortBufferException {
        byte[] key7 = new byte[7];
        byte[] e8 = new byte[8];

        for ( int i = 0; i < key.length / 7; i++ ) {
            System.arraycopy(key, i * 7, key7, 0, 7);
            Cipher des = Crypto.getDES(key7);
            des.update(data, 0, data.length, e8);
            System.arraycopy(e8, 0, e, i * 8, 8);
        }
    }
1194800
def encrypt(self, paddedPlaintext):
        
        # TODO: make this less ugly and python 2 and 3 compatible
        # paddedMessage = bytearray(paddedMessage.encode() if (sys.version_info >= (3, 0) and not type(paddedMessage) in (bytes, bytearray)) or type(paddedMessage) is unicode else paddedMessage)
        if (sys.version_info >= (3, 0) and
                not type(paddedPlaintext) in (bytes, bytearray)) or type(paddedPlaintext) is unicode:
            paddedPlaintext = bytearray(paddedPlaintext.encode())
        else:
            paddedPlaintext = bytearray(paddedPlaintext)
        try:
            record = self.senderKeyStore.loadSenderKey(self.senderKeyName)
            senderKeyState = record.getSenderKeyState()
            senderKey = senderKeyState.getSenderChainKey().getSenderMessageKey()
            ciphertext = self.getCipherText(senderKey.getIv(), senderKey.getCipherKey(), paddedPlaintext)

            senderKeyMessage = SenderKeyMessage(senderKeyState.getKeyId(),
                                                senderKey.getIteration(),
                                                ciphertext,
                                                senderKeyState.getSigningKeyPrivate())

            senderKeyState.setSenderChainKey(senderKeyState.getSenderChainKey().getNext())
            self.senderKeyStore.storeSenderKey(self.senderKeyName, record)

            return senderKeyMessage.serialize()
        except InvalidKeyIdException as e:
            raise NoSessionException(e)
333479
public static ByteBuf wrappedBuffer(int maxNumComponents, ByteBuffer... buffers) {
        return wrappedBuffer(maxNumComponents, CompositeByteBuf.BYTE_BUFFER_WRAPPER, buffers);
    }
1182358
public byte[] encrypt(byte[] data) {
		lock.lock();
		try {
			if (null == this.params) {
				cipher.init(Cipher.ENCRYPT_MODE, secretKey);
			} else {
				cipher.init(Cipher.ENCRYPT_MODE, secretKey, params);
			}
			return cipher.doFinal(data);
		} catch (Exception e) {
			throw new CryptoException(e);
		} finally {
			lock.unlock();
		}
	}
669517
public void ofWriteByteBuffer(ByteBuffer byteBuffer) {
		assert !isRecycled() : "Attempt to use recycled bytebuf";
		assert array == byteBuffer.array();
		assert byteBuffer.limit() == array.length;
		tail = byteBuffer.position();
	}
865119
public final ByteBuffer asByteBuffer () {

        final StringBuilder sb = new StringBuilder();
        for (Map.Entry<OperationalTextKey , String> e : settingsMap.entrySet()) {
            sb.append(e.getKey().value());
            sb.append(KEY_VALUE_DELIMITER);
            sb.append(e.getValue());
            sb.append(PAIR_DELIMITER);
        }

        return ByteBuffer.wrap(sb.toString().getBytes());
    }
560141
ByteBuffer[] writableNioBuffers(ByteBuf buf) {
    // Set the writer index to the capacity to guarantee that the returned NIO buffers will have
    // the capacity available.
    int readerIndex = buf.readerIndex();
    int writerIndex = buf.writerIndex();
    buf.readerIndex(writerIndex);
    buf.writerIndex(buf.capacity());

    try {
      return nioBuffers(buf, singleWriteBuffer);
    } finally {
      // Restore the writer index before returning.
      buf.readerIndex(readerIndex);
      buf.writerIndex(writerIndex);
    }
  }
1291963
public <V> V convertFrom(final ByteBuffer... buffers) {
        if (buffers == null || buffers.length == 0) return null;
        return (V) new AnyDecoder(factory).convertFrom(new JsonByteBufferReader((ConvertMask) null, buffers));
    }