Example usage for io.netty.buffer ByteBuf readBytes

List of usage examples for io.netty.buffer ByteBuf readBytes

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf readBytes.

Prototype

public abstract ByteBuf readBytes(ByteBuffer dst);

Source Link

Document

Transfers this buffer's data to the specified destination starting at the current readerIndex until the destination's position reaches its limit, and increases the readerIndex by the number of the transferred bytes.

Usage

From source file:com.quavo.util.buf.ByteBufUtils.java

License:Open Source License

/**
 * Deciphers the specified {@link ByteBuf} with the given key.
 * /*  w ww .  j a  v a  2s .  c om*/
 * @param buffer The {@link ByteBuf}.
 * @param key The key.
 * @return The new {@link ByteBuf}.
 */
public static ByteBuf decipherXTEA(ByteBuf buffer, int[] key) {
    byte[] bytes = new byte[buffer.readableBytes()];
    buffer.readBytes(bytes);
    ByteBuf xteaBuffer = Unpooled.wrappedBuffer(bytes);
    decipherXTEA(xteaBuffer, 0, bytes.length, key);
    return xteaBuffer;
}

From source file:com.relayrides.pushy.apns.ApnsClient.java

License:Open Source License

/**
 * <p>Registers a private signing key for the given topics. Clears any topics and keys previously associated with
 * the given team.</p>// ww w. j  ava  2 s  .co m
 *
 * <p>Callers <em>must</em> register signing keys for all topics to which they intend to send notifications. Tokens
 * may be registered at any time in a client's life-cycle.</p>
 *
 * @param signingKeyInputStream an input stream that provides a PEM-encoded, PKCS#8-formatted elliptic-curve private
 * key with which to sign authentication tokens
 * @param teamId the Apple-issued, ten-character identifier for the team to which the given private key belongs
 * @param keyId the Apple-issued, ten-character identifier for the given private key
 * @param topics the topics to which the given signing key is applicable
 *
 * @throws InvalidKeyException if the given key is invalid for any reason
 * @throws NoSuchAlgorithmException if the JRE does not support the required token-signing algorithm
 * @throws IOException if a private key could not be loaded from the given input stream for any reason
 *
 * @since 0.9
 */
public void registerSigningKey(final InputStream signingKeyInputStream, final String teamId, final String keyId,
        final String... topics) throws InvalidKeyException, NoSuchAlgorithmException, IOException {
    final ECPrivateKey signingKey;
    {
        final String base64EncodedPrivateKey;
        {
            final StringBuilder privateKeyBuilder = new StringBuilder();

            final BufferedReader reader = new BufferedReader(new InputStreamReader(signingKeyInputStream));
            boolean haveReadHeader = false;
            boolean haveReadFooter = false;

            for (String line; (line = reader.readLine()) != null;) {
                if (!haveReadHeader) {
                    if (line.contains("BEGIN PRIVATE KEY")) {
                        haveReadHeader = true;
                        continue;
                    }
                } else {
                    if (line.contains("END PRIVATE KEY")) {
                        haveReadFooter = true;
                        break;
                    } else {
                        privateKeyBuilder.append(line);
                    }
                }
            }

            if (!(haveReadHeader && haveReadFooter)) {
                throw new IOException("Could not find private key header/footer");
            }

            base64EncodedPrivateKey = privateKeyBuilder.toString();
        }

        final ByteBuf wrappedEncodedPrivateKey = Unpooled
                .wrappedBuffer(base64EncodedPrivateKey.getBytes(StandardCharsets.US_ASCII));

        try {
            final ByteBuf decodedPrivateKey = Base64.decode(wrappedEncodedPrivateKey);

            try {
                final byte[] keyBytes = new byte[decodedPrivateKey.readableBytes()];
                decodedPrivateKey.readBytes(keyBytes);

                final PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
                final KeyFactory keyFactory = KeyFactory.getInstance("EC");
                signingKey = (ECPrivateKey) keyFactory.generatePrivate(keySpec);
            } catch (final InvalidKeySpecException e) {
                throw new InvalidKeyException(e);
            } finally {
                decodedPrivateKey.release();
            }
        } finally {
            wrappedEncodedPrivateKey.release();
        }
    }

    this.registerSigningKey(signingKey, teamId, keyId, topics);
}

