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:org.ambraproject.wombat.controller.ArticleController.java

@RequestMapping(name = "uploadPreprintRevision", value = "/article/uploadPreprintRevision")
public String uploadPreprintRevision(HttpServletRequest request, Model model, @SiteParam Site site,
        @RequestParam("state") String state, @RequestParam("code") String code)
        throws IOException, URISyntaxException {
    final byte[] decodedState = Base64.getDecoder().decode(state);
    final String decodedJson = URLDecoder.decode(new String(decodedState), "UTF-8");
    Map<String, Object> stateJson = gson.fromJson(decodedJson, HashMap.class);

    String correspondingAuthorOrcidId = (String) stateJson.get("orcid_id");
    String authenticatedOrcidId = "";

    try {//from  w  w w.  ja  va  2s .  c om
        authenticatedOrcidId = orcidApi.getOrcidIdFromAuthorizationCode(site, code);
    } catch (OrcidAuthenticationTokenExpiredException | OrcidAuthenticationTokenReusedException e) {
        model.addAttribute("orcidAuthenticationError", e.getMessage());
    }

    boolean isError = true;
    if (correspondingAuthorOrcidId.equals(authenticatedOrcidId)) {
        model.addAttribute("orcidId", correspondingAuthorOrcidId);
        isError = false;
    } else if (!Strings.isNullOrEmpty(authenticatedOrcidId)) {
        model.addAttribute("orcidAuthenticationError",
                "ORCID IDs do not match. " + "Corresponding author ORCID ID must be used.");
    }

    if (isError) {
        final RequestedDoiVersion articleId = RequestedDoiVersion.of((String) stateJson.get("doi"));
        return renderArticle(request, model, site, articleId);
    } else {
        return site + "/ftl/article/uploadPreprintRevision";
    }
}

From source file:org.wso2.carbon.siddhi.editor.core.internal.EditorMicroservice.java

@GET
@Path("/workspace/listFilesInPath")
@Produces("application/json")
public Response listFilesInPath(@QueryParam("path") String path) {
    try {/*from  ww w. j  a v  a  2s .  c o  m*/
        return Response.status(Response.Status.OK)
                .entity(workspace.listDirectoryFiles(
                        new String(Base64.getDecoder().decode(path), Charset.defaultCharset())))
                .type(MediaType.APPLICATION_JSON).build();
    } catch (IOException e) {
        return Response.serverError().entity("failed." + e.getMessage()).build();
    } catch (Throwable ignored) {
        return Response.serverError().entity("failed").build();
    }

}

From source file:org.apache.nifi.registry.web.api.SecureLdapIT.java

@Test
public void testTokenGenerationWithIdentityProvider() throws Exception {

    // Given: the client and server have been configured correctly for LDAP authentication
    String expectedJwtPayloadJson = "{" + "\"sub\":\"nobel\"," + "\"preferred_username\":\"nobel\","
            + "\"iss\":\"LdapIdentityProvider\"," + "\"aud\":\"LdapIdentityProvider\"" + "}";
    String expectedAccessStatusJson = "{" + "\"identity\":\"nobel\"," + "\"anonymous\":false" + "}";

    // When: the /access/token/identity-provider endpoint is queried
    final String basicAuthCredentials = encodeCredentialsForBasicAuth("nobel", "password");
    final Response tokenResponse = client.target(createURL(tokenIdentityProviderPath)).request()
            .header("Authorization", "Basic " + basicAuthCredentials).post(null, Response.class);

    // Then: the server returns 200 OK with an access token
    assertEquals(201, tokenResponse.getStatus());
    String token = tokenResponse.readEntity(String.class);
    assertTrue(StringUtils.isNotEmpty(token));
    String[] jwtParts = token.split("\\.");
    assertEquals(3, jwtParts.length);//from  w  ww  .j a  v a 2  s. c o m
    String jwtPayload = new String(Base64.getDecoder().decode(jwtParts[1]), "UTF-8");
    JSONAssert.assertEquals(expectedJwtPayloadJson, jwtPayload, false);

    // When: the token is returned in the Authorization header
    final Response accessResponse = client.target(createURL("access")).request()
            .header("Authorization", "Bearer " + token).get(Response.class);

    // Then: the server acknowledges the client has access
    assertEquals(200, accessResponse.getStatus());
    String accessStatus = accessResponse.readEntity(String.class);
    JSONAssert.assertEquals(expectedAccessStatusJson, accessStatus, false);

}

