Java Code Examples for java.io.ByteArrayInputStream.available()

The following are Jave code examples for showing how to use available() of the java.io.ByteArrayInputStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: AppCoins-ethereumj   File: ECIESCoder.java   View Source Code Vote up 6 votes
public static byte[] decrypt(BigInteger privKey, byte[] cipher, byte[] macData) throws IOException, InvalidCipherTextException {

        byte[] plaintext;

        ByteArrayInputStream is = new ByteArrayInputStream(cipher);
        byte[] ephemBytes = new byte[2*((CURVE.getCurve().getFieldSize()+7)/8) + 1];

        is.read(ephemBytes);
        ECPoint ephem = CURVE.getCurve().decodePoint(ephemBytes);
        byte[] IV = new byte[KEY_SIZE /8];
        is.read(IV);
        byte[] cipherBody = new byte[is.available()];
        is.read(cipherBody);

        plaintext = decrypt(ephem, privKey, IV, cipherBody, macData);

        return plaintext;
    }
 
Example 2
Project: Higher-Cloud-Computing-Project   File: DBcrud.java   View Source Code Vote up 6 votes
private String BlobToString(Blob blob) throws SQLException, IOException {

    String reString = "";
    InputStream is =  blob.getBinaryStream();

    ByteArrayInputStream bais = (ByteArrayInputStream)is;
    byte[] byte_data = new byte[bais.available()]; //bais.available()���ش����������ֽ���
    bais.read(byte_data, 0,byte_data.length);//���������е����ݶ���ָ��������
    reString = new String(byte_data,"utf-8"); //��תΪString����ʹ��ָ���ı��뷽ʽ
    is.close();

    return reString;
  }
 
Example 3
Project: Java8583   File: Iso8583Filed55Parser.java   View Source Code Vote up 6 votes
@Override
public TlvObject tlvParse(String data) {
	//输入流转换
	ByteArrayInputStream bais = new ByteArrayInputStream(EncodeUtil.bcd(data));
	//解析结果
	LinkedHashMap<String, TlvValue> values = new LinkedHashMap<String, TlvValue>();
	//构建结果对象
	TlvObject tlvObject = new Field55TlvObject(values);
	try{
		do{
			//依次解析
			Field55TlvValue tlvValue = read(bais);
			//放置结果
			values.put(tlvValue.getTagName(), tlvValue);
		}while(bais.available() > 0);
	}catch(IOException e){
		e.printStackTrace();
	}
	return tlvObject;
}
 
Example 4
Project: neoscada   File: StreamProcessor.java   View Source Code Vote up 6 votes
private void read () throws IOException
{
    int i;

    int offset = 0;
    final byte[] buffer = new byte[this.bufferSize];

    while ( ( i = this.stream.read ( buffer, offset, buffer.length - offset ) ) > 0 )
    {
        logger.debug ( String.format ( "Read %s bytes", i ) );

        final ByteArrayInputStream inputStream = new ByteArrayInputStream ( buffer, 0, i );
        handleNewInput ( new InputStreamReader ( inputStream ) );
        logger.debug ( String.format ( "%s byte(s) remaining", inputStream.available () ) );
        offset = inputStream.available ();

        if ( buffer.length - offset <= 0 )
        {
            throw new RuntimeException ( "Buffer is full" );
        }
    }
}
 
Example 5
Project: rskj   File: ECIESCoder.java   View Source Code Vote up 6 votes
public static byte[] decrypt(BigInteger privKey, byte[] cipher, byte[] macData) throws IOException, InvalidCipherTextException {

        byte[] plaintext;

        ByteArrayInputStream is = new ByteArrayInputStream(cipher);
        byte[] ephemBytes = new byte[2*((CURVE.getCurve().getFieldSize()+7)/8) + 1];

        is.read(ephemBytes);
        ECPoint ephem = CURVE.getCurve().decodePoint(ephemBytes);
        byte[] iv = new byte[KEY_SIZE /8];
        is.read(iv);
        byte[] cipherBody = new byte[is.available()];
        is.read(cipherBody);

        plaintext = decrypt(ephem, privKey, iv, cipherBody, macData);

        return plaintext;
    }
 