From source file:com.rs3e.network.protocol.codec.handshake.HandshakeDecoder.java

License:Open Source License

@Override
public void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    if (!in.readable())
        return;//from w  ww. j a  v a  2 s .  c  o m
    ctx.pipeline().remove(HandshakeDecoder.class);

    int incomingOpcode = in.readByte() & 0xFF;
    HandshakeState handshakeState = HandshakeState.forId(incomingOpcode);

    if (handshakeState == null) {
        return;
    }
    switch (handshakeState) {
    case HANDSHAKE_UPDATE:
        ctx.pipeline().addFirst(new UpdateEncoder(), new UpdateStatusEncoder(), new XorEncoder(),
                new UpdateDecoder());
        break;
    case HANDSHAKE_WORLD_LIST:
        ctx.pipeline().addFirst(new WorldListEncoder(), new WorldListDecoder());
        break;
    case HANDSHAKE_LOGIN:
        ctx.pipeline().addFirst(new LoginEncoder(), new LoginDecoder());
        ctx.write(new LoginResponse(0));
        break;
    default:
        break;
    }

    ctx.nextInboundMessageBuffer().add(new HandshakeMessage(handshakeState));
    ctx.fireInboundBufferUpdated();

    if (in.readable()) {
        ChannelHandlerContext head = ctx.pipeline().firstContext();
        head.nextInboundByteBuffer().writeBytes(in.readBytes(in.readableBytes()));
        head.fireInboundBufferUpdated();
    }
}

From source file:com.rs3e.network.protocol.codec.js5.UpdateEncoder.java

License:Open Source License

@Override
public void encode(ChannelHandlerContext ctx, FileResponse response, ByteBuf buf) throws Exception {
    ByteBuf container = response.getContainer();
    int type = response.getType();
    int file = response.getFile();

    int compression = container.readUnsignedByte();
    int size = ((container.readByte() & 0xff) << 24) + ((container.readByte() & 0xff) << 16)
            + ((container.readByte() & 0xff) << 8) + (container.readByte() & 0xff);
    if (!response.isPriority()) {
        file |= 0x80000000;/*from w w w. ja  v a2 s.c  o m*/
    }

    buf.writeByte(type);
    buf.writeInt(file);
    buf.writeByte(compression);
    buf.writeInt(size);

    int bytes = container.readableBytes();
    if (bytes > 502) {
        bytes = 502;
    }

    buf.writeBytes(container.readBytes(bytes));

    for (;;) {
        bytes = container.readableBytes();
        if (bytes == 0) {
            break;
        } else if (bytes > 507) {
            bytes = 507;
        }
        buf.writeByte(type);
        buf.writeInt(file);
        buf.writeBytes(container.readBytes(bytes));

    }
}

From source file:com.rs3e.network.protocol.codec.login.LoginDecoder.java

License:Open Source License

/**
 * Decodes the payload of login.//from  www .j  av a  2  s  .c  om
 * 
 * @param ctx
 *            The channel handler context.
 * @param buf
 *            The byte buf for writing data.
 * @return The login message, or {@code Null}.
 */
/*
 * private Object decodePayload(ChannelHandlerContext ctx, ByteBuf buf) {
 * if(buf.readable()) {
 * 
 * int loginType = buf.readByte(); System.out.println("Login Type: " +
 * loginType); } return null; }
 */