From source file:org.wildfly.test.integration.elytron.http.SpnegoMechTestCase.java

@Test
public void testSuccess() throws Exception {

    final Krb5LoginConfiguration krb5Configuration = new Krb5LoginConfiguration(Utils.getLoginConfiguration());
    Configuration.setConfiguration(krb5Configuration);

    LoginContext lc = Utils.loginWithKerberos(krb5Configuration, "user1@WILDFLY.ORG", "password1");
    Subject.doAs(lc.getSubject(), (PrivilegedExceptionAction<Void>) () -> {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            GSSManager manager = GSSManager.getInstance();
            GSSName acceptorName = manager.createName("HTTP@localhost", GSSName.NT_HOSTBASED_SERVICE);
            GSSCredential credential = manager.createCredential(null, GSSCredential.DEFAULT_LIFETIME,
                    new Oid[] { KERBEROS_V5, SPNEGO }, GSSCredential.INITIATE_ONLY);
            GSSContext context = manager.createContext(acceptorName, KERBEROS_V5, credential,
                    GSSContext.INDEFINITE_LIFETIME);

            URI uri = new URI(url.toExternalForm() + "role1");
            byte[] message = new byte[0];

            for (int i = 0; i < 5; i++) { // prevent infinite loop - max 5 continuations
                message = context.initSecContext(message, 0, message.length);

                HttpGet request = new HttpGet(uri);
                request.setHeader(HEADER_AUTHORIZATION,
                        CHALLENGE_PREFIX + Base64.getEncoder().encodeToString(message));
                try (CloseableHttpResponse response = httpClient.execute(request)) {
                    int statusCode = response.getStatusLine().getStatusCode();

                    if (statusCode != SC_UNAUTHORIZED) {
                        assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
                        assertEquals("Unexpected content of HTTP response.", SimpleServlet.RESPONSE_BODY,
                                EntityUtils.toString(response.getEntity()));

                        // test cached identity
                        HttpGet request2 = new HttpGet(uri);
                        try (CloseableHttpResponse response2 = httpClient.execute(request2)) {
                            int statusCode2 = response.getStatusLine().getStatusCode();
                            assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode2);
                            assertEquals("Unexpected content of HTTP response.", SimpleServlet.RESPONSE_BODY,
                                    EntityUtils.toString(response2.getEntity()));
                        }/*  w  w  w  .j  a  va  2s . co m*/

                        return null;
                    }

                    String responseHeader = response.getFirstHeader(HEADER_WWW_AUTHENTICATE).getValue();
                    if (!responseHeader.startsWith(CHALLENGE_PREFIX))
                        Assert.fail("Invalid authenticate header");
                    message = Base64.getDecoder().decode(responseHeader.substring(CHALLENGE_PREFIX.length()));
                }
            }
            Assert.fail("Infinite unauthorized loop");
        }
        return null;
    });
}

From source file:com.machinepublishers.jbrowserdriver.StreamConnectionClient.java