Example 6
Project: grift   File: ThriftInputStream.java   View Source Code Vote up 6 votes
@Override
public int available() throws IOException {
  if (message != null) {
    try {
      partial = new ByteArrayInputStream(serializer.serialize(message));
      message = null;
      return partial.available();
    } catch (TException e) {
      throw Status.INTERNAL.withDescription("failed to serialize thrift message")
          .withCause(e).asRuntimeException();
    }
  } else if (partial != null) {
    return partial.available();
  }
  return 0;
}
 
Example 7
Project: jdk8u-jdk   File: TestBase64.java   View Source Code Vote up 5 votes
private static void testDecoderKeepsAbstinence(Base64.Decoder dec)
        throws Throwable {
    List<Integer> vals = Arrays.asList(Integer.MIN_VALUE,
            Integer.MIN_VALUE + 1, -1111, -2, -1, 0, 1, 2, 3, 1111,
            Integer.MAX_VALUE - 1, Integer.MAX_VALUE,
            rnd.nextInt(), rnd.nextInt(), rnd.nextInt(),
            rnd.nextInt());
    byte[] buf = new byte[3];
    for (int off : vals) {
        for (int len : vals) {
            if (off >= 0 && len >= 0 && off <= buf.length - len) {
                // valid args, skip them
                continue;
            }
            // invalid args, test them
            System.out.println("testing off=" + off + ", len=" + len);

            String input = "AAAAAAAAAAAAAAAAAAAAAA";
            ByteArrayInputStream bais =
                    new ByteArrayInputStream(input.getBytes("Latin1"));
            try (InputStream is = dec.wrap(bais)) {
                is.read(buf, off, len);
                throw new RuntimeException("Expected IOOBEx was not thrown");
            } catch (IndexOutOfBoundsException expected) {
            }
            if (bais.available() != input.length())
                throw new RuntimeException("No input should be consumed, "
                        + "but consumed " + (input.length() - bais.available())
                        + " bytes");
        }
    }
}
 
Example 8
Project: PACE   File: FieldEncryptor.java   View Source Code Vote up 5 votes
/**
 * Decrypt the given entry.
 *
 * @param entry
 *          {@link MutableEntry} to encrypt.
 * @param result
 *          {@link MutableEntry} to write result to.
 * @param columnVisibility
 *          The parsed column visibility.
 *
 * @throws IOException
 *           Not actually thrown.
 */
void decrypt(MutableEntry entry, MutableEntry result, ColumnVisibility columnVisibility) throws IOException {
  ByteArrayInputStream ciphertextStream = new ByteArrayInputStream(entry.getBytes(config.destination));
  DataInput ciphertextIn = new DataInputStream(ciphertextStream);

  byte[] key = getKey(columnVisibility, ciphertextIn);
  byte[] ciphertext = new byte[ciphertextStream.available()];
  ciphertextIn.readFully(ciphertext);
  byte[] decryptedData = encryptor.decrypt(key, ciphertext);

  // Break apart the decrypted data.
  ByteArrayInputStream dataStream = new ByteArrayInputStream(decryptedData);
  DataInput dataIn = new DataInputStream(dataStream);

  for (EntryField source : config.sources) {
    switch (source) {
      case ROW:
      case COLUMN_FAMILY:
      case COLUMN_QUALIFIER:
      case COLUMN_VISIBILITY:
      case VALUE:
        int length = WritableUtils.readVInt(dataIn);
        byte[] bytes = new byte[length];
        dataIn.readFully(bytes);
        result.setBytes(source, bytes);
        break;

      // case TIMESTAMP:
      // result.timestamp = WritableUtils.readVLong(dataIn);
      // break;

      // case DELETE:
      // result.delete = dataIn.readBoolean();
      // break;

      default:
        throw new UnsupportedOperationException();
    }
  }
}
 
