Example usage for java.util Base64 getDecoder

List of usage examples for java.util Base64 getDecoder

Introduction

In this page you can find the example usage for java.util Base64 getDecoder.

Prototype

public static Decoder getDecoder() 

Source Link

Document

Returns a Decoder that decodes using the Basic type base64 encoding scheme.

Usage

From source file:com.thoughtworks.go.server.newsecurity.utils.BasicAuthHeaderExtractor.java

public static UsernamePassword extractBasicAuthenticationCredentials(String authorizationHeader) {
    if (isBlank(authorizationHeader)) {
        return null;
    }//from   w ww. ja  v  a  2 s.c  o m

    final Matcher matcher = BASIC_AUTH_EXTRACTOR_PATTERN.matcher(authorizationHeader);
    if (matcher.matches()) {
        final String encodedCredentials = matcher.group(1);
        final byte[] decode = Base64.getDecoder().decode(encodedCredentials);
        String decodedCredentials = new String(decode, StandardCharsets.UTF_8);

        final int indexOfSeparator = decodedCredentials.indexOf(':');
        if (indexOfSeparator == -1) {
            throw new BadCredentialsException("Invalid basic authentication credentials specified in request.");
        }

        final String username = decodedCredentials.substring(0, indexOfSeparator);
        final String password = decodedCredentials.substring(indexOfSeparator + 1);

        return new UsernamePassword(username, password);
    }

    return null;
}

From source file:com.esri.geoportal.harvester.api.base.SimpleScrambler.java

/**
 * Decodes string.//from   ww  w  .j  av a2s  .  c om
 * @param encoded encoded string to decode
 * @return decoded string or <code>null</code> if error decoding string
 */
