Java Code Examples for com.google.common.primitives.Bytes#concat()

The following examples show how to use com.google.common.primitives.Bytes#concat() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ZCashTransaction_taddr.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private byte[] getSignedInputBytes(int index) throws ZCashException {
  Tx_in input = inputs.get(index);
  byte[] sign = Bytes.concat(getInputSignature(input), new byte[]{1});
  byte[] pubKey = privKey.getPubKeyPoint().getEncoded(true);
  return Bytes.concat(
    input.txid,
    Utils.int32BytesLE(input.index),
    Utils.compactSizeIntLE(sign.length + pubKey.length + Utils.compactSizeIntLE(sign.length).length + Utils.compactSizeIntLE(pubKey.length).length),
    Utils.compactSizeIntLE(sign.length),
    sign,
    Utils.compactSizeIntLE(pubKey.length),
    pubKey,
    Utils.int32BytesLE(input.sequence)
  );
}
 
Example 2
Source File: SizeExtraFieldTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
void parseFromCentralDirectoryDataShouldHandleOffset() throws Exception {
    byte[] input = Bytes.concat(UNUSED, _123456789ABCDEF0_AS_LE_BYTE_ARRAY);
    testee.parseFromCentralDirectoryData(input, 2, 8);
    assertThat(testee.getValue())
        .contains(0x123456789ABCDEF0L);
}
 
Example 3
Source File: Psnp.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] asBytes() {
    byte[] psnpMessage = null;
    byte[] isisPduHeader = isisPduHeader();
    byte[] psnpBody = partialSequenceNumberPduBody();
    psnpMessage = Bytes.concat(isisPduHeader, psnpBody);
    return psnpMessage;
}
 
Example 4
Source File: UnknownLinkSubType.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Returns instance as byte array.
 *
 * @return instance as byte array
 */
public byte[] asBytes() {
    byte[] linkSubType = null;

    byte[] linkSubTlvHeader = getTlvHeaderAsByteArray();
    byte[] linkSubTlvBody = getLinkSubTypeTlvBodyAsByteArray();
    linkSubType = Bytes.concat(linkSubTlvHeader, linkSubTlvBody);
    return linkSubType;

}
 
Example 5
Source File: LedgerUtils.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
public static byte[] compressedLedgerPubkey(byte[] pubkey) {
    if (pubkey.length != 65) {
        return null;
    }
    byte[] result = new byte[1];
    BigInteger bigX = new BigInteger(Arrays.copyOfRange(pubkey, 1, 33));
    BigInteger bigY = new BigInteger(Arrays.copyOfRange(pubkey, 33, 65));

    result[0] = (byte) 0x2;
    if (bigY.toByteArray()[0] % 2 != 0) {
        result[0] = (byte) (result[0] | 0x1);
    }
    return Bytes.concat(result, bigX.toByteArray());
}
 
Example 6
Source File: SeqGraph.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static SeqVertex mergeLinearChainVertices(final Iterable<SeqVertex> vertices) {
    final List<byte[]> seqs = new LinkedList<>();
    for ( final SeqVertex v : vertices ) {
        seqs.add(v.getSequence());
    }
    final byte[] seqsCat = Bytes.concat(seqs.toArray(new byte[][]{}));
    return new SeqVertex( seqsCat );
}
 
Example 7
Source File: HIDSetReport.java    From boogie-board-sync-sdk-android with MIT License 5 votes vote down vote up
/**
 * Returns a byte array that has the CRC computed and is properly framed to be sent to a HID device.
 * @return byte[]
 */
public byte[] getPacketBytes() {
    // Create the initial packet without the payload.
    // NOTE: For our implementation we need to repeat the report id and then add a zero-byte.
    byte[] initialBytes = new byte[]{getChannel(), mHeader, mSetReportId, mSetReportId, 0x00 };

    // Add the packet.
    byte[] packet = Bytes.concat(initialBytes, mPayload);

    return HIDUtilities.framePacket(packet);
}
 
Example 8
Source File: IsisMessageDecoderTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecode() throws Exception {
    channel = EasyMock.createMock(Channel.class);
    socketAddress = InetSocketAddress.createUnresolved(id, 7000);
    byte[] array = IsisUtil.getPaddingTlvs(hello.length - 17);
    array1 = Bytes.concat(hello, array);
    channelBuffer = ChannelBuffers.copiedBuffer(Bytes.concat(hello, array));
    assertThat(isisMessageDecoder.decode(ctx, channel, channelBuffer), is(nullValue()));
}
 