Example 9
Project: ipack   File: TlsProtocol.java   View Source Code Vote up 5 votes
protected static Hashtable readExtensions(ByteArrayInputStream input)
    throws IOException
{

    if (input.available() < 1)
    {
        return null;
    }

    byte[] extBytes = TlsUtils.readOpaque16(input);

    assertEmpty(input);

    ByteArrayInputStream buf = new ByteArrayInputStream(extBytes);

    // Integer -> byte[]
    Hashtable extensions = new Hashtable();

    while (buf.available() > 0)
    {
        Integer extType = Integers.valueOf(TlsUtils.readUint16(buf));
        byte[] extValue = TlsUtils.readOpaque16(buf);

        /*
         * RFC 3546 2.3 There MUST NOT be more than one extension of the same type.
         */
        if (null != extensions.put(extType, extValue))
        {
            throw new TlsFatalAlert(AlertDescription.illegal_parameter);
        }
    }

    return extensions;
}
 
Example 10
Project: openjdk-jdk10   File: AttributeClass.java   View Source Code Vote up 5 votes
/**
 * Returns array of int values.
 */
public int[] getArrayOfIntValues() {

    byte[] bufArray = (byte[])myValue;
    if (bufArray != null) {

        //ArrayList valList = new ArrayList();
        ByteArrayInputStream bufStream =
            new ByteArrayInputStream(bufArray);
        int available = bufStream.available();

        // total number of values is at the end of the stream
        bufStream.mark(available);
        bufStream.skip(available-1);
        int length = bufStream.read();
        bufStream.reset();

        int[] valueArray = new int[length];
        for (int i = 0; i < length; i++) {
            // read length
            int valLength = bufStream.read();
            if (valLength != 4) {
                // invalid data
                return null;
            }

            byte[] bufBytes = new byte[valLength];
            bufStream.read(bufBytes, 0, valLength);
            valueArray[i] = convertToInt(bufBytes);

        }
        return valueArray;
    }
    return null;
}
 
Example 11
Project: Spitfire   File: UploadFileRequest.java   View Source Code Vote up 5 votes
/**
 * Returns the raw POST or PUT body to be sent.
 *
 * <p>By default, the body consists of the request parameters in
 * application/x-www-form-urlencoded format. When overriding this method, consider overriding
 * {@link #getBodyContentType()} as well to match the new body format.
 *
 * @throws AuthFailureError in the event of auth failure
 */