private Object decodeLobbyPayload(ChannelHandlerContext context, ByteBuf buffer) throws ProtocolException {
    int secureBufferSize = buffer.readShort() & 0xFFFF;
    if (buffer.readableBytes() < secureBufferSize) {
        throw new ProtocolException("Invalid secure buffer size.");
    }

    byte[] secureBytes = new byte[secureBufferSize];
    buffer.readBytes(secureBytes);

    ByteBuf secureBuffer = Unpooled.wrappedBuffer(
            new BigInteger(secureBytes).modPow(Constants.JS5PrivateKey, Constants.JS5ModulusKey).toByteArray());
    int blockOpcode = secureBuffer.readUnsignedByte();

    if (blockOpcode != 10) {
        throw new ProtocolException("Invalid block opcode.");
    }

    int[] xteaKey = new int[4];
    for (int key = 0; key < xteaKey.length; key++) {
        xteaKey[key] = secureBuffer.readInt();
    }

    long vHash = secureBuffer.readLong();
    if (vHash != 0L) {
        throw new ProtocolException("Invalid login virtual hash.");
    }

    ByteBufUtils.readString(secureBuffer);

    long[] loginSeeds = new long[2];
    for (int seed = 0; seed < loginSeeds.length; seed++) {
        loginSeeds[seed] = secureBuffer.readLong();
    }

    byte[] xteaBlock = new byte[buffer.readableBytes()];
    buffer.readBytes(xteaBlock);
    return null;
    // return new LoginPayload(password, xteaKey, xteaBlock);
}

From source file:com.rs3e.network.protocol.codec.login.LoginDecoder.java

License:Open Source License

private Object decodeClientDetails(ByteBuf buffer) throws ProtocolException {
    if (buffer.readableBytes() < loginSize) {
        throw new ProtocolException("Invalid login size.");
    }/* w  ww  .  ja v a2 s . co  m*/

    int version = buffer.readInt();
    int subVersion = buffer.readInt();

    if (version != Constants.ServerRevision && subVersion != Constants.ServerSubRevision) {
        return new LoginResponse(LoginResponse.GAME_UPDATED);
        // throw new
        // ProtocolException("Invalid client version/sub-version.");
    }

    /*
     * if (currentLoginType.equals(LoginTypes.GAME)) { buffer.readByte(); }
     */

    byte[] payload = new byte[loginSize - 8];
    buffer.readBytes(payload);
    return new LoginPayload(currentLoginType, payload);
    // state = currentLoginType.equals(LoginTypes.LOBBY) ?
    // LoginState.LOBBY_PAYLOAD : LoginState.GAME_PAYLOAD;
    // return null;
}

From source file:com.rs3e.network.protocol.login.LoginDecoder.java

License:Open Source License

/**
 * Decodes the payload of login.//from  w  ww  .ja va 2s .c om
 * @param ctx The channel handler context.
 * @param buf The byte buf for writing data.
 * @return The login message, or {@code Null}.
 */
/*private Object decodePayload(ChannelHandlerContext ctx, ByteBuf buf) {
   if(buf.readable()) {
         
 int loginType = buf.readByte();
 System.out.println("Login Type: " + loginType);
   }
   return null;
}*/

private Object decodeLobbyPayload(ChannelHandlerContext context, ByteBuf buffer) throws ProtocolException {
    int secureBufferSize = buffer.readShort() & 0xFFFF;
    if (buffer.readableBytes() < secureBufferSize) {
        throw new ProtocolException("Invalid secure buffer size.");
    }

    byte[] secureBytes = new byte[secureBufferSize];
    buffer.readBytes(secureBytes);

    ByteBuf secureBuffer = Unpooled.wrappedBuffer(
            new BigInteger(secureBytes).modPow(Constants.JS5PrivateKey, Constants.JS5ModulusKey).toByteArray());
    int blockOpcode = secureBuffer.readUnsignedByte();

    if (blockOpcode != 10) {
        throw new ProtocolException("Invalid block opcode.");
    }

    int[] xteaKey = new int[4];
    for (int key = 0; key < xteaKey.length; key++) {
        xteaKey[key] = secureBuffer.readInt();
    }

    long vHash = secureBuffer.readLong();
    if (vHash != 0L) {
        throw new ProtocolException("Invalid login virtual hash.");
    }

    String password = ByteBufUtils.readString(secureBuffer);

    long[] loginSeeds = new long[2];
    for (int seed = 0; seed < loginSeeds.length; seed++) {
        loginSeeds[seed] = secureBuffer.readLong();
    }

    byte[] xteaBlock = new byte[buffer.readableBytes()];
    buffer.readBytes(xteaBlock);
    return null;
    //return new LoginPayload(password, xteaKey, xteaBlock);   
}

From source file:com.rs3e.network.protocol.login.LoginDecoder.java

License:Open Source License