Example 9
Source File: UpdateNameTransaction.java    From Qora with MIT License 5 votes vote down vote up
@Override
public byte[] toBytes() 
{
	byte[] data = new byte[0];
	
	//WRITE TYPE
	byte[] typeBytes = Ints.toByteArray(UPDATE_NAME_TRANSACTION);
	typeBytes = Bytes.ensureCapacity(typeBytes, TYPE_LENGTH, 0);
	data = Bytes.concat(data, typeBytes);
	
	//WRITE TIMESTAMP
	byte[] timestampBytes = Longs.toByteArray(this.timestamp);
	timestampBytes = Bytes.ensureCapacity(timestampBytes, TIMESTAMP_LENGTH, 0);
	data = Bytes.concat(data, timestampBytes);
	
	//WRITE REFERENCE
	data = Bytes.concat(data, this.reference);
	
	//WRITE OWNER
	data = Bytes.concat(data, this.owner.getPublicKey());
	
	//WRITE NAME
	data = Bytes.concat(data , this.name.toBytes());
	
	//WRITE FEE
	byte[] feeBytes = this.fee.unscaledValue().toByteArray();
	byte[] fill = new byte[FEE_LENGTH - feeBytes.length];
	feeBytes = Bytes.concat(fill, feeBytes);
	data = Bytes.concat(data, feeBytes);

	//SIGNATURE
	data = Bytes.concat(data, this.signature);
	
	return data;
}
 
Example 10
Source File: CanaryFactory.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a "canary" class to a secondary dex that can be safely loaded on any system. This avoids
 * an issue where, during secondary dex loading, we attempt to verify a secondary dex by loading
 * an arbitrary class, but the class we try to load isn't valid on that system (e.g., it depends
 * on Google Maps, but we are on AOSP).
 *
 * @param store dex store name of the current zip (to ensure unique names).
 * @param index Index of the current zip (to ensure unique names).
 */
public static FileLike create(String store, String index) {
  String className = String.format(CANARY_PATH_FORMAT, store, index);
  byte[] classNameBytes = className.getBytes(Charsets.UTF_8);
  // See above comment regarding CONSTANT_Utf8_info
  byte[] stringInfo = new byte[3];
  stringInfo[0] = (byte) 0x01;
  stringInfo[1] = (byte) ((classNameBytes.length & 0x0000FF00) >> 8);
  stringInfo[2] = (byte) (classNameBytes.length & 0x000000FF);

  byte[] canaryClass = Bytes.concat(CANARY_START, stringInfo, classNameBytes, CANARY_REMAINDER);

  String classFilePath = className + ".class";
  return getCanaryClass(classFilePath, canaryClass);
}
 
Example 11
Source File: ArbitraryTransaction.java    From Qora with MIT License 5 votes vote down vote up
@Override
public boolean isSignatureValid() 
{
	byte[] data = new byte[0];
	
	//WRITE TYPE
	byte[] typeBytes = Ints.toByteArray(ARBITRARY_TRANSACTION);
	typeBytes = Bytes.ensureCapacity(typeBytes, TYPE_LENGTH, 0);
	data = Bytes.concat(data, typeBytes);
	
	//WRITE TIMESTAMP
	byte[] timestampBytes = Longs.toByteArray(this.timestamp);
	timestampBytes = Bytes.ensureCapacity(timestampBytes, TIMESTAMP_LENGTH, 0);
	data = Bytes.concat(data, timestampBytes);
	
	//WRITE REFERENCE
	data = Bytes.concat(data, this.reference);
	
	//WRITE CREATOR
	data = Bytes.concat(data, this.creator.getPublicKey());
	
	//WRITE SERVICE
	byte[] serviceBytes = Ints.toByteArray(this.service);
	data = Bytes.concat(data, serviceBytes);
	
	//WRITE DATA SIZE
	byte[] dataSizeBytes = Ints.toByteArray(this.data.length);
	data = Bytes.concat(data, dataSizeBytes);
	
	//WRITE DATA
	data = Bytes.concat(data, this.data);
	
	//WRITE FEE
	byte[] feeBytes = this.fee.unscaledValue().toByteArray();
	byte[] fill = new byte[FEE_LENGTH - feeBytes.length];
	feeBytes = Bytes.concat(fill, feeBytes);
	data = Bytes.concat(data, feeBytes);
	
	return Crypto.getInstance().verify(this.creator.getPublicKey(), this.signature, data);
}
 