@Override
public byte[] getBody() throws AuthFailureError {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);

    try {
        ByteArrayInputStream fileInputStream = new ByteArrayInputStream(getPartData().getContent());
        int bytesAvailable = fileInputStream.available();

        int maxBufferSize = 1024 * 1024;
        int bufferSize = Math.min(bytesAvailable, maxBufferSize);
        byte[] buffer = new byte[bufferSize];

        int bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        return bos.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 12
Project: openjdk-jdk10   File: TestBase64.java   View Source Code Vote up 5 votes
private static void testDecoderKeepsAbstinence(Base64.Decoder dec)
        throws Throwable {
    List<Integer> vals = new ArrayList<>(List.of(Integer.MIN_VALUE,
            Integer.MIN_VALUE + 1, -1111, -2, -1, 0, 1, 2, 3, 1111,
            Integer.MAX_VALUE - 1, Integer.MAX_VALUE));
    vals.addAll(List.of(rnd.nextInt(), rnd.nextInt(), rnd.nextInt(),
            rnd.nextInt()));
    byte[] buf = new byte[3];
    for (int off : vals) {
        for (int len : vals) {
            if (off >= 0 && len >= 0 && off <= buf.length - len) {
                // valid args, skip them
                continue;
            }
            // invalid args, test them
            System.out.println("testing off=" + off + ", len=" + len);

            String input = "AAAAAAAAAAAAAAAAAAAAAA";
            ByteArrayInputStream bais =
                    new ByteArrayInputStream(input.getBytes("Latin1"));
            try (InputStream is = dec.wrap(bais)) {
                is.read(buf, off, len);
                throw new RuntimeException("Expected IOOBEx was not thrown");
            } catch (IndexOutOfBoundsException expected) {
            }
            if (bais.available() != input.length())
                throw new RuntimeException("No input should be consumed, "
                        + "but consumed " + (input.length() - bais.available())
                        + " bytes");
        }
    }
}
 
Example 13
Project: openjdk-jdk10   File: AttributeClass.java   View Source Code Vote up 5 votes
/**
 * Returns array of String values.
 */
public String[] getArrayOfStringValues() {

    byte[] bufArray = (byte[])myValue;
    if (bufArray != null) {
        ByteArrayInputStream bufStream =
            new ByteArrayInputStream(bufArray);
        int available = bufStream.available();

        // total number of values is at the end of the stream
        bufStream.mark(available);
        bufStream.skip(available-1);
        int length = bufStream.read();
        bufStream.reset();

        String[] valueArray = new String[length];
        for (int i = 0; i < length; i++) {
            // read length
            int valLength = bufStream.read();
            byte[] bufBytes = new byte[valLength];
            bufStream.read(bufBytes, 0, valLength);
            try {
                valueArray[i] = new String(bufBytes, "UTF-8");
            } catch (java.io.UnsupportedEncodingException uee) {
            }
        }
        return valueArray;
    }
    return null;
}
 
Example 14
Project: phone-simulator   File: SmsStatusReportTpduImpl.java   View Source Code Vote up 4 votes
public SmsStatusReportTpduImpl(byte[] data, Charset gsm8Charset) throws MAPException {
    this();

    if (data == null)
        throw new MAPException("Error creating a new SmsStatusReport instance: data is empty");
    if (data.length < 1)
        throw new MAPException("Error creating a new SmsStatusReport instance: data length is equal zero");

    ByteArrayInputStream stm = new ByteArrayInputStream(data);

    int bt = stm.read();
    if ((bt & _MASK_TP_UDHI) != 0)
        this.userDataHeaderIndicator = true;
    if ((bt & _MASK_TP_MMS) == 0)
        this.moreMessagesToSend = true;
    if ((bt & _MASK_TP_LP) != 0)
        this.forwardedOrSpawned = true;
    int code = (bt & _MASK_TP_SRQ) >> 5;
    this.statusReportQualifier = StatusReportQualifier.getInstance(code);

    this.messageReference = stm.read();
    if (this.messageReference == -1)
        throw new MAPException("Error creating a new SmsStatusReport instance: messageReference field has not been found");

    this.recipientAddress = AddressFieldImpl.createMessage(stm);
    this.serviceCentreTimeStamp = AbsoluteTimeStampImpl.createMessage(stm);
    this.dischargeTime = AbsoluteTimeStampImpl.createMessage(stm);

    bt = stm.read();
    if (bt == -1)
        throw new MAPException("Error creating a new SmsStatusReport instance: Status field has not been found");
    this.status = new StatusImpl(bt);

    bt = stm.read();
    if (bt == -1)
        this.parameterIndicator = new ParameterIndicatorImpl(0);
    else
        this.parameterIndicator = new ParameterIndicatorImpl(bt);

    if (this.parameterIndicator.getTP_PIDPresence()) {
        bt = stm.read();
        if (bt == -1)
            throw new MAPException(
                    "Error creating a new SmsStatusReport instance: protocolIdentifier field has not been found");
        this.protocolIdentifier = new ProtocolIdentifierImpl(bt);
    }

    if (this.parameterIndicator.getTP_DCSPresence()) {
        bt = stm.read();
        if (bt == -1)
            throw new MAPException(
                    "Error creating a new SmsStatusReport instance: dataCodingScheme field has not been found");
        this.dataCodingScheme = new DataCodingSchemeImpl(bt);
    }

    if (this.parameterIndicator.getTP_UDLPresence()) {
        this.userDataLength = stm.read();
        if (this.userDataLength == -1)
            throw new MAPException("Error creating a new SmsStatusReport instance: userDataLength field has not been found");

        int avail = stm.available();
        byte[] buf = new byte[avail];
        try {
            stm.read(buf);
        } catch (IOException e) {
            throw new MAPException("IOException while creating a new SmsStatusReport instance: " + e.getMessage(), e);
        }
        userData = new UserDataImpl(buf, dataCodingScheme, userDataLength, userDataHeaderIndicator, gsm8Charset);
    }
}
 
Example 15
Project: phone-simulator   File: SmsDeliverReportTpduImpl.java   View Source Code Vote up 4 votes
public SmsDeliverReportTpduImpl(byte[] data, Charset gsm8Charset) throws MAPException {
    this();

    if (data == null)
        throw new MAPException("Error creating a new SmsDeliverReportTpdu instance: data is empty");
    if (data.length < 1)
        throw new MAPException("Error creating a new SmsDeliverReportTpdu instance: data length is equal zero");

    ByteArrayInputStream stm = new ByteArrayInputStream(data);

    int bt = stm.read();
    if ((bt & _MASK_TP_UDHI) != 0)
        this.userDataHeaderIndicator = true;

    bt = stm.read();
    if (bt == -1)
        throw new MAPException(
                "Error creating a new SmsDeliverReportTpdu instance: Failure-Cause and Parameter-Indicator fields have not been found");
    if ((bt & 0x80) != 0) {
        // Failure-Cause exists
        this.failureCause = new FailureCauseImpl(bt);

        bt = stm.read();
        if (bt == -1)
            throw new MAPException(
                    "Error creating a new SmsDeliverReportTpdu instance: Parameter-Indicator field has not been found");
    }

    this.parameterIndicator = new ParameterIndicatorImpl(bt);

    if (this.parameterIndicator.getTP_PIDPresence()) {
        bt = stm.read();
        if (bt == -1)
            throw new MAPException(
                    "Error creating a new SmsDeliverTpduImpl instance: protocolIdentifier field has not been found");
        this.protocolIdentifier = new ProtocolIdentifierImpl(bt);
    }

    if (this.parameterIndicator.getTP_DCSPresence()) {
        bt = stm.read();
        if (bt == -1)
            throw new MAPException(
                    "Error creating a new SmsDeliverTpduImpl instance: dataCodingScheme field has not been found");
        this.dataCodingScheme = new DataCodingSchemeImpl(bt);
    }

    if (this.parameterIndicator.getTP_UDLPresence()) {
        this.userDataLength = stm.read();
        if (this.userDataLength == -1)
            throw new MAPException(
                    "Error creating a new SmsDeliverTpduImpl instance: userDataLength field has not been found");

        int avail = stm.available();
        byte[] buf = new byte[avail];
        try {
            stm.read(buf);
        } catch (IOException e) {
            throw new MAPException("IOException while creating a new SmsDeliverTpduImpl instance: " + e.getMessage(), e);
        }
        userData = new UserDataImpl(buf, dataCodingScheme, userDataLength, userDataHeaderIndicator, gsm8Charset);
    }
}
 
Example 16
Project: phone-simulator   File: SmsDeliverTpduImpl.java   View Source Code Vote up 4 votes
public SmsDeliverTpduImpl(byte[] data, Charset gsm8Charset) throws MAPException {
    this();

    if (data == null)
        throw new MAPException("Error creating a new SmsDeliverTpduImpl instance: data is empty");
    if (data.length < 1)
        throw new MAPException("Error creating a new SmsDeliverTpduImpl instance: data length is equal zero");

    ByteArrayInputStream stm = new ByteArrayInputStream(data);

    int bt = stm.read();
    if ((bt & _MASK_TP_MMS) == 0)
        this.moreMessagesToSend = true;
    if ((bt & _MASK_TP_LP) != 0)
        this.forwardedOrSpawned = true;
    if ((bt & _MASK_TP_RP) != 0)
        this.replyPathExists = true;
    if ((bt & _MASK_TP_UDHI) != 0)
        this.userDataHeaderIndicator = true;
    if ((bt & _MASK_TP_SRI) != 0)
        this.statusReportIndication = true;

    this.originatingAddress = AddressFieldImpl.createMessage(stm);

    bt = stm.read();
    if (bt == -1)
        throw new MAPException(
                "Error creating a new SmsDeliverTpduImpl instance: protocolIdentifier field has not been found");
    this.protocolIdentifier = new ProtocolIdentifierImpl(bt);

    bt = stm.read();
    if (bt == -1)
        throw new MAPException(
                "Error creating a new SmsDeliverTpduImpl instance: dataCodingScheme field has not been found");
    this.dataCodingScheme = new DataCodingSchemeImpl(bt);

    this.serviceCentreTimeStamp = AbsoluteTimeStampImpl.createMessage(stm);

    this.userDataLength = stm.read();
    if (this.userDataLength == -1)
        throw new MAPException("Error creating a new SmsDeliverTpduImpl instance: userDataLength field has not been found");

    int avail = stm.available();
    byte[] buf = new byte[avail];
    try {
        stm.read(buf);
    } catch (IOException e) {
        throw new MAPException("IOException while creating a new SmsDeliverTpduImpl instance: " + e.getMessage(), e);
    }
    userData = new UserDataImpl(buf, dataCodingScheme, userDataLength, userDataHeaderIndicator, gsm8Charset);
}
 
Example 17
Project: creacoinj   File: Script.java   View Source Code Vote up 4 votes
/**
 * <p>To run a script, first we parse it which breaks it up into chunks representing pushes of data or logical
 * opcodes. Then we can run the parsed chunks.</p>
 *
 * <p>The reason for this split, instead of just interpreting directly, is to make it easier
 * to reach into a programs structure and pull out bits of data without having to run it.
 * This is necessary to render the to/from addresses of transactions in a user interface.
 * Bitcoin Core does something similar.</p>
 */
private void parse(byte[] program) throws ScriptException {
    chunks = new ArrayList<>(5);   // Common size.
    ByteArrayInputStream bis = new ByteArrayInputStream(program);
    int initialSize = bis.available();
    while (bis.available() > 0) {
        int startLocationInProgram = initialSize - bis.available();
        int opcode = bis.read();

        long dataToRead = -1;
        if (opcode >= 0 && opcode < OP_PUSHDATA1) {
            // Read some bytes of data, where how many is the opcode value itself.
            dataToRead = opcode;
        } else if (opcode == OP_PUSHDATA1) {
            if (bis.available() < 1) throw new ScriptException("Unexpected end of script");
            dataToRead = bis.read();
        } else if (opcode == OP_PUSHDATA2) {
            // Read a short, then read that many bytes of data.
            if (bis.available() < 2) throw new ScriptException("Unexpected end of script");
            dataToRead = bis.read() | (bis.read() << 8);
        } else if (opcode == OP_PUSHDATA4) {
            // Read a uint32, then read that many bytes of data.
            // Though this is allowed, because its value cannot be > 520, it should never actually be used
            if (bis.available() < 4) throw new ScriptException("Unexpected end of script");
            dataToRead = ((long)bis.read()) | (((long)bis.read()) << 8) | (((long)bis.read()) << 16) | (((long)bis.read()) << 24);
        }

        ScriptChunk chunk;
        if (dataToRead == -1) {
            chunk = new ScriptChunk(opcode, null, startLocationInProgram);
        } else {
            if (dataToRead > bis.available())
                throw new ScriptException("Push of data element that is larger than remaining data");
            byte[] data = new byte[(int)dataToRead];
            checkState(dataToRead == 0 || bis.read(data, 0, (int)dataToRead) == dataToRead);
            chunk = new ScriptChunk(opcode, data, startLocationInProgram);
        }
        // Save some memory by eliminating redundant copies of the same chunk objects.
        for (ScriptChunk c : STANDARD_TRANSACTION_SCRIPT_CHUNKS) {
            if (c.equals(chunk)) chunk = c;
        }
        chunks.add(chunk);
    }
}
 
Example 18
Project: MetadataEditor   File: ID3Unsynchronization.java   View Source Code Vote up 4 votes
/**
 * Unsynchronize an array of bytes, this should only be called if the decision has already been made to
 * unsynchronize the byte array
 *
 * In order to prevent a media player from incorrectly interpreting the contents of a tag, all $FF bytes
 * followed by a byte with value >=224 must be followed by a $00 byte (thus, $FF $F0 sequences become $FF $00 $F0).
 * Additionally because unsynchronisation is being applied any existing $FF $00 have to be converted to
 * $FF $00 $00
 *
 * @param abySource a byte array to be unsynchronized
 * @return a unsynchronized representation of the source
 */
public static byte[] unsynchronize(byte[] abySource)
{
    ByteArrayInputStream input = new ByteArrayInputStream(abySource);
    ByteArrayOutputStream output = new ByteArrayOutputStream(abySource.length);

    int count = 0;
    while (input.available() > 0)
    {
        int firstByte = input.read();
        count++;
        output.write(firstByte);
        if ((firstByte & MPEGFrameHeader.SYNC_BYTE1) == MPEGFrameHeader.SYNC_BYTE1)
        {
            // if byte is $FF, we must check the following byte if there is one
            if (input.available() > 0)
            {
                input.mark(1);  // remember where we were, if we don't need to unsynchronize
                int secondByte = input.read();
                if ((secondByte & MPEGFrameHeader.SYNC_BYTE2) == MPEGFrameHeader.SYNC_BYTE2)
                {
                    // we need to unsynchronize here
                    if (logger.isLoggable(Level.FINEST))
                    {
                        logger.finest("Writing unsynchronisation bit at:" + count);
                    }
                    output.write(0);

                }
                else if (secondByte == 0)
                {
                    // we need to unsynchronize here
                    if (logger.isLoggable(Level.FINEST))
                    {
                        logger.finest("Inserting zero unsynchronisation bit at:" + count);
                    }
                    output.write(0);
                }
                input.reset();
            }
        }
    }
    // if we needed to unsynchronize anything, and this tag ends with 0xff, we have to append a zero byte,
    // which will be removed on de-unsynchronization later
    if ((abySource[abySource.length - 1] & MPEGFrameHeader.SYNC_BYTE1) == MPEGFrameHeader.SYNC_BYTE1)
    {
        logger.finest("Adding unsynchronisation bit at end of stream");
        output.write(0);
    }
    return output.toByteArray();
}
 
Example 19
Project: ipack   File: IESEngine.java   View Source Code Vote up 4 votes
public byte[] processBlock(
    byte[] in,
    int inOff,
    int inLen)
    throws InvalidCipherTextException
{
    if (forEncryption)
    {
        if (keyPairGenerator != null)
        {
            EphemeralKeyPair ephKeyPair = keyPairGenerator.generate();

            this.privParam = ephKeyPair.getKeyPair().getPrivate();
            this.V = ephKeyPair.getEncodedPublicKey();
        }
    }
    else
    {
        if (keyParser != null)
        {
            ByteArrayInputStream bIn = new ByteArrayInputStream(in, inOff, inLen);

            try
            {
                this.pubParam = keyParser.readKey(bIn);
            }
            catch (IOException e)
            {
                throw new InvalidCipherTextException("unable to recover ephemeral public key: " + e.getMessage(), e);
            }

            int encLength = (inLen - bIn.available());
            this.V = Arrays.copyOfRange(in, inOff, inOff + encLength);
        }
    }

    // Compute the common value and convert to byte array. 
    agree.init(privParam);
    BigInteger z = agree.calculateAgreement(pubParam);
    byte[] Z = BigIntegers.asUnsignedByteArray(agree.getFieldSize(), z);

    // Create input to KDF.  
    byte[] VZ;
    if (V.length != 0)
    {
        VZ = new byte[V.length + Z.length];
        System.arraycopy(V, 0, VZ, 0, V.length);
        System.arraycopy(Z, 0, VZ, V.length, Z.length);
    }
    else
    {
        VZ = Z;
    }

    // Initialise the KDF.
    KDFParameters kdfParam = new KDFParameters(VZ, param.getDerivationV());
    kdf.init(kdfParam);

    return forEncryption
        ? encryptBlock(in, inOff, inLen)
        : decryptBlock(in, inOff, inLen);
}
 
Example 20
Project: okwallet   File: Script.java   View Source Code Vote up 4 votes
/**
 * <p>To run a script, first we parse it which breaks it up into chunks representing pushes of data or logical
 * opcodes. Then we can run the parsed chunks.</p>
 *
 * <p>The reason for this split, instead of just interpreting directly, is to make it easier
 * to reach into a programs structure and pull out bits of data without having to run it.
 * This is necessary to render the to/from addresses of transactions in a user interface.
 * Bitcoin Core does something similar.</p>
 */
private void parse(byte[] program) throws ScriptException {
    chunks = new ArrayList<>(5);   // Common size.
    ByteArrayInputStream bis = new ByteArrayInputStream(program);
    int initialSize = bis.available();
    while (bis.available() > 0) {
        int startLocationInProgram = initialSize - bis.available();
        int opcode = bis.read();

        long dataToRead = -1;
        if (opcode >= 0 && opcode < OP_PUSHDATA1) {
            // Read some bytes of data, where how many is the opcode value itself.
            dataToRead = opcode;
        } else if (opcode == OP_PUSHDATA1) {
            if (bis.available() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Unexpected end of script");
            dataToRead = bis.read();
        } else if (opcode == OP_PUSHDATA2) {
            // Read a short, then read that many bytes of data.
            if (bis.available() < 2) throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Unexpected end of script");
            dataToRead = bis.read() | (bis.read() << 8);
        } else if (opcode == OP_PUSHDATA4) {
            // Read a uint32, then read that many bytes of data.
            // Though this is allowed, because its value cannot be > 520, it should never actually be used
            if (bis.available() < 4) throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Unexpected end of script");
            dataToRead = ((long)bis.read()) | (((long)bis.read()) << 8) | (((long)bis.read()) << 16) | (((long)bis.read()) << 24);
        }

        ScriptChunk chunk;
        if (dataToRead == -1) {
            chunk = new ScriptChunk(opcode, null, startLocationInProgram);
        } else {
            if (dataToRead > bis.available())
                throw new ScriptException(ScriptError.SCRIPT_ERR_BAD_OPCODE, "Push of data element that is larger than remaining data");
            byte[] data = new byte[(int)dataToRead];
            checkState(dataToRead == 0 || bis.read(data, 0, (int)dataToRead) == dataToRead);
            chunk = new ScriptChunk(opcode, data, startLocationInProgram);
        }
        // Save some memory by eliminating redundant copies of the same chunk objects.
        for (ScriptChunk c : STANDARD_TRANSACTION_SCRIPT_CHUNKS) {
            if (c.equals(chunk)) chunk = c;
        }
        chunks.add(chunk);
    }
}