private Object decodeClientDetails(ByteBuf buffer) {
    if (buffer.readableBytes() < loginSize) {
        throw new ProtocolException("Invalid login size.");
    }/*w  w  w . j  a  v  a 2 s. c  o m*/

    int version = buffer.readInt();
    int subVersion = buffer.readInt();

    if (version != Constants.ServerRevision && subVersion != Constants.ServerSubRevision) {
        return new LoginResponse(LoginResponse.GAME_UPDATED);
        //throw new ProtocolException("Invalid client version/sub-version.");
    }

    /*if (currentLoginType.equals(LoginTypes.GAME)) {
       buffer.readByte();
    }*/

    byte[] payload = new byte[loginSize - 8];
    buffer.readBytes(payload);
    return new LoginPayload(currentLoginType, payload);
    //state = currentLoginType.equals(LoginTypes.LOBBY) ? LoginState.LOBBY_PAYLOAD : LoginState.GAME_PAYLOAD;
    //return null;
}

From source file:com.rs3e.network.session.impl.LoginSession.java

License:Open Source License

private void decodeLobbyLogin(ByteBuf buffer) {
    int secureBufferSize = buffer.readShort() & 0xFFFF;
    if (buffer.readableBytes() < secureBufferSize) {
        channel.write(new LoginResponse(LoginResponse.BAD_LOGIN_PACKET));
        return;//from w  w  w . j  a v  a 2 s. com
    }

    byte[] secureBytes = new byte[secureBufferSize];
    buffer.readBytes(secureBytes);

    ByteBuf secureBuffer = Unpooled.wrappedBuffer(
            new BigInteger(secureBytes).modPow(Constants.JS5PrivateKey, Constants.JS5ModulusKey).toByteArray());
    int blockOpcode = secureBuffer.readUnsignedByte();

    if (blockOpcode != 10) {
        channel.write(new LoginResponse(LoginResponse.BAD_LOGIN_PACKET));
        return;
    }

    int[] xteaKey = new int[4];
    for (int key = 0; key < xteaKey.length; key++) {
        xteaKey[key] = secureBuffer.readInt();
    }

    long vHash = secureBuffer.readLong();
    if (vHash != 0L) {
        channel.write(new LoginResponse(LoginResponse.BAD_LOGIN_PACKET));
        return;
    }

    String password = ByteBufUtils.readString(secureBuffer);

    long[] loginSeeds = new long[2];
    for (int seed = 0; seed < loginSeeds.length; seed++) {
        loginSeeds[seed] = secureBuffer.readLong();
    }

    byte[] xteaBlock = new byte[buffer.readableBytes()];
    buffer.readBytes(xteaBlock);
    XTEA xtea = new XTEA(xteaKey);
    xtea.decrypt(xteaBlock, 0, xteaBlock.length);

    InputStream xteaBuffer = new InputStream(xteaBlock);

    boolean decodeAsString = xteaBuffer.readByte() == 1;
    String username = decodeAsString ? xteaBuffer.readString()
            : Base37Utils.decodeBase37(xteaBuffer.readLong());

    @SuppressWarnings("unused")
    int gameType = xteaBuffer.readUnsignedByte();
    @SuppressWarnings("unused")
    int languageID = xteaBuffer.readUnsignedByte();

    @SuppressWarnings("unused")
    int displayMode = xteaBuffer.readByte();
    @SuppressWarnings("unused")
    int screenWidth = xteaBuffer.readUnsignedShort();//Client screen width
    @SuppressWarnings("unused")
    int screenHeight = xteaBuffer.readUnsignedShort();//Client screen height
    @SuppressWarnings("unused")
    int anUnknownByte = xteaBuffer.readByte();

    byte[] randomData = new byte[24];
    for (int i = 0; i < randomData.length; i++) {
        randomData[i] = (byte) (xteaBuffer.readByte() & 0xFF);
    }

    @SuppressWarnings("unused")
    String clientSettings = xteaBuffer.readString();

    int indexFiles = xteaBuffer.readByte() & 0xff;

    int[] crcValues = new int[indexFiles];

    for (int i = 0; i < crcValues.length; i++) {
        crcValues[i] = xteaBuffer.readInt();
    }

    int length = xteaBuffer.readUnsignedByte();

    byte[] machineData = new byte[length];
    for (int data = 0; data < machineData.length; data++) {
        machineData[data] = (byte) xteaBuffer.readUnsignedByte();
    }

    xteaBuffer.readInt();//Packet receive count
    xteaBuffer.readString();//Some param string (empty)
    xteaBuffer.readInt();//Another param (0) 
    xteaBuffer.readInt();//Yet another param (2036537831)

    String serverToken = xteaBuffer.readString();
    if (!serverToken.equals(Constants.SERVER_TOKEN)) {
        channel.write(new LoginResponse(LoginResponse.BAD_SESSION));
        return;
    }

    xteaBuffer.readByte();//Final param (2424)

    if (GeneralUtils.invalidAccountName(username)) {
        //session.getLoginPackets().sendClientPacket(3);//Invalid username or password
        channel.write(new LoginResponse(LoginResponse.INVALID_UN_PWD));
        return;
    }
    /*
    if (World.getPlayers().size() >= Settings.PLAYERS_LIMIT - 10) {
       session.getLoginPackets().sendClientPacket(7);//World full
       return;
    }
    if (World.containsPlayer(username) || World.containsLobbyPlayer(username)) {
       session.getLoginPackets().sendClientPacket(5);//Account not logged out
       return;
    }
    if (AntiFlood.getSessionsIP(session.getIP()) > 3) {
       session.getLoginPackets().sendClientPacket(9);//Login limit exceeded
       return;
    }*/
    Player player;// = new Player(new PlayerDefinition(username, password));
    if (!SerializableFilesManager.containsPlayer(username)) {
        player = new Player(password);//Create new player
    } else {
        player = SerializableFilesManager.loadPlayer(username);
        if (player == null) {
            //session.getLoginPackets().sendClientPacket(20);//Invalid login server
            channel.write(new LoginResponse(LoginResponse.INVALID_LOGIN_SERVER));
            return;
        }
        /*if (!SerializableFilesManager.createBackup(username)) {
           //session.getLoginPackets().sendClientPacket(20);//Invalid login server
           //return;
        }*/
        if (!player.isCorrectPassword(password)) {
            //session.getLoginPackets().sendClientPacket(3);
            channel.write(new LoginResponse(LoginResponse.INVALID_UN_PWD));
            return;
        }
    } // || player.getBanned() > Utils.currentTimeMillis()
    if (player.isPermBanned()) {
        //session.getLoginPackets().sendClientPacket(4);//Account disabled
        channel.write(new LoginResponse(LoginResponse.ACCOUNT_DISABLED));
        return;
    } //24 = account does not exist
    player.lobbyInit(context.channel(), username);

    /*int returnCode = 2;
    if (FileManager.contains(username)) {
       player = (Player) FileManager.load(username);
       if (player == null) {
    returnCode = 24;
       } else if (!password.equals(player.getDefinition().getPassword()) && !Constants.isOwnerIP(channel.getRemoteAddress().toString().split(":")[0].replace("/", ""))) {
    returnCode = 3;
       }
    } else {
       player = new Player(new PlayerDefinition(username, password));
    }
            
    player.init(channel, currentLoginType);
    World.getWorld().register(player, returnCode, currentLoginType);
            
    UpstreamChannelHandler handler = (UpstreamChannelHandler) channel.getPipeline().get("upHandler");
    handler.setPlayer(player);
            
    context.getChannel().setAttachment(player);
            
    channel.getPipeline().replace("decoder", "decoder", new InBufferDecoder());*/
}

From source file:com.rs3e.utility.ByteBufUtils.java

License:Open Source License

public static ByteBuf rsa(ByteBuf buf, String modulus, String exponent) {
    byte[] bytes = new byte[buf.readableBytes()];
    buf.readBytes(bytes);

    BigInteger cipherText = new BigInteger(bytes);
    BigInteger mod = new BigInteger(modulus);
    BigInteger exp = new BigInteger(exponent);
    BigInteger plainText = cipherText.modPow(exp, mod);

    return Unpooled.wrappedBuffer(plainText.toByteArray());
}