Example 12
Source File: TransferAssetTransaction.java    From Qora with MIT License 4 votes vote down vote up
public static byte[] generateSignature(DBSet db, PrivateKeyAccount sender, Account recipient, long key, BigDecimal amount, BigDecimal fee, long timestamp) 
{
	byte[] data = new byte[0];
	
	//WRITE TYPE
	byte[] typeBytes = Ints.toByteArray(TRANSFER_ASSET_TRANSACTION);
	typeBytes = Bytes.ensureCapacity(typeBytes, TYPE_LENGTH, 0);
	data = Bytes.concat(data, typeBytes);
	
	//WRITE TIMESTAMP
	byte[] timestampBytes = Longs.toByteArray(timestamp);
	timestampBytes = Bytes.ensureCapacity(timestampBytes, TIMESTAMP_LENGTH, 0);
	data = Bytes.concat(data, timestampBytes);
	
	//WRITE REFERENCE
	data = Bytes.concat(data, sender.getLastReference(db));
	
	//WRITE SENDER
	data = Bytes.concat(data , sender.getPublicKey());
	
	//WRITE RECIPIENT
	data = Bytes.concat(data, Base58.decode(recipient.getAddress()));
	
	//WRITE KEY
	byte[] keyBytes = Longs.toByteArray(key);
	keyBytes = Bytes.ensureCapacity(keyBytes, KEY_LENGTH, 0);
	data = Bytes.concat(data, keyBytes);
	
	//WRITE AMOUNT
	byte[] amountBytes = amount.unscaledValue().toByteArray();
	byte[] fill = new byte[AMOUNT_LENGTH - amountBytes.length];
	amountBytes = Bytes.concat(fill, amountBytes);
	data = Bytes.concat(data, amountBytes);
	
	//WRITE FEE
	byte[] feeBytes = fee.unscaledValue().toByteArray();
	fill = new byte[FEE_LENGTH - feeBytes.length];
	feeBytes = Bytes.concat(fill, feeBytes);
	data = Bytes.concat(data, feeBytes);
	
	//SIGN
	return Crypto.getInstance().sign(sender, data);
}
 
Example 13
Source File: Block.java    From Qora with MIT License 4 votes vote down vote up
public boolean isSignatureValid()
{
	//VALIDATE BLOCK SIGNATURE
	byte[] data = new byte[0];
	
	//WRITE PARENT GENERATOR SIGNATURE
	byte[] generatorSignature = Arrays.copyOfRange(this.reference, 0, GENERATOR_SIGNATURE_LENGTH);
	data = Bytes.concat(data, generatorSignature);
	
	//WRITE GENERATING BALANCE
	byte[] baseTargetBytes = Longs.toByteArray(this.generatingBalance);
	data = Bytes.concat(data, baseTargetBytes);
	
	//WRITE GENERATOR
	byte[] generatorBytes = Bytes.ensureCapacity(this.generator.getPublicKey(), GENERATOR_LENGTH, 0);
	data = Bytes.concat(data, generatorBytes);
							
	if(!Crypto.getInstance().verify(this.generator.getPublicKey(), this.generatorSignature, data))
	{
		return false;
	}
	
	//VALIDATE TRANSACTIONS SIGNATURE
	data = this.generatorSignature;		
	for(Transaction transaction: this.getTransactions())
	{
		//CHECK IF TRANSACTION SIGNATURE IS VALID
		if(!transaction.isSignatureValid())
		{
			return false;
		}
		
		//ADD SIGNATURE TO DATA
		data = Bytes.concat(data, transaction.getSignature());
	}
	
	if(!Crypto.getInstance().verify(this.generator.getPublicKey(), this.transactionsSignature, data))
	{
		return false;
	}
	
	return true;
}
 
