Example usage for io.netty.handler.codec.base64 Base64 decode

List of usage examples for io.netty.handler.codec.base64 Base64 decode

Introduction

In this page you can find the example usage for io.netty.handler.codec.base64 Base64 decode.

Prototype

public static ByteBuf decode(ByteBuf src) 

Source Link

Usage

From source file:com.comphenix.protocol.compat.netty.independent.IndependentNetty.java

License:Open Source License

@Override
public WrappedByteBuf decode(byte[] encoded) {
    return new NettyByteBuf(Base64.decode(Unpooled.wrappedBuffer(encoded)));
}

From source file:com.github.sinsinpub.pero.manual.proxyhandler.HttpProxyServer.java

License:Apache License

private boolean authenticate(ChannelHandlerContext ctx, FullHttpRequest req) {
    assertThat(req.method(), Matchers.is(HttpMethod.CONNECT));

    if (testMode != TestMode.INTERMEDIARY) {
        ctx.pipeline().addBefore(ctx.name(), "lineDecoder", new LineBasedFrameDecoder(64, false, true));
    }//from w  w  w.  ja v  a 2  s . co m

    ctx.pipeline().remove(HttpObjectAggregator.class);
    ctx.pipeline().remove(HttpRequestDecoder.class);

    boolean authzSuccess = false;
    if (username != null) {
        CharSequence authz = req.headers().get(HttpHeaderNames.PROXY_AUTHORIZATION);
        if (authz != null) {
            String[] authzParts = StringUtil.split(authz.toString(), ' ', 2);
            ByteBuf authzBuf64 = Unpooled.copiedBuffer(authzParts[1], CharsetUtil.US_ASCII);
            ByteBuf authzBuf = Base64.decode(authzBuf64);

            String expectedAuthz = username + ':' + password;
            authzSuccess = "Basic".equals(authzParts[0])
                    && expectedAuthz.equals(authzBuf.toString(CharsetUtil.US_ASCII));

            authzBuf64.release();
            authzBuf.release();
        }
    } else {
        authzSuccess = true;
    }

    return authzSuccess;
}

From source file:com.ibm.mqlight.api.security.PemFile.java

License:Apache License

/**
 * Obtains the list of certificates stored in the PEM file.
 * //from w w  w  .j  a v  a2s . co  m
 * @return The list of certificates stored in the PEM file.
 * @throws CertificateException If a parsing error occurs.
 * @throws IOException If the PEM file cannot be read for any reason.
 */
public List<Certificate> getCertificates() throws CertificateException, IOException {
    final String methodName = "getCertificates";
    logger.entry(this, methodName);

    final String fileData = getPemFileData();

    final List<ByteBuf> certDataList = new ArrayList<ByteBuf>();
    final Matcher m = CERTIFICATE_PATTERN.matcher(fileData);
    int start = 0;
    while (m.find(start)) {
        final ByteBuf base64CertData = Unpooled.copiedBuffer(m.group(1), Charset.forName("US-ASCII"));
        final ByteBuf certData = Base64.decode(base64CertData);
        base64CertData.release();
        certDataList.add(certData);
        start = m.end();
    }

    if (certDataList.isEmpty()) {
        final CertificateException exception = new CertificateException(
                "No certificates found in PEM file: " + pemFile);
        logger.throwing(this, methodName, exception);
        throw exception;
    }

    final CertificateFactory cf = CertificateFactory.getInstance("X.509");
    final List<Certificate> certificates = new ArrayList<Certificate>();

    try {
        for (ByteBuf certData : certDataList) {
            certificates.add(cf.generateCertificate(new ByteBufInputStream(certData)));
        }
    } finally {
        for (ByteBuf certData : certDataList)
            certData.release();
    }

    logger.exit(this, methodName, certificates);

    return certificates;
}

From source file:com.ibm.mqlight.api.security.PemFile.java

License:Apache License

/**
 * Obtains the private key data as a byte array from the PEM file.
 * <p>//w  ww .jav a2 s  .  c om
 * Within the PEM file the private key data is base 64 encoded. This method will decode the data for the returned private key
 * data.
 * <p>
 * Note that for an encrypted private key the data will remain encrypted.
 * 
 * @return The private key data.
 * @throws KeyException If a private key cannot be found in the PEM file. 
 * @throws IOException If the PEM file cannot be read for any reason.
 */
public byte[] getPrivateKeyBytes() throws KeyException, IOException {
    final String methodName = "getPrivateKeyBytes";
    logger.entry(this, methodName);

    final String fileData = getPemFileData();

    Matcher m = KEY_PATTERN.matcher(fileData);
    final byte[] keyBytes;
    final String base64KeyDataStr;
    if (m.find()) {
        base64KeyDataStr = m.group(1);
    } else {
        m = ENCRYPTED_KEY_PATTERN.matcher(fileData);
        if (m.find()) {
            base64KeyDataStr = m.group(1);
        } else {
            final KeyException exception = new KeyException("Private key not found in PEM file: " + pemFile);
            logger.throwing(this, methodName, exception);
            throw exception;
        }
    }

    final ByteBuf base64KeyData = Unpooled.copiedBuffer(base64KeyDataStr, Charset.forName("US-ASCII"));
    final ByteBuf keyData = Base64.decode(base64KeyData);
    base64KeyData.release();
    keyBytes = new byte[keyData.readableBytes()];
    keyData.readBytes(keyBytes).release();

    logger.exit(this, methodName, keyBytes);

    return keyBytes;
}

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>/* w ww  .j  a v a 2  s . com*/
 *
 * <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.turo.pushy.apns.auth.ApnsKey.java