public static String decode(String encoded) {
    try {
        encoded = StringUtils.defaultIfEmpty(encoded, "");
        Base64.Decoder decoder = Base64.getDecoder();
        String crctxt = new String(decoder.decode(encoded), "UTF-8");
        if (crctxt.length() < 10) {
            return null;
        }
        long crc = Long.parseLong(StringUtils.trimToEmpty(crctxt.substring(0, 10)));
        String txt = crctxt.substring(10);
        CRC32 crC32 = new CRC32();
        crC32.update(txt.getBytes("UTF-8"));
        if (crc != crC32.getValue()) {
            return null;
        }
        return txt;
    } catch (NumberFormatException | UnsupportedEncodingException ex) {
        return null;
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.servlets.filters.FenixOAuthToken.java

public static FenixOAuthToken parse(String oAuthToken) throws FenixOAuthTokenException {

    if (StringUtils.isBlank(oAuthToken)) {
        throw new FenixOAuthTokenException();
    }/* w ww.  ja  v a  2  s . c o m*/

    String accessTokenDecoded = new String(Base64.getDecoder().decode(oAuthToken));
    String[] accessTokenBuilder = accessTokenDecoded.split(":");

    if (accessTokenBuilder.length != 2) {
        throw new FenixOAuthTokenException();
    }

    String appUserSessionExternalId = accessTokenBuilder[0];
    String accessToken = accessTokenBuilder[1];

    LOGGER.info("AccessToken: {}", accessTokenDecoded);
    LOGGER.info("[0] AppUserSesson ID: {}", appUserSessionExternalId);
    LOGGER.info("[1] Random: {}", accessTokenBuilder[1]);

    AppUserSession appUserSession = appUserSession(appUserSessionExternalId);

    if (appUserSession == null || !appUserSession.isActive()) {
        throw new FenixOAuthTokenException();
    }

    return new FenixOAuthToken(appUserSession, accessToken);
}

From source file:os4.serv.XMLTools.java

public static byte[] decodeByteArray(String xml) {
    return Base64.getDecoder().decode(xml);
}

From source file:Main.java

private static void serializeObjectAsXml(JsonObject objectJson, StringBuffer buff) {
    Iterator elements = objectJson.entrySet().iterator();
    while (elements.hasNext()) {
        Entry entry = (Entry) elements.next();
        Object key = entry.getKey();
        Object value = entry.getValue();
        if (value instanceof JsonObject) {
            buff.append(LT).append(key);
            serializeObjectAttributes((JsonObject) value, buff);
            buff.append(GT);//from w  w w . j  a  v a2  s .  c om
            serializeObjectAsXml((JsonObject) value, buff);
            buff.append(LTS).append(key).append(GT);
        } else if (value instanceof JsonArray) {
            serializeArrayAsXml(buff, key, value);
        } else if (value instanceof JsonPrimitive) {
            if (ATTR_TEXT.equals(key)) {
                buff.append(value.toString().replace(EQ, EMPTY));
            } else if (ATTR_CDATA.equals(key)) {
                buff.append(CDATA_OPEN)
                        .append(new String(Base64.getDecoder().decode(value.toString().replace(EQ, EMPTY))))
                        .append(CDATA_CLOSE);
            } else {
                if (!key.toString().startsWith("-")) {
                    buff.append(LT).append(key.toString()).append(GT)
                            .append(value.toString().replace(EQ, EMPTY)).append(LTS).append(key.toString())
                            .append(GT);
                }
            }
        } else {
            System.err.println("ERROR: unhandled element");
        }
    }
}

From source file:it.infn.mw.iam.util.ssh.RSAPublicKeyUtils.java

private static String buildSHA256Fingerprint(String key) throws InvalidSshKeyException {

    String fingerprint = null;//from   w ww  . j  a v a 2  s .  c  o m

    try {

        byte[] decodedKey = Base64.getDecoder().decode(key);
        byte[] digest = MessageDigest.getInstance(MessageDigestAlgorithms.SHA_256).digest(decodedKey);
        fingerprint = Base64.getEncoder().encodeToString(digest);

    } catch (Exception e) {

        throw new InvalidSshKeyException("Error during fingerprint generation: RSA key is not base64 encoded",
                e);
    }

    return fingerprint;
}

From source file:br.com.localizae.model.service.FileServiceLocal.java

@Override
public void upload(File file) throws Exception {
    Connection conn = null;//from  w ww. ja  v  a 2  s . c om

    try {
        conn = ConnectionManager.getInstance().getConnection();
        FileDAO dao = new FileDAO();

        dao.create(conn, file);

        if (!file.getBase64().isEmpty()) {
            byte[] data = Base64.getDecoder().decode(file.getBase64());
            try (OutputStream stream = new FileOutputStream(Constantes.PATH_FILE + file.getUri())) {
                stream.write(data);
            }
        } else if (file.getFile().length != 0) {
            FileOutputStream fos = new FileOutputStream(Constantes.PATH_FILE + file.getUri());
            fos.write(file.getFile());

            fos.close();
        } else {
            throw new IllegalArgumentException(
                    " necessrio o envio do arquivo como array de byte ou como base64.");
        }

        conn.commit();
    } catch (Exception e) {
        conn.rollback();

        throw e;
    } finally {
        conn.close();
    }
}

From source file:org.khannex.action.Command.java

public void addParam(String value) {
    if (value != null && !value.trim().isEmpty()) {
        if (org.apache.commons.codec.binary.Base64.isBase64(value.getBytes())) {
            params.add(new String(Base64.getDecoder().decode(value)));
        } else {//ww  w  .  j a va  2  s  .co m
            params.add(value);
        }
    }
}

From source file:com.searchcode.app.util.AESEncryptor.java

public String decryptFromBase64String(String cipherText) throws Exception {
    byte[] plainText = this.decrypt(Base64.getDecoder().decode(cipherText));
    return new String(plainText);
}

From source file:tk.jomp16.plugin.codecutils.ui.EncodeDecodePanel.java

public EncodeDecodePanel(boolean encode) {
    base64Button.addActionListener(e -> {
        if (encode) {
            if (inputTextArea.getText().length() != 0)
                outputTextArea/*from   w  w  w .  j  av  a 2 s.  co m*/
                        .setText(new String(Base64.getEncoder().encode(inputTextArea.getText().getBytes())));
        } else {
            if (inputTextArea.getText().length() != 0)
                outputTextArea.setText(new String(Base64.getDecoder().decode(inputTextArea.getText())));
        }
    });

    hexadecimalButton.addActionListener(e -> {
        if (encode) {
            if (inputTextArea.getText().length() != 0)
                outputTextArea.setText(String.valueOf(Hex.encodeHex(inputTextArea.getText().getBytes())));
        } else {
            if (inputTextArea.getText().length() != 0) {
                try {
                    outputTextArea.setText(new String(Hex.decodeHex(inputTextArea.getText().toCharArray())));
                } catch (DecoderException e1) {
                    e1.printStackTrace();
                }
            }
        }
    });

    binaryButton.addActionListener(e -> {
        if (encode) {
            if (inputTextArea.getText().length() != 0)
                outputTextArea.setText(CodecUtils.getBinary(inputTextArea.getText()));
        } else {
            if (inputTextArea.getText().length() != 0)
                outputTextArea.setText(
                        new String(BinaryCodec.fromAscii(inputTextArea.getText().replace(" ", "").getBytes())));
        }
    });
}