private static SSLContext sslContext() {
    final String property = SettingsManager.settings().ssl();
    if (property != null && !property.isEmpty() && !"null".equals(property)) {
        if ("trustanything".equals(property)) {
            try {
                return SSLContexts.custom().loadTrustMaterial(KeyStore.getInstance(KeyStore.getDefaultType()),
                        new TrustStrategy() {
                            public boolean isTrusted(X509Certificate[] chain, String authType)
                                    throws CertificateException {
                                return true;
                            }// ww  w  .java2  s.co m
                        }).build();
            } catch (Throwable t) {
                LogsServer.instance().exception(t);
            }
        } else {
            try {
                String location = property;
                location = location.equals("compatible")
                        ? "https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt"
                        : location;
                File cachedPemFile = new File("./pemfile_cached");
                boolean remote = location.startsWith("https://") || location.startsWith("http://");
                if (remote && cachedPemFile.exists()
                        && (System.currentTimeMillis() - cachedPemFile.lastModified() < 48 * 60 * 60 * 1000)) {
                    location = cachedPemFile.getAbsolutePath();
                    remote = false;
                }
                String pemBlocks = null;
                if (remote) {
                    HttpURLConnection remotePemFile = (HttpURLConnection) StreamHandler
                            .defaultConnection(new URL(location));
                    remotePemFile.setRequestMethod("GET");
                    remotePemFile.connect();
                    pemBlocks = Util.toString(remotePemFile.getInputStream(), Util.charset(remotePemFile));
                    cachedPemFile.delete();
                    Files.write(Paths.get(cachedPemFile.getAbsolutePath()), pemBlocks.getBytes("utf-8"));
                } else {
                    pemBlocks = new String(Files.readAllBytes(Paths.get(new File(location).getAbsolutePath())),
                            "utf-8");
                }
                KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                keyStore.load(null);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                Matcher matcher = pemBlock.matcher(pemBlocks);
                boolean found = false;
                while (matcher.find()) {
                    String pemBlock = matcher.group(1).replaceAll("[\\n\\r]+", "");
                    ByteArrayInputStream byteStream = new ByteArrayInputStream(
                            Base64.getDecoder().decode(pemBlock));
                    java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) cf
                            .generateCertificate(byteStream);
                    String alias = cert.getSubjectX500Principal().getName("RFC2253");
                    if (alias != null && !keyStore.containsAlias(alias)) {
                        found = true;
                        keyStore.setCertificateEntry(alias, cert);
                    }
                }
                if (found) {
                    KeyManagerFactory keyManager = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    keyManager.init(keyStore, null);
                    TrustManagerFactory trustManager = TrustManagerFactory
                            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                    trustManager.init(keyStore);
                    SSLContext context = SSLContext.getInstance("TLS");
                    context.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
                    return context;
                }
            } catch (Throwable t) {
                LogsServer.instance().exception(t);
            }
        }
    }
    return SSLContexts.createSystemDefault();
}

From source file:org.apache.nifi.security.kms.CryptoUtils.java

/**
 * Returns a map containing the key IDs and the parsed key from a key provider definition file.
 * The values in the file are decrypted using the master key provided. If the file is missing or empty,
 * cannot be read, or if no valid keys are read, a {@link KeyManagementException} will be thrown.
 *
 * @param filepath  the key definition file path
 * @param masterKey the master key used to decrypt each key definition
 * @return a Map of key IDs to SecretKeys
 * @throws KeyManagementException if the file is missing or invalid
 *//*from   w  w  w. j  av a 2 s.c  o m*/
public static Map<String, SecretKey> readKeys(String filepath, SecretKey masterKey)
        throws KeyManagementException {
    Map<String, SecretKey> keys = new HashMap<>();

    if (StringUtils.isBlank(filepath)) {
        throw new KeyManagementException("The key provider file is not present and readable");
    }
    if (masterKey == null) {
        throw new KeyManagementException("The master key must be provided to decrypt the individual keys");
    }

    File file = new File(filepath);
    if (!file.exists() || !file.canRead()) {
        throw new KeyManagementException("The key provider file is not present and readable");
    }

    try (BufferedReader br = new BufferedReader(new FileReader(file))) {
        AESKeyedCipherProvider masterCipherProvider = new AESKeyedCipherProvider();

        String line;
        int l = 1;
        while ((line = br.readLine()) != null) {
            String[] components = line.split("=", 2);
            if (components.length != 2 || StringUtils.isAnyEmpty(components)) {
                logger.warn("Line " + l + " is not properly formatted -- keyId=Base64EncodedKey...");
            }
            String keyId = components[0];
            if (StringUtils.isNotEmpty(keyId)) {
                try {
                    byte[] base64Bytes = Base64.getDecoder().decode(components[1]);
                    byte[] ivBytes = Arrays.copyOfRange(base64Bytes, 0, IV_LENGTH);

                    Cipher masterCipher = null;
                    try {
                        masterCipher = masterCipherProvider.getCipher(EncryptionMethod.AES_GCM, masterKey,
                                ivBytes, false);
                    } catch (Exception e) {
                        throw new KeyManagementException(
                                "Error building cipher to decrypt FileBaseKeyProvider definition at "
                                        + filepath,
                                e);
                    }
                    byte[] individualKeyBytes = masterCipher
                            .doFinal(Arrays.copyOfRange(base64Bytes, IV_LENGTH, base64Bytes.length));

                    SecretKey key = new SecretKeySpec(individualKeyBytes, "AES");
                    logger.debug("Read and decrypted key for " + keyId);
                    if (keys.containsKey(keyId)) {
                        logger.warn("Multiple key values defined for " + keyId + " -- using most recent value");
                    }
                    keys.put(keyId, key);
                } catch (IllegalArgumentException e) {
                    logger.error("Encountered an error decoding Base64 for " + keyId + ": "
                            + e.getLocalizedMessage());
                } catch (BadPaddingException | IllegalBlockSizeException e) {
                    logger.error("Encountered an error decrypting key for " + keyId + ": "
                            + e.getLocalizedMessage());
                }
            }
            l++;
        }

        if (keys.isEmpty()) {
            throw new KeyManagementException("The provided file contained no valid keys");
        }

        logger.info("Read " + keys.size() + " keys from FileBasedKeyProvider " + filepath);
        return keys;
    } catch (IOException e) {
        throw new KeyManagementException("Error reading FileBasedKeyProvider definition at " + filepath, e);
    }

}

