List of usage examples for io.netty.buffer ByteBuf arrayOffset
public abstract int arrayOffset();
From source file:divconq.pgp.PGPUtil.java
License:Open Source License
static public void encryptFile(String outputFileName, String inputFileName, String encKeyFileName) throws IOException, NoSuchProviderException, PGPException { Path fileIn = Paths.get(inputFileName); Path fileOut = Paths.get(outputFileName); Path fileKey = Paths.get(encKeyFileName); OutputStream out = new BufferedOutputStream(new FileOutputStream(fileOut.toFile())); try {/* w w w . ja v a 2 s. co m*/ EncryptedFileStream pw = new EncryptedFileStream(); //pw.setAlgorithm(SymmetricKeyAlgorithmTags.NULL); pw.setFileName(fileIn.getFileName().toString()); pw.loadPublicKey(fileKey); pw.init(); FileInputStream in = new FileInputStream(fileIn.toFile()); byte[] ibuf = new byte[31 * 1024]; int len; while ((len = in.read(ibuf)) > 0) { pw.writeData(ibuf, 0, len); ByteBuf buf = pw.nextReadyBuffer(); while (buf != null) { out.write(buf.array(), buf.arrayOffset(), buf.readableBytes()); buf.release(); buf = pw.nextReadyBuffer(); } } in.close(); pw.close(); ByteBuf buf = pw.nextReadyBuffer(); while (buf != null) { out.write(buf.array(), buf.arrayOffset(), buf.readableBytes()); buf.release(); buf = pw.nextReadyBuffer(); } out.close(); } catch (Exception e) { System.err.println(e); e.printStackTrace(); } }
From source file:divconq.struct.CompositeStruct.java
License:Open Source License
public void toSerialMemory(Memory res) throws BuilderStateException { ByteBuf buf = Hub.instance.getBufferAllocator().heapBuffer(16 * 1024, 16 * 1024 * 1024); CompositeToBufferBuilder rb = new CompositeToBufferBuilder(buf); this.toBuilder(rb); rb.write(Special.End);//from w w w. ja v a 2s . c o m res.write(buf.array(), buf.arrayOffset(), buf.readableBytes()); buf.release(); }
From source file:divconq.struct.CompositeStruct.java
License:Open Source License
public Memory toSerialMemory() throws BuilderStateException { ByteBuf buf = Hub.instance.getBufferAllocator().heapBuffer(16 * 1024, 16 * 1024 * 1024); CompositeToBufferBuilder rb = new CompositeToBufferBuilder(buf); this.toBuilder(rb); rb.write(Special.End);//from w ww . j a v a 2 s . c o m Memory res = new Memory(buf.readableBytes()); res.write(buf.array(), buf.arrayOffset(), buf.readableBytes()); buf.release(); return res; }
From source file:divconq.test.pgp.PGPWriter2.java
License:Open Source License
@SuppressWarnings("resource") public void test2(String srcpath, String destpath, String keyring) throws Exception { Path src = Paths.get(srcpath); // file data byte[] fileData = Files.readAllBytes(src); // dest//from w ww . j a va 2 s . c o m OutputStream dest = new BufferedOutputStream(new FileOutputStream(destpath)); // encryption key PGPPublicKey pubKey = null; InputStream keyIn = new BufferedInputStream(new FileInputStream(keyring)); PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection( org.bouncycastle.openpgp.PGPUtil.getDecoderStream(keyIn), new JcaKeyFingerprintCalculator()); // // we just loop through the collection till we find a key suitable for encryption, in the real // world you would probably want to be a bit smarter about this. // @SuppressWarnings("rawtypes") Iterator keyRingIter = pgpPub.getKeyRings(); while (keyRingIter.hasNext() && (pubKey == null)) { PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next(); @SuppressWarnings("rawtypes") Iterator keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext() && (pubKey == null)) { PGPPublicKey key = (PGPPublicKey) keyIter.next(); if (key.isEncryptionKey()) pubKey = key; } } if (pubKey == null) throw new IllegalArgumentException("Can't find encryption key in key ring."); String fileName = src.getFileName().toString(); byte[] encName = Utf8Encoder.encode(fileName); long modificationTime = System.currentTimeMillis(); SecureRandom rand = new SecureRandom(); int algorithm = PGPEncryptedData.AES_256; Cipher cipher = null; ByteBuf leadingbuf = Hub.instance.getBufferAllocator().heapBuffer(1024 * 1024); // 1 mb ByteBuf encbuf = Hub.instance.getBufferAllocator().heapBuffer(1024 * 1024); // 1 mb // ******************************************************************* // public key packet // ******************************************************************* PGPKeyEncryptionMethodGenerator method = new JcePublicKeyKeyEncryptionMethodGenerator(pubKey); byte[] key = org.bouncycastle.openpgp.PGPUtil.makeRandomKey(algorithm, rand); byte[] sessionInfo = new byte[key.length + 3]; // add algorithm sessionInfo[0] = (byte) algorithm; // add key System.arraycopy(key, 0, sessionInfo, 1, key.length); // add checksum int check = 0; for (int i = 1; i != sessionInfo.length - 2; i++) check += sessionInfo[i] & 0xff; sessionInfo[sessionInfo.length - 2] = (byte) (check >> 8); sessionInfo[sessionInfo.length - 1] = (byte) (check); ContainedPacket packet1 = method.generate(algorithm, sessionInfo); byte[] encoded1 = packet1.getEncoded(); leadingbuf.writeBytes(encoded1); // ******************************************************************* // encrypt packet, add IV to encryption though // ******************************************************************* leadingbuf.writeByte(0xC0 | PacketTags.SYM_ENC_INTEGRITY_PRO); this.writePacketLength(leadingbuf, 0); // 0 = we don't know leadingbuf.writeByte(1); // version number String cName = PGPUtil.getSymmetricCipherName(algorithm) + "/CFB/NoPadding"; DefaultJcaJceHelper helper = new DefaultJcaJceHelper(); cipher = helper.createCipher(cName); byte[] iv = new byte[cipher.getBlockSize()]; cipher.init(Cipher.ENCRYPT_MODE, PGPUtil.makeSymmetricKey(algorithm, key), new IvParameterSpec(iv)); // ******************** start encryption ********************** // --- encrypt checksum for encrypt packet, part of the encrypted output --- byte[] inLineIv = new byte[cipher.getBlockSize() + 2]; rand.nextBytes(inLineIv); inLineIv[inLineIv.length - 1] = inLineIv[inLineIv.length - 3]; inLineIv[inLineIv.length - 2] = inLineIv[inLineIv.length - 4]; encbuf.writeBytes(inLineIv); System.out.println("bytes written a: " + encbuf.readableBytes()); // --- data packet --- int chunkpos = 0; int headerlen = 1 // format + 1 // name length + encName.length // file name + 4; // time encbuf.writeByte(0xC0 | PacketTags.LITERAL_DATA); int packetsize = 512 - headerlen; if (fileData.length - chunkpos < packetsize) { packetsize = fileData.length - chunkpos; this.writePacketLength(encbuf, headerlen + packetsize); } else { encbuf.writeByte(0xE9); // 512 packet length } System.out.println("bytes written b: " + encbuf.readableBytes()); encbuf.writeByte(PGPLiteralData.BINARY); // data format encbuf.writeByte((byte) encName.length); // file name encbuf.writeBytes(encName); encbuf.writeInt((int) (modificationTime / 1000)); // mod time System.out.println("bytes written c: " + encbuf.readableBytes()); encbuf.writeBytes(fileData, chunkpos, packetsize); System.out.println("bytes written d: " + encbuf.readableBytes()); chunkpos += packetsize; // write one or more literal packets while (chunkpos < fileData.length) { packetsize = 512; // check if this is the final packet if (fileData.length - chunkpos <= packetsize) { packetsize = fileData.length - chunkpos; this.writePacketLength(encbuf, packetsize); } else { encbuf.writeByte(0xE9); // full 512 packet length } encbuf.writeBytes(fileData, chunkpos, packetsize); chunkpos += packetsize; } // protection packet encbuf.writeByte(0xC0 | PacketTags.MOD_DETECTION_CODE); encbuf.writeByte(20); // packet length MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex()); byte[] rv = md.digest(); encbuf.writeBytes(rv); System.out.println("Pre-Encrypted Hex"); this.hexDump(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex()); System.out.println(); System.out.println(); // ***** encryption data ready ********* byte[] encdata = cipher.doFinal(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex()); // add encrypted data to main buffer leadingbuf.writeBytes(encdata); System.out.println("Final Hex"); this.hexDump(leadingbuf.array(), leadingbuf.arrayOffset(), leadingbuf.writerIndex()); System.out.println(); System.out.println(); // write to file dest.write(leadingbuf.array(), leadingbuf.arrayOffset(), leadingbuf.writerIndex()); dest.flush(); dest.close(); }
From source file:divconq.test.pgp.PGPWriter2.java
License:Open Source License
@SuppressWarnings("resource") public void test1(String srcpath, String destpath, String keyring) throws Exception { Path src = Paths.get(srcpath); // file data byte[] story = Files.readAllBytes(src); // dest/*from ww w.j a v a2 s. c o m*/ OutputStream dest = new BufferedOutputStream(new FileOutputStream(destpath)); // encryption key PGPPublicKey pubKey = null; InputStream keyIn = new BufferedInputStream(new FileInputStream(keyring)); PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection( org.bouncycastle.openpgp.PGPUtil.getDecoderStream(keyIn), new JcaKeyFingerprintCalculator()); // // we just loop through the collection till we find a key suitable for encryption, in the real // world you would probably want to be a bit smarter about this. // @SuppressWarnings("rawtypes") Iterator keyRingIter = pgpPub.getKeyRings(); while (keyRingIter.hasNext() && (pubKey == null)) { PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next(); @SuppressWarnings("rawtypes") Iterator keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext() && (pubKey == null)) { PGPPublicKey key = (PGPPublicKey) keyIter.next(); if (key.isEncryptionKey()) pubKey = key; } } if (pubKey == null) throw new IllegalArgumentException("Can't find encryption key in key ring."); String fileName = src.getFileName().toString(); byte[] encName = Utf8Encoder.encode(fileName); long modificationTime = System.currentTimeMillis(); SecureRandom rand = new SecureRandom(); int algorithm = PGPEncryptedData.AES_256; Cipher cipher = null; ByteBuf leadingbuf = Hub.instance.getBufferAllocator().heapBuffer(1024 * 1024); // 1 mb ByteBuf encbuf = Hub.instance.getBufferAllocator().heapBuffer(1024 * 1024); // 1 mb // ******************************************************************* // public key packet // ******************************************************************* PGPKeyEncryptionMethodGenerator method = new JcePublicKeyKeyEncryptionMethodGenerator(pubKey); byte[] key = org.bouncycastle.openpgp.PGPUtil.makeRandomKey(algorithm, rand); byte[] sessionInfo = new byte[key.length + 3]; // add algorithm sessionInfo[0] = (byte) algorithm; // add key System.arraycopy(key, 0, sessionInfo, 1, key.length); // add checksum int check = 0; for (int i = 1; i != sessionInfo.length - 2; i++) check += sessionInfo[i] & 0xff; sessionInfo[sessionInfo.length - 2] = (byte) (check >> 8); sessionInfo[sessionInfo.length - 1] = (byte) (check); ContainedPacket packet1 = method.generate(algorithm, sessionInfo); byte[] encoded1 = packet1.getEncoded(); leadingbuf.writeBytes(encoded1); // ******************************************************************* // encrypt packet, add IV to // ******************************************************************* String cName = PGPUtil.getSymmetricCipherName(algorithm) + "/CFB/NoPadding"; DefaultJcaJceHelper helper = new DefaultJcaJceHelper(); cipher = helper.createCipher(cName); byte[] iv = new byte[cipher.getBlockSize()]; cipher.init(Cipher.ENCRYPT_MODE, PGPUtil.makeSymmetricKey(algorithm, key), new IvParameterSpec(iv)); // ******************** start encryption ********************** // --- encrypt checksum for encrypt packet, part of the encrypted output --- byte[] inLineIv = new byte[cipher.getBlockSize() + 2]; rand.nextBytes(inLineIv); inLineIv[inLineIv.length - 1] = inLineIv[inLineIv.length - 3]; inLineIv[inLineIv.length - 2] = inLineIv[inLineIv.length - 4]; encbuf.writeBytes(inLineIv); // --- data packet --- encbuf.writeByte(0xC0 | PacketTags.LITERAL_DATA); this.writePacketLength(encbuf, 1 // format + 1 // name length + encName.length // file name + 4 // time + story.length // data ); encbuf.writeByte(PGPLiteralData.BINARY); encbuf.writeByte((byte) encName.length); encbuf.writeBytes(encName); encbuf.writeInt((int) (modificationTime / 1000)); encbuf.writeBytes(story); // protection packet encbuf.writeByte(0xC0 | PacketTags.MOD_DETECTION_CODE); encbuf.writeByte(20); // packet length MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex()); byte[] rv = md.digest(); encbuf.writeBytes(rv); System.out.println("Encrypted Hex"); this.hexDump(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex()); System.out.println(); System.out.println(); // ***** encryption data ready ********* byte[] encdata = cipher.doFinal(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex()); leadingbuf.writeByte(0xC0 | PacketTags.SYM_ENC_INTEGRITY_PRO); /* this.writePacketLength(leadingbuf, 1 // version + encdata.length // encrypted data ); */ this.writePacketLength(leadingbuf, 0); // 0 = we don't know leadingbuf.writeByte(1); // version number // add encrypted data to main buffer leadingbuf.writeBytes(encdata); System.out.println("Final Hex"); this.hexDump(leadingbuf.array(), leadingbuf.arrayOffset(), leadingbuf.writerIndex()); System.out.println(); System.out.println(); // write to file dest.write(leadingbuf.array(), leadingbuf.arrayOffset(), leadingbuf.writerIndex()); dest.flush(); dest.close(); }
From source file:dorkbox.network.connection.KryoExtra.java
License:Apache License
/** * This is NOT ENCRYPTED (and is only done on the loopback connection!) *///from www. j av a 2s . c o m public synchronized void writeCompressed(final Connection_ connection, final ByteBuf buffer, final Object message) throws IOException { // required by RMI and some serializers to determine which connection wrote (or has info about) this object this.rmiSupport = connection.rmiSupport(); ByteBuf objectOutputBuffer = this.tempBuffer; objectOutputBuffer.clear(); // always have to reset everything // write the object to a TEMP buffer! this will be compressed writer.setBuffer(objectOutputBuffer); writeClassAndObject(writer, message); // save off how much data the object took + magic byte int length = objectOutputBuffer.writerIndex(); // NOTE: compression and encryption MUST work with byte[] because they use JNI! // Realistically, it is impossible to get the backing arrays out of a Heap Buffer once they are resized and begin to use // sliced. It's lame that there is a "double copy" of bytes here, but I don't know how to avoid it... // see: https://stackoverflow.com/questions/19296386/netty-java-getting-data-from-bytebuf byte[] inputArray; int inputOffset; // Even if a ByteBuf has a backing array (i.e. buf.hasArray() returns true), the using it isn't always possible because // the buffer might be a slice of other buffer or a pooled buffer: //noinspection Duplicates if (objectOutputBuffer.hasArray() && objectOutputBuffer.array()[0] == objectOutputBuffer.getByte(0) && objectOutputBuffer.array().length == objectOutputBuffer.capacity()) { // we can use it... inputArray = objectOutputBuffer.array(); inputArrayLength = -1; // this is so we don't REUSE this array accidentally! inputOffset = objectOutputBuffer.arrayOffset(); } else { // we can NOT use it. if (length > inputArrayLength) { inputArrayLength = length; inputArray = new byte[length]; this.inputArray = inputArray; } else { inputArray = this.inputArray; } objectOutputBuffer.getBytes(objectOutputBuffer.readerIndex(), inputArray, 0, length); inputOffset = 0; } ////////// compressing data // we ALWAYS compress our data stream -- because of how AES-GCM pads data out, the small input (that would result in a larger // output), will be negated by the increase in size by the encryption byte[] compressOutput = this.compressOutput; int maxLengthLengthOffset = 4; // length is never negative, so 4 is OK (5 means it's negative) int maxCompressedLength = compressor.maxCompressedLength(length); // add 4 so there is room to write the compressed size to the buffer int maxCompressedLengthWithOffset = maxCompressedLength + maxLengthLengthOffset; // lazy initialize the compression output buffer if (maxCompressedLengthWithOffset > compressOutputLength) { compressOutputLength = maxCompressedLengthWithOffset; compressOutput = new byte[maxCompressedLengthWithOffset]; this.compressOutput = compressOutput; } // LZ4 compress. output offset max 4 bytes to leave room for length of tempOutput data int compressedLength = compressor.compress(inputArray, inputOffset, length, compressOutput, maxLengthLengthOffset, maxCompressedLength); // bytes can now be written to, because our compressed data is stored in a temp array. final int lengthLength = OptimizeUtilsByteArray.intLength(length, true); // correct input. compression output is now buffer input inputArray = compressOutput; inputOffset = maxLengthLengthOffset - lengthLength; // now write the ORIGINAL (uncompressed) length to the front of the byte array (this is NOT THE BUFFER!). This is so we can use the FAST decompress version OptimizeUtilsByteArray.writeInt(inputArray, length, true, inputOffset); // have to copy over the orig data, because we used the temp buffer. Also have to account for the length of the uncompressed size buffer.writeBytes(inputArray, inputOffset, compressedLength + lengthLength); }
From source file:dorkbox.network.connection.KryoExtra.java
License:Apache License
/** * This is NOT ENCRYPTED (and is only done on the loopback connection!) */// www .j a v a 2 s. c o m public Object readCompressed(final Connection_ connection, final ByteBuf buffer, int length) throws IOException { // required by RMI and some serializers to determine which connection wrote (or has info about) this object this.rmiSupport = connection.rmiSupport(); //////////////// // Note: we CANNOT write BACK to the buffer as "temp" storage, since there could be additional data on it! //////////////// ByteBuf inputBuf = buffer; // get the decompressed length (at the beginning of the array) final int uncompressedLength = OptimizeUtilsByteBuf.readInt(buffer, true); final int lengthLength = OptimizeUtilsByteArray.intLength(uncompressedLength, true); // because 1-5 bytes for the decompressed size // have to adjust for uncompressed length length = length - lengthLength; ///////// decompress data -- as it's ALWAYS compressed // NOTE: compression and encryption MUST work with byte[] because they use JNI! // Realistically, it is impossible to get the backing arrays out of a Heap Buffer once they are resized and begin to use // sliced. It's lame that there is a "double copy" of bytes here, but I don't know how to avoid it... // see: https://stackoverflow.com/questions/19296386/netty-java-getting-data-from-bytebuf byte[] inputArray; int inputOffset; // Even if a ByteBuf has a backing array (i.e. buf.hasArray() returns true), the using it isn't always possible because // the buffer might be a slice of other buffer or a pooled buffer: //noinspection Duplicates if (inputBuf.hasArray() && inputBuf.array()[0] == inputBuf.getByte(0) && inputBuf.array().length == inputBuf.capacity()) { // we can use it... inputArray = inputBuf.array(); inputArrayLength = -1; // this is so we don't REUSE this array accidentally! inputOffset = inputBuf.arrayOffset() + lengthLength; } else { // we can NOT use it. if (length > inputArrayLength) { inputArrayLength = length; inputArray = new byte[length]; this.inputArray = inputArray; } else { inputArray = this.inputArray; } inputBuf.getBytes(inputBuf.readerIndex(), inputArray, 0, length); inputOffset = 0; } // have to make sure to set the position of the buffer, since our conversion to array DOES NOT set the new reader index. buffer.readerIndex(buffer.readerIndex() + length); ///////// decompress data -- as it's ALWAYS compressed byte[] decompressOutputArray = this.decompressOutput; if (uncompressedLength > decompressOutputLength) { decompressOutputLength = uncompressedLength; decompressOutputArray = new byte[uncompressedLength]; this.decompressOutput = decompressOutputArray; decompressBuf = Unpooled.wrappedBuffer(decompressOutputArray); // so we can read via kryo } inputBuf = decompressBuf; // LZ4 decompress, requires the size of the ORIGINAL length (because we use the FAST decompressor) decompressor.decompress(inputArray, inputOffset, decompressOutputArray, 0, uncompressedLength); inputBuf.setIndex(0, uncompressedLength); // read the object from the buffer. reader.setBuffer(inputBuf); return readClassAndObject(reader); // this properly sets the readerIndex, but only if it's the correct buffer }
From source file:dorkbox.network.connection.KryoExtra.java
License:Apache License
public synchronized void writeCrypto(final Connection_ connection, final ByteBuf buffer, final Object message) throws IOException { // required by RMI and some serializers to determine which connection wrote (or has info about) this object this.rmiSupport = connection.rmiSupport(); ByteBuf objectOutputBuffer = this.tempBuffer; objectOutputBuffer.clear(); // always have to reset everything // write the object to a TEMP buffer! this will be compressed writer.setBuffer(objectOutputBuffer); writeClassAndObject(writer, message); // save off how much data the object took int length = objectOutputBuffer.writerIndex(); // NOTE: compression and encryption MUST work with byte[] because they use JNI! // Realistically, it is impossible to get the backing arrays out of a Heap Buffer once they are resized and begin to use // sliced. It's lame that there is a "double copy" of bytes here, but I don't know how to avoid it... // see: https://stackoverflow.com/questions/19296386/netty-java-getting-data-from-bytebuf byte[] inputArray; int inputOffset; // Even if a ByteBuf has a backing array (i.e. buf.hasArray() returns true), the using it isn't always possible because // the buffer might be a slice of other buffer or a pooled buffer: //noinspection Duplicates if (objectOutputBuffer.hasArray() && objectOutputBuffer.array()[0] == objectOutputBuffer.getByte(0) && objectOutputBuffer.array().length == objectOutputBuffer.capacity()) { // we can use it... inputArray = objectOutputBuffer.array(); inputArrayLength = -1; // this is so we don't REUSE this array accidentally! inputOffset = objectOutputBuffer.arrayOffset(); } else {//from w w w . j a va 2 s. c om // we can NOT use it. if (length > inputArrayLength) { inputArrayLength = length; inputArray = new byte[length]; this.inputArray = inputArray; } else { inputArray = this.inputArray; } objectOutputBuffer.getBytes(objectOutputBuffer.readerIndex(), inputArray, 0, length); inputOffset = 0; } ////////// compressing data // we ALWAYS compress our data stream -- because of how AES-GCM pads data out, the small input (that would result in a larger // output), will be negated by the increase in size by the encryption byte[] compressOutput = this.compressOutput; int maxLengthLengthOffset = 4; // length is never negative, so 4 is OK (5 means it's negative) int maxCompressedLength = compressor.maxCompressedLength(length); // add 4 so there is room to write the compressed size to the buffer int maxCompressedLengthWithOffset = maxCompressedLength + maxLengthLengthOffset; // lazy initialize the compression output buffer if (maxCompressedLengthWithOffset > compressOutputLength) { compressOutputLength = maxCompressedLengthWithOffset; compressOutput = new byte[maxCompressedLengthWithOffset]; this.compressOutput = compressOutput; } // LZ4 compress. output offset max 4 bytes to leave room for length of tempOutput data int compressedLength = compressor.compress(inputArray, inputOffset, length, compressOutput, maxLengthLengthOffset, maxCompressedLength); // bytes can now be written to, because our compressed data is stored in a temp array. final int lengthLength = OptimizeUtilsByteArray.intLength(length, true); // correct input. compression output is now encryption input inputArray = compressOutput; inputOffset = maxLengthLengthOffset - lengthLength; // now write the ORIGINAL (uncompressed) length to the front of the byte array. This is so we can use the FAST decompress version OptimizeUtilsByteArray.writeInt(inputArray, length, true, inputOffset); // correct length for encryption length = compressedLength + lengthLength; // +1 to +4 for the uncompressed size bytes /////// encrypting data. final long nextGcmSequence = connection.getNextGcmSequence(); // this is a threadlocal, so that we don't clobber other threads that are performing crypto on the same connection at the same time final ParametersWithIV cryptoParameters = connection.getCryptoParameters(); BigEndian.Long_.toBytes(nextGcmSequence, cryptoParameters.getIV(), 4); // put our counter into the IV final GCMBlockCipher aes = this.aesEngine; aes.reset(); aes.init(true, cryptoParameters); byte[] cryptoOutput; // lazy initialize the crypto output buffer int cryptoSize = length + 16; // from: aes.getOutputSize(length); // 'output' is the temp byte array if (cryptoSize > cryptoOutputLength) { cryptoOutputLength = cryptoSize; cryptoOutput = new byte[cryptoSize]; this.cryptoOutput = cryptoOutput; } else { cryptoOutput = this.cryptoOutput; } int encryptedLength = aes.processBytes(inputArray, inputOffset, length, cryptoOutput, 0); try { // authentication tag for GCM encryptedLength += aes.doFinal(cryptoOutput, encryptedLength); } catch (Exception e) { throw new IOException("Unable to AES encrypt the data", e); } // write out our GCM counter OptimizeUtilsByteBuf.writeLong(buffer, nextGcmSequence, true); // have to copy over the orig data, because we used the temp buffer buffer.writeBytes(cryptoOutput, 0, encryptedLength); }
From source file:dorkbox.network.connection.KryoExtra.java
License:Apache License
public Object readCrypto(final Connection_ connection, final ByteBuf buffer, int length) throws IOException { // required by RMI and some serializers to determine which connection wrote (or has info about) this object this.rmiSupport = connection.rmiSupport(); //////////////// // Note: we CANNOT write BACK to the buffer as "temp" storage, since there could be additional data on it! //////////////// ByteBuf inputBuf = buffer; final long gcmIVCounter = OptimizeUtilsByteBuf.readLong(buffer, true); int lengthLength = OptimizeUtilsByteArray.longLength(gcmIVCounter, true); // have to adjust for the gcmIVCounter length = length - lengthLength;//from w ww . j av a 2 s . c o m /////////// decrypting data // NOTE: compression and encryption MUST work with byte[] because they use JNI! // Realistically, it is impossible to get the backing arrays out of a Heap Buffer once they are resized and begin to use // sliced. It's lame that there is a "double copy" of bytes here, but I don't know how to avoid it... // see: https://stackoverflow.com/questions/19296386/netty-java-getting-data-from-bytebuf byte[] inputArray; int inputOffset; // Even if a ByteBuf has a backing array (i.e. buf.hasArray() returns true), the using it isn't always possible because // the buffer might be a slice of other buffer or a pooled buffer: //noinspection Duplicates if (inputBuf.hasArray() && inputBuf.array()[0] == inputBuf.getByte(0) && inputBuf.array().length == inputBuf.capacity()) { // we can use it... inputArray = inputBuf.array(); inputArrayLength = -1; // this is so we don't REUSE this array accidentally! inputOffset = inputBuf.arrayOffset() + lengthLength; } else { // we can NOT use it. if (length > inputArrayLength) { inputArrayLength = length; inputArray = new byte[length]; this.inputArray = inputArray; } else { inputArray = this.inputArray; } inputBuf.getBytes(inputBuf.readerIndex(), inputArray, 0, length); inputOffset = 0; } // have to make sure to set the position of the buffer, since our conversion to array DOES NOT set the new reader index. buffer.readerIndex(buffer.readerIndex() + length); // this is a threadlocal, so that we don't clobber other threads that are performing crypto on the same connection at the same time final ParametersWithIV cryptoParameters = connection.getCryptoParameters(); BigEndian.Long_.toBytes(gcmIVCounter, cryptoParameters.getIV(), 4); // put our counter into the IV final GCMBlockCipher aes = this.aesEngine; aes.reset(); aes.init(false, cryptoParameters); int cryptoSize = length - 16; // from: aes.getOutputSize(length); // lazy initialize the decrypt output buffer byte[] decryptOutputArray; if (cryptoSize > decryptOutputLength) { decryptOutputLength = cryptoSize; decryptOutputArray = new byte[cryptoSize]; this.decryptOutput = decryptOutputArray; decryptBuf = Unpooled.wrappedBuffer(decryptOutputArray); } else { decryptOutputArray = this.decryptOutput; } int decryptedLength = aes.processBytes(inputArray, inputOffset, length, decryptOutputArray, 0); try { // authentication tag for GCM decryptedLength += aes.doFinal(decryptOutputArray, decryptedLength); } catch (Exception e) { throw new IOException("Unable to AES decrypt the data", e); } ///////// decompress data -- as it's ALWAYS compressed // get the decompressed length (at the beginning of the array) inputArray = decryptOutputArray; final int uncompressedLength = OptimizeUtilsByteArray.readInt(inputArray, true); inputOffset = OptimizeUtilsByteArray.intLength(uncompressedLength, true); // because 1-4 bytes for the decompressed size byte[] decompressOutputArray = this.decompressOutput; if (uncompressedLength > decompressOutputLength) { decompressOutputLength = uncompressedLength; decompressOutputArray = new byte[uncompressedLength]; this.decompressOutput = decompressOutputArray; decompressBuf = Unpooled.wrappedBuffer(decompressOutputArray); // so we can read via kryo } inputBuf = decompressBuf; // LZ4 decompress, requires the size of the ORIGINAL length (because we use the FAST decompressor decompressor.decompress(inputArray, inputOffset, decompressOutputArray, 0, uncompressedLength); inputBuf.setIndex(0, uncompressedLength); // read the object from the buffer. reader.setBuffer(inputBuf); return readClassAndObject(reader); // this properly sets the readerIndex, but only if it's the correct buffer }
From source file:io.atomix.cluster.messaging.impl.MessageDecoder.java
License:Apache License
static String readString(ByteBuf buffer, int length, Charset charset) { if (buffer.isDirect()) { final String result = buffer.toString(buffer.readerIndex(), length, charset); buffer.skipBytes(length);/*w w w . jav a2 s .c om*/ return result; } else if (buffer.hasArray()) { final String result = new String(buffer.array(), buffer.arrayOffset() + buffer.readerIndex(), length, charset); buffer.skipBytes(length); return result; } else { final byte[] array = new byte[length]; buffer.readBytes(array); return new String(array, charset); } }