Example 14
Source File: S1Flasher.java    From Flashtool with GNU General Public License v3.0 4 votes vote down vote up
public void BackupTA(int partition, String timeStamp) throws IOException, X10FlashException {
	openTA(partition);
	String folder = OS.getFolderRegisteredDevices()+File.separator+getPhoneProperty("MSN")+File.separator+"s1ta"+File.separator+timeStamp;
	new File(folder).mkdirs();
	TextFile tazone = new TextFile(folder+File.separator+partition+".ta","ISO8859-1");
	tazone.open(false);
	try {
  tazone.writeln(HexDump.toHex((byte)partition));
  try {
  	logger.info("Start Dumping TA partition "+partition);
  	cmd.send(S1Command.CMD18, S1Command.VALNULL, false);
  	if (cmd.getLastReply().getDataLength()>0) {
  	logger.info("Finished Dumping TA partition "+partition);
  	ByteArrayInputStream inputStream = new ByteArrayInputStream(cmd.getLastReply().getDataArray());
  	TreeMap<Integer, byte[]> treeMap = new  TreeMap<Integer, byte[]>();
  	int i = 0;
  	while(i == 0) {
  		int j = inputStream.read();
  		if (j == -1) {
  			i = 1;
  		}
  		else {
  			byte[] buff = new byte[3];
  			if(Streams.readFully(inputStream, buff)!=3){
  				throw new X10FlashException("Not enough data to read Uint32 when decoding command");
  			}
  			
  			byte[] unitbuff = Bytes.concat(new byte[] { (byte)j }, buff);
  			long unit = ByteBuffer.wrap(unitbuff).getInt() & 0xFFFFFFFF;
  			long unitdatalen = decodeUint32(inputStream);
  			if (unitdatalen > 1000000L) {
  				throw new X10FlashException("Maximum unit size exceeded, application will handle units of a maximum size of 0x"
  			              + Long.toHexString(1000000L) + ". Got a unit of size 0x" + Long.toHexString(unitdatalen) + ".");
  			}
  			byte[] databuff = new byte[(int)unitdatalen];
  			if (Streams.readFully(inputStream, databuff) != unitdatalen) {
  				throw new X10FlashException("Not enough data to read unit data decoding command");
  			}
       	treeMap.put((int)unit, databuff);
  		}
  	}
  	for (Map.Entry<Integer, byte[]> entry : treeMap.entrySet())
  	{
  		TAUnit tau = new TAUnit(entry.getKey(), entry.getValue());
  		if (tau.getUnitNumber()>0)
  			tazone.write(tau.toString());
  	    if (treeMap.lastEntry().getKey()!=entry.getKey()) tazone.write("\n");
  	}
      tazone.close();
      logger.info("TA partition "+partition+" saved to "+folder+File.separator+partition+".ta");
  	} else {
   	logger.warn("This partition is not readable");
   }
      closeTA();
  } catch (X10FlashException e) {
  	closeTA();
  	throw e;
  }
 }
	catch (Exception ioe) {
     tazone.close();
     closeTA();
		logger.error(ioe.getMessage());
		logger.error("Error dumping TA. Aborted");
	}
}
 
Example 15
Source File: ZCashTransaction_taddr.java    From guarda-android-wallets with GNU General Public License v3.0 4 votes vote down vote up
byte[] getBytes() {
  return Bytes.concat(Utils.int64BytesLE(value), Utils.compactSizeIntLE(script.length), script);
}
 
Example 16
Source File: RyaTypeResolverImpl.java    From rya with Apache License 2.0 4 votes vote down vote up
@Override
public byte[] serialize(final RyaType ryaType) throws RyaTypeResolverException {
    final byte[][] bytes = serializeType(ryaType);
    return Bytes.concat(bytes[0], bytes[1]);
}
 
Example 17
Source File: VoteOnPollTransaction.java    From Qora with MIT License 4 votes vote down vote up
@Override
public byte[] toBytes() 
{
	byte[] data = new byte[0];
	
	//WRITE TYPE
	byte[] typeBytes = Ints.toByteArray(VOTE_ON_POLL_TRANSACTION);
	typeBytes = Bytes.ensureCapacity(typeBytes, TYPE_LENGTH, 0);
	data = Bytes.concat(data, typeBytes);
	
	//WRITE TIMESTAMP
	byte[] timestampBytes = Longs.toByteArray(this.timestamp);
	timestampBytes = Bytes.ensureCapacity(timestampBytes, TIMESTAMP_LENGTH, 0);
	data = Bytes.concat(data, timestampBytes);
	
	//WRITE REFERENCE
	data = Bytes.concat(data, this.reference);
	
	//WRITE CREATOR
	data = Bytes.concat(data, this.creator.getPublicKey());
	
	//WRITE POLL SIZE
	byte[] pollBytes = this.poll.getBytes(StandardCharsets.UTF_8);
	int pollLength = pollBytes.length;
	byte[] pollLengthBytes = Ints.toByteArray(pollLength);
	data = Bytes.concat(data, pollLengthBytes);
			
	//WRITE NAME
	data = Bytes.concat(data, pollBytes);
	
	//WRITE OPTION
	byte[] optionBytes = Ints.toByteArray(this.option);
	optionBytes = Bytes.ensureCapacity(optionBytes, OPTION_SIZE_LENGTH, 0);
	data = Bytes.concat(data, optionBytes);
	
	//WRITE FEE
	byte[] feeBytes = this.fee.unscaledValue().toByteArray();
	byte[] fill = new byte[FEE_LENGTH - feeBytes.length];
	feeBytes = Bytes.concat(fill, feeBytes);
	data = Bytes.concat(data, feeBytes);

	//SIGNATURE
	data = Bytes.concat(data, this.signature);
	
	return data;
}
 