License:Open Source License

protected static byte[] decodeBase64EncodedString(final String base64EncodedString) {
    final ByteBuf base64EncodedByteBuf = Unpooled
            .wrappedBuffer(base64EncodedString.getBytes(StandardCharsets.US_ASCII));

    final ByteBuf decodedByteBuf = Base64.decode(base64EncodedByteBuf);
    final byte[] decodedBytes = new byte[decodedByteBuf.readableBytes()];

    decodedByteBuf.readBytes(decodedBytes);

    base64EncodedByteBuf.release();//from w w w. j a  v a  2s .c  o  m
    decodedByteBuf.release();

    return decodedBytes;
}

From source file:divconq.net.ssl.PemReader.java

License:Apache License

static ByteBuf[] readCertificates(File file) throws CertificateException {
    String content;//from ww w.  j  a va 2s.co  m
    try {
        content = readContent(file);
    } catch (IOException e) {
        throw new CertificateException("failed to read a file: " + file, e);
    }

    List<ByteBuf> certs = new ArrayList<ByteBuf>();
    Matcher m = CERT_PATTERN.matcher(content);
    int start = 0;
    for (;;) {
        if (!m.find(start)) {
            break;
        }

        ByteBuf base64 = Unpooled.copiedBuffer(m.group(1), CharsetUtil.US_ASCII);
        ByteBuf der = Base64.decode(base64);
        base64.release();
        certs.add(der);

        start = m.end();
    }

    if (certs.isEmpty()) {
        throw new CertificateException("found no certificates: " + file);
    }

    return certs.toArray(new ByteBuf[certs.size()]);
}

From source file:divconq.net.ssl.PemReader.java

License:Apache License

static ByteBuf readPrivateKey(File file) throws KeyException {
    String content;//from w  w w.  j av a 2  s .c om
    try {
        content = readContent(file);
    } catch (IOException e) {
        throw new KeyException("failed to read a file: " + file, e);
    }

    Matcher m = KEY_PATTERN.matcher(content);
    if (!m.find()) {
        throw new KeyException("found no private key: " + file);
    }

    ByteBuf base64 = Unpooled.copiedBuffer(m.group(1), CharsetUtil.US_ASCII);
    ByteBuf der = Base64.decode(base64);
    base64.release();
    return der;
}

From source file:net.minecrell.quartz.status.QuartzFavicon.java

License:MIT License

private static BufferedImage decode(String encoded) throws IOException {
    checkArgument(encoded.startsWith(FAVICON_PREFIX), "Unknown favicon format");
    ByteBuf base64 = Unpooled.copiedBuffer(encoded.substring(FAVICON_PREFIX.length()), Charsets.UTF_8);
    try {//from www  .  j a v a2 s  .  c  o  m
        ByteBuf buf = Base64.decode(base64);
        try {
            BufferedImage result = ImageIO.read(new ByteBufInputStream(buf));
            checkState(result.getWidth() == 64, "favicon must be 64 pixels wide");
            checkState(result.getHeight() == 64, "favicon must be 64 pixels high");
            return result;
        } finally {
            buf.release();
        }
    } finally {
        base64.release();
    }
}

From source file:org.apache.camel.component.netty4.http.handlers.HttpServerChannelHandler.java

License:Apache License

/**
 * Extracts the username and password details from the HTTP basic header Authorization.
 * <p/>//from w ww .  java2s .  c  o m
 * This requires that the <tt>Authorization</tt> HTTP header is provided, and its using Basic.
 * Currently Digest is <b>not</b> supported.
 *
 * @return {@link HttpPrincipal} with username and password details, or <tt>null</tt> if not possible to extract
 */
protected static HttpPrincipal extractBasicAuthSubject(HttpRequest request) {
    String auth = request.headers().get("Authorization");
    if (auth != null) {
        String constraint = ObjectHelper.before(auth, " ");
        if (constraint != null) {
            if ("Basic".equalsIgnoreCase(constraint.trim())) {
                String decoded = ObjectHelper.after(auth, " ");
                // the decoded part is base64 encoded, so we need to decode that
                ByteBuf buf = NettyConverter.toByteBuffer(decoded.getBytes());
                ByteBuf out = Base64.decode(buf);
                String userAndPw = out.toString(Charset.defaultCharset());
                String username = ObjectHelper.before(userAndPw, ":");
                String password = ObjectHelper.after(userAndPw, ":");
                HttpPrincipal principal = new HttpPrincipal(username, password);

                LOG.debug("Extracted Basic Auth principal from HTTP header: {}", principal);
                return principal;
            }
        }
    }
    return null;
}