From source file:de.ii.xtraplatform.feature.provider.pgis.FeatureProviderPgis.java

private Config createSlickConfig(ConnectionInfo connectionInfo) {
    String password = connectionInfo.getPassword();
    try {/*from  ww w.  ja  va  2s.c  o  m*/
        password = new String(Base64.getDecoder().decode(password), Charsets.UTF_8);
    } catch (IllegalArgumentException e) {
        //ignore if not valid base64
    }

    return ConfigFactory.parseMap(ImmutableMap.<String, Object>builder()
            .put("profile", "slick.jdbc.PostgresProfile$")
            //.put("dataSourceClass", "org.postgresql.ds.PGSimpleDataSource")
            .put("db", ImmutableMap.<String, Object>builder().put("user", connectionInfo.getUser())
                    .put("password", password).put("dataSourceClass", "org.postgresql.ds.PGSimpleDataSource")
                    //.put("hikaricp.dataSourceClassName", "org.postgresql.ds.PGSimpleDataSource")
                    //.put("hikaricp.datasource.user", connectionInfo.getUser())
                    //.put("hikaricp.datasource.password", connectionInfo.getPassword())
                    .put("properties.serverName", connectionInfo.getHost())
                    .put("properties.databaseName", connectionInfo.getDatabase())
                    //.put("url", String.format("jdbc:postgresql://%s/%s", connectionInfo.getHost(), connectionInfo.getDatabase()))
                    .put("numThreads", 10).put("initializationFailFast", true).build())
            .build());
}

From source file:com.jrestless.aws.gateway.handler.GatewayRequestObjectHandlerIntTest.java

@Test
public void testBinaryBase64EncodingWithContentEncoding() throws IOException {
    DefaultGatewayRequest request = new DefaultGatewayRequestBuilder().httpMethod("GET").resource("/byte-array")
            .headers(ImmutableMap.of(HttpHeaders.ACCEPT_ENCODING, "gzip")).build();

    GatewayResponse response = handler.handleRequest(request, context);
    assertTrue(response.isIsBase64Encoded());
    byte[] bytes = Base64.getDecoder().decode(response.getBody());
    InputStream unzipStream = new GZIPInputStream(new ByteArrayInputStream(bytes));
    assertEquals("test", new String(toBytes(unzipStream)));
    assertNotNull(response.getHeaders().get(HttpHeaders.CONTENT_ENCODING));
}

From source file:org.codice.ddf.security.certificate.generator.PkiTools.java

/**
 * Convert a Java String to a byte array
 *
 * @param string PEM encoded bytes/*from w  ww. jav a 2  s .c o m*/
 * @return DER encoded bytes
 */
public static byte[] pemToDer(String string) {
    Validate.isTrue(string != null, "PEM string cannot be null");
    assert string != null;

    return Base64.getDecoder().decode(string);
}

From source file:org.codice.ddf.registry.federationadmin.impl.FederationAdmin.java

@Override
public String createLocalEntry(String base64EncodedXmlData) throws FederationAdminException {
    if (StringUtils.isBlank(base64EncodedXmlData)) {
        throw new FederationAdminException("Error creating local entry. String provided was blank.");
    }/*from   www. jav a  2  s .  c o  m*/

    String metacardId;
    try (InputStream xmlStream = new ByteArrayInputStream(Base64.getDecoder().decode(base64EncodedXmlData))) {
        Metacard metacard = getRegistryMetacardFromInputStream(xmlStream);
        metacard.setAttribute(new AttributeImpl(RegistryObjectMetacardType.REGISTRY_LOCAL_NODE, true));
        metacardId = federationAdminService.addRegistryEntry(metacard);
    } catch (IOException | IllegalArgumentException e) {
        throw new FederationAdminException("Error creating local entry. Couldn't decode string.", e);
    }
    return metacardId;
}