Example 18
Source File: FixStreamMessageParserPermutationsTest.java    From nanofix with Apache License 2.0 4 votes vote down vote up
@Test
public void messageBoundaryConditions() throws Exception
{
    final byte[] msgBytes = Bytes.concat(MESSAGE_1, MESSAGE_2, MESSAGE_3);
    final ByteBuffer bb = ByteBuffer.wrap(msgBytes);
    final List<byte[]> messages = asList(MESSAGE_1, MESSAGE_2, MESSAGE_3);

    final String wholeString = FixMessageUtil.convertFixControlCharacters(msgBytes);
    final int startOfFirstMessage = 0;
    final int offsetOfFirstMessageChecksum = wholeString.indexOf("|10=");
    final int offsetOfSecondMessageChecksum = wholeString.indexOf("|10=", offsetOfFirstMessageChecksum + 1);
    final int offsetOfLastMessageChecksum = wholeString.indexOf("|10=", offsetOfSecondMessageChecksum + 1);

    for (int i = 1; i <= 6; i++) // possible fragmentations of "8=FIX." prefix of message 1
    {
        for (int j = 1; j <= 15; j++) // possible fragmentations of "|10=067|8=FIX." block between messages 1 and 2
        {
            for (int k = 1; k <= 15; k++) // possible fragmentations of "|10=067|8=FIX." block between messages 2 and 3
            {
                for (int l = 1; l <= 9; l++) // possible fragmentations of "|10=067|" suffix of message 3
                {
                    final int consumeFromStart = i;
                    final int consumeFromBoundaryMsg1Msg2 = j;
                    final int consumeFromBoundaryMsg2Msg3 = k;
                    final int consumeFromMsg3Checksum = l;
                    performIteration(bb, messages, new BytesToConsumeCalculator()
                    {
                        @Override
                        public int getBytesToConsume(final int fromPosition)
                        {
                            if (fromPosition == startOfFirstMessage)
                            {
                                return consumeFromStart;
                            }
                            if (fromPosition < offsetOfFirstMessageChecksum)
                            {
                                return offsetOfFirstMessageChecksum - fromPosition + consumeFromBoundaryMsg1Msg2;
                            }
                            if (fromPosition < offsetOfSecondMessageChecksum)
                            {
                                return offsetOfSecondMessageChecksum - fromPosition + consumeFromBoundaryMsg2Msg3;
                            }
                            if (fromPosition < offsetOfLastMessageChecksum)
                            {
                                return offsetOfLastMessageChecksum - fromPosition + consumeFromMsg3Checksum;
                            }
                            return wholeString.length() - fromPosition;
                        }
                    });
                }
            }
        }
    }
}
 
Example 19
Source File: GCMEncryptor.java    From keywhiz with Apache License 2.0 4 votes vote down vote up
public synchronized byte[] encrypt(byte[] plaintext) throws AEADBadTagException {
  byte[] nonce = new byte[NONCE_LENGTH];
  secureRandom.nextBytes(nonce);

  return Bytes.concat(nonce, gcm(ENCRYPT, plaintext, nonce));
}
 
Example 20
Source File: ZCashTransaction_taddr.java    From guarda-android-wallets with GNU General Public License v3.0 4 votes vote down vote up
Tx_out(byte[] pubKeyHash, long value) {
  this.value = value;
  script = Bytes.concat(new byte[]{(byte) 0x76, (byte) 0xa9, (byte) 0x14}, pubKeyHash, new byte[]{(byte) 0x88, (byte) 0xac});
  //                                OP_DUP       OP_HASH160  20_bytes     <PubkeyHash>           OP_EQUALVERIFY OP_CHECKSIG
}