Example usage for java.util Base64 getEncoder

List of usage examples for java.util Base64 getEncoder

Introduction

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

Prototype

public static Encoder getEncoder() 

Source Link

Document

Returns a Encoder that encodes using the Basic type base64 encoding scheme.

Usage

From source file:at.medevit.elexis.emediplan.core.internal.EMediplanServiceImpl.java

private String getEncodedLogo() {
    try (InputStream input = getClass().getResourceAsStream("/rsc/img/Logo_Full.jpeg");
            ByteArrayOutputStream output = new ByteArrayOutputStream()) {
        IOUtils.copy(input, output);/*from  w w w  .  j av a  2  s. c  o  m*/
        return "data:image/jpg;base64," + Base64.getEncoder().encodeToString(output.toByteArray());
    } catch (IOException e) {
        LoggerFactory.getLogger(getClass()).error("Error encoding logo", e);
    }
    return "";
}

From source file:org.kontalk.client.KonMessageListener.java

public static MessageContent parseMessageContent(Message m) {
    // default body
    String plainText = m.getBody() != null ? m.getBody() : "";

    // encryption extension (RFC 3923), decrypted later
    String encryptedContent = "";
    PacketExtension encryptionExt = m.getExtension(E2EEncryption.ELEMENT_NAME, E2EEncryption.NAMESPACE);
    if (encryptionExt != null && encryptionExt instanceof E2EEncryption) {
        if (m.getBody() != null)
            LOGGER.info("message contains encryption and body (ignoring body): " + m.getBody());
        E2EEncryption encryption = (E2EEncryption) encryptionExt;
        encryptedContent = Base64.getEncoder().encodeToString(encryption.getData());
    }/*  w ww .  j  a v  a 2 s .c o  m*/

    // Out of Band Data: a URI to a file
    Optional<Attachment> optAttachment = Optional.empty();
    PacketExtension oobExt = m.getExtension(OutOfBandData.ELEMENT_NAME, OutOfBandData.NAMESPACE);
    if (oobExt != null && oobExt instanceof OutOfBandData) {
        LOGGER.info("Parsing Out of Band Data");
        OutOfBandData oobData = (OutOfBandData) oobExt;
        Attachment attachment = new MessageContent.Attachment(oobData.getUrl(),
                oobData.getMime() != null ? oobData.getMime() : "", oobData.getLength(), oobData.isEncrypted());
        optAttachment = Optional.of(attachment);
    }
    return new MessageContent(plainText, optAttachment, encryptedContent);
}

From source file:com.amazonaws.sample.entitlement.authorization.CognitoIdentityAuthorizationHandler.java

/**
 * @param authorization/*from w  w  w .jav a2s. co  m*/
 *     An authorization string. The first part of the string must match one of the keys in AUTHORIZATION_TYPES
 *     The remainder of the string must be an OAuth2 or OpenId access token.
 * @return an Identity containing the IdentityID from Amazon Cognito, and email, and name from the third-party
 * @throws AuthorizationException
 */
@Override
public Identity processAuthorization(String authorization) throws AuthorizationException {
    String authorizationType;
    Identity thirdPartyIdentity;
    String trimmedAuthorization = authorization.trim();
    try {
        String[] splitString = trimmedAuthorization.split("\\s");
        authorizationType = splitString[0];
    } catch (Exception e) {
        throw new AuthorizationException("Don't know how to handle authorization.");
    }
    if (!AUTHORIZATION_TYPES.containsKey(authorizationType)) {
        throw new AuthorizationException("Don't know how to handle authorization type: " + authorizationType);
    }
    Util.checkAuthorizationString(authorizationType, authorization);
    // Verify that the access token is valid and belongs to us.
    // If the access token can be verified and also profile information can be retrieved with one call to the oauth2
    // provider then return an Identity object here, otherwise return null and a separate call will be made
    // in getIdentity to retrieve the profile information and create an Identity object.
    switch (authorizationType) {
    case "FacebookOAuth2":
        thirdPartyIdentity = facebookAuthorizationHandler.processAuthorization(authorization);
        log.info("Email from Facebook: " + thirdPartyIdentity.getEmail());
        break;
    case "GoogleOAuth2":
        thirdPartyIdentity = googleAuthorizationHandler.processAuthorization(authorization);
        break;
    case "AmazonOAuth2":
        thirdPartyIdentity = loginWithAmazonAuthorizationHandler.processAuthorization(authorization);
        log.info("Email from Amazon: " + thirdPartyIdentity.getEmail());
        break;
    default:
        throw new AuthorizationException("Don't know how to handle authorization.");
    }
    try {
        Instant fifteenMinutesFromNow = Instant.now().plus(15, ChronoUnit.MINUTES);
        String base64EncEmail = Base64.getEncoder().withoutPadding()
                .encodeToString(thirdPartyIdentity.getEmail().getBytes("utf-8"));
        GetOpenIdTokenForDeveloperIdentityRequest req = new GetOpenIdTokenForDeveloperIdentityRequest();
        req.setIdentityPoolId(awsCognitoIdentityPool);
        req.addLoginsEntry(awsCognitoDeveloperProviderName, base64EncEmail);
        GetOpenIdTokenForDeveloperIdentityResult res = cognitoIdentityClient
                .getOpenIdTokenForDeveloperIdentity(req);
        thirdPartyIdentity.setId(res.getIdentityId());
        thirdPartyIdentity.setToken(res.getToken());
        thirdPartyIdentity.setExpires(fifteenMinutesFromNow.toEpochMilli());
    } catch (UnsupportedEncodingException e) {
        throw new AuthorizationException("Don't know how to handle authorization.");
    }
    return thirdPartyIdentity;
}

From source file:org.structr.websocket.command.LoginCommand.java

@Override
public void processMessage(final WebSocketMessage webSocketData) throws FrameworkException {

    final App app = StructrApp.getInstance();

    try (final Tx tx = app.tx(true, true, true)) {

        final String username = webSocketData.getNodeDataStringValue("username");
        final String password = webSocketData.getNodeDataStringValue("password");
        final String twoFactorToken = webSocketData.getNodeDataStringValue("twoFactorToken");
        final String twoFactorCode = webSocketData.getNodeDataStringValue("twoFactorCode");
        Principal user = null;/*from   www . jav  a  2  s . co  m*/

        try {

            Authenticator auth = getWebSocket().getAuthenticator();

            if (StringUtils.isNotEmpty(twoFactorToken)) {

                user = AuthHelper.getUserForTwoFactorToken(twoFactorToken);

            } else if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {

                user = auth.doLogin(getWebSocket().getRequest(), username, password);

                tx.setSecurityContext(SecurityContext.getInstance(user, AccessMode.Backend));
            }

            if (user != null) {

                final boolean twoFactorAuthenticationSuccessOrNotNecessary = AuthHelper
                        .handleTwoFactorAuthentication(user, twoFactorCode, twoFactorToken,
                                getWebSocket().getRequest().getRemoteAddr());

                if (twoFactorAuthenticationSuccessOrNotNecessary) {

                    String sessionId = webSocketData.getSessionId();
                    if (sessionId == null) {

                        logger.debug("Unable to login {}: No sessionId found",
                                new Object[] { username, password });
                        getWebSocket().send(MessageBuilder.status().code(403).build(), true);

                    } else {

                        sessionId = SessionHelper.getShortSessionId(sessionId);

                        // Clear possible existing sessions
                        SessionHelper.clearSession(sessionId);
                        user.addSessionId(sessionId);

                        AuthHelper.sendLoginNotification(user);

                        // store token in response data
                        webSocketData.getNodeData().clear();
                        webSocketData.setSessionId(sessionId);
                        webSocketData.getNodeData().put("username", user.getProperty(AbstractNode.name));

                        // authenticate socket
                        getWebSocket().setAuthenticated(sessionId, user);

                        tx.setSecurityContext(getWebSocket().getSecurityContext());

                        // send data..
                        getWebSocket().send(webSocketData, false);
                    }
                }

            } else {

                getWebSocket().send(MessageBuilder.status().code(401).build(), true);

            }

        } catch (PasswordChangeRequiredException | TooManyFailedLoginAttemptsException
                | TwoFactorAuthenticationFailedException | TwoFactorAuthenticationTokenInvalidException ex) {

            logger.info(ex.getMessage());
            getWebSocket().send(MessageBuilder.status().message(ex.getMessage()).code(401)
                    .data("reason", ex.getReason()).build(), true);

        } catch (TwoFactorAuthenticationRequiredException ex) {

            logger.debug(ex.getMessage());

            final MessageBuilder msg = MessageBuilder.status().message(ex.getMessage()).data("token",
                    ex.getNextStepToken());

            if (ex.showQrCode()) {

                try {

                    final Map<String, Object> hints = new HashMap();
                    hints.put("MARGIN", 0);
                    hints.put("ERROR_CORRECTION", "M");

                    final String qrdata = Base64.getEncoder()
                            .encodeToString(BarcodeFunction
                                    .getQRCode(Principal.getTwoFactorUrl(user), "QR_CODE", 200, 200, hints)
                                    .getBytes("ISO-8859-1"));

                    msg.data("qrdata", qrdata);

                } catch (UnsupportedEncodingException uee) {
                    logger.warn("Charset ISO-8859-1 not supported!?", uee);
                }
            }

            getWebSocket().send(msg.code(202).build(), true);

        } catch (AuthenticationException e) {

            logger.info("Unable to login {}, probably wrong password", username);
            getWebSocket().send(MessageBuilder.status().code(403).build(), true);

        } catch (FrameworkException fex) {

            logger.warn("Unable to execute command", fex);
            getWebSocket().send(MessageBuilder.status().code(401).build(), true);

        }

        tx.success();
    }
}

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

@Test
public void testTokenGenerationAndAccessStatus() throws Exception {

    // Note: this test intentionally does not use the token generated
    // for nifiadmin by the @Before method

    // Given: the client and server have been configured correctly for Kerberos SPNEGO authentication
    String expectedJwtPayloadJson = "{" + "\"sub\":\"kerberosUser@LOCALHOST\","
            + "\"preferred_username\":\"kerberosUser@LOCALHOST\","
            + "\"iss\":\"KerberosSpnegoIdentityProvider\"" + "}";
    String expectedAccessStatusJson = "{" + "\"identity\":\"kerberosUser@LOCALHOST\"," + "\"anonymous\":false}";

    // When: the /access/token/kerberos endpoint is accessed with no credentials
    final Response tokenResponse1 = client.target(createURL("/access/token/kerberos")).request().post(null,
            Response.class);

    // Then: the server returns 401 Unauthorized with an authenticate challenge header
    assertEquals(401, tokenResponse1.getStatus());
    assertNotNull(tokenResponse1.getHeaders().get("www-authenticate"));
    assertEquals(1, tokenResponse1.getHeaders().get("www-authenticate").size());
    assertEquals("Negotiate", tokenResponse1.getHeaders().get("www-authenticate").get(0));

    // When: the /access/token/kerberos endpoint is accessed again with an invalid ticket
    String invalidTicket = new String(
            java.util.Base64.getEncoder().encode(invalidKerberosTicket.getBytes(Charset.forName("UTF-8"))));
    final Response tokenResponse2 = client.target(createURL("/access/token/kerberos")).request()
            .header("Authorization", "Negotiate " + invalidTicket).post(null, Response.class);

    // Then: the server returns 401 Unauthorized
    assertEquals(401, tokenResponse2.getStatus());

    // When: the /access/token/kerberos endpoint is accessed with a valid ticket
    String validTicket = new String(
            Base64.getEncoder().encode(validKerberosTicket.getBytes(Charset.forName("UTF-8"))));
    final Response tokenResponse3 = client.target(createURL("/access/token/kerberos")).request()
            .header("Authorization", "Negotiate " + validTicket).post(null, Response.class);

    // Then: the server returns 200 OK with a JWT in the body
    assertEquals(201, tokenResponse3.getStatus());
    String token = tokenResponse3.readEntity(String.class);
    assertTrue(StringUtils.isNotEmpty(token));
    String[] jwtParts = token.split("\\.");
    assertEquals(3, jwtParts.length);//from   ww  w.j av  a  2  s . com
    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.wso2.identity.scenarios.commons.HTTPCommonClient.java

public String getBasicAuthorizeHeader(String key, String secret) {

    Base64.Encoder encoder = Base64.getEncoder();
    String encodedHeader = encoder.encodeToString(String.join(":", key, secret).getBytes());
    return String.join(" ", BASIC, encodedHeader);
}

From source file:org.wso2.is.portal.user.client.api.ChallengeQuestionManagerClientServiceImpl.java

@Override
public List<ChallengeQuestion> getAllChallengeQuestionsForUser(String userUniqueId)
        throws IdentityStoreException, UserNotFoundException, IdentityRecoveryException {

    if (challengeQuestionManager == null || realmService == null) {
        throw new IdentityRecoveryException("Challenge question manager or Realm service is not available.");
    }//  w  ww .  j  a  v  a 2  s  . co m

    List<UserChallengeAnswer> userChallengeAnswers = challengeQuestionManager
            .getChallengeAnswersOfUser(userUniqueId);

    return userChallengeAnswers.stream().map(UserChallengeAnswer::getQuestion).map(challengeQuestion -> {
        challengeQuestion
                .setQuestionSetId(
                        new String(
                                Base64.getEncoder()
                                        .encode(challengeQuestion.getQuestionSetId()
                                                .getBytes(Charset.forName("UTF-8"))),
                                Charset.forName("UTF-8")));
        return challengeQuestion;
    }).collect(Collectors.toList());
}

From source file:org.apache.syncope.core.logic.SAML2IdPLogic.java

private List<SAML2IdPTO> importIdPs(final InputStream input) throws Exception {
    List<EntityDescriptor> idpEntityDescriptors = new ArrayList<>();

    Element root = OpenSAMLUtil.getParserPool().parse(new InputStreamReader(input)).getDocumentElement();
    if (SAMLConstants.SAML20MD_NS.equals(root.getNamespaceURI())
            && EntityDescriptor.DEFAULT_ELEMENT_LOCAL_NAME.equals(root.getLocalName())) {

        idpEntityDescriptors.add((EntityDescriptor) OpenSAMLUtil.fromDom(root));
    } else if (SAMLConstants.SAML20MD_NS.equals(root.getNamespaceURI())
            && EntitiesDescriptor.DEFAULT_ELEMENT_LOCAL_NAME.equals(root.getLocalName())) {

        NodeList children = root.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (SAMLConstants.SAML20MD_NS.equals(child.getNamespaceURI())
                    && EntityDescriptor.DEFAULT_ELEMENT_LOCAL_NAME.equals(child.getLocalName())) {

                NodeList descendants = child.getChildNodes();
                for (int j = 0; j < descendants.getLength(); j++) {
                    Node descendant = descendants.item(j);
                    if (SAMLConstants.SAML20MD_NS.equals(descendant.getNamespaceURI())
                            && IDPSSODescriptor.DEFAULT_ELEMENT_LOCAL_NAME.equals(descendant.getLocalName())) {

                        idpEntityDescriptors.add((EntityDescriptor) OpenSAMLUtil.fromDom((Element) child));
                    }//w  ww .j av a2 s.co  m
                }
            }
        }
    }

    List<SAML2IdPTO> result = new ArrayList<>(idpEntityDescriptors.size());
    for (EntityDescriptor idpEntityDescriptor : idpEntityDescriptors) {
        SAML2IdPTO idpTO = new SAML2IdPTO();
        idpTO.setEntityID(idpEntityDescriptor.getEntityID());
        idpTO.setName(idpEntityDescriptor.getEntityID());
        idpTO.setUseDeflateEncoding(false);

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            saml2rw.write(new OutputStreamWriter(baos), idpEntityDescriptor, false);
            idpTO.setMetadata(Base64.getEncoder().encodeToString(baos.toByteArray()));
        }

        ItemTO connObjectKeyItem = new ItemTO();
        connObjectKeyItem.setIntAttrName("username");
        connObjectKeyItem.setExtAttrName("NameID");
        idpTO.setConnObjectKeyItem(connObjectKeyItem);

        SAML2IdPEntity idp = cache.put(idpEntityDescriptor, idpTO);
        if (idp.getSSOLocation(SAML2BindingType.POST) != null) {
            idpTO.setBindingType(SAML2BindingType.POST);
        } else if (idp.getSSOLocation(SAML2BindingType.REDIRECT) != null) {
            idpTO.setBindingType(SAML2BindingType.REDIRECT);
        } else {
            throw new IllegalArgumentException(
                    "Neither POST nor REDIRECT artifacts supported by " + idp.getId());
        }

        result.add(idpTO);
    }

    return result;
}

From source file:io.kodokojo.bdd.stage.AccessRestWhen.java

private void connectToWebSocket(UserInfo requesterUserInfo, boolean expectSuccess) {

    try {/*from w  w  w  .  j  a v a 2 s  .c o  m*/

        final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build();

        ClientManager client = ClientManager.createClient();
        if (requesterUserInfo != null) {
            client.getProperties().put(ClientProperties.CREDENTIALS,
                    new Credentials(requesterUserInfo.getUsername(), requesterUserInfo.getPassword()));

        }

        String uriStr = "ws://" + restEntryPointHost + ":" + restEntryPointPort + "/api/v1/event";
        CountDownLatch messageLatch = new CountDownLatch(1);
        Session session = client.connectToServer(new Endpoint() {
            @Override
            public void onOpen(Session session, EndpointConfig config) {

                session.addMessageHandler(new MessageHandler.Whole<String>() {
                    @Override
                    public void onMessage(String messsage) {
                        GsonBuilder builder = new GsonBuilder();
                        builder.registerTypeAdapter(WebSocketMessage.class, new WebSocketMessageGsonAdapter());
                        Gson gson = builder.create();
                        WebSocketMessage response = gson.fromJson(messsage, WebSocketMessage.class);
                        LOGGER.info("Receive WebSocket mesage : {}", response);
                        if ("user".equals(response.getEntity()) && "authentication".equals(response.getAction())
                                && response.getData().has("message") && ((JsonObject) response.getData())
                                        .getAsJsonPrimitive("message").getAsString().equals("success")) {
                            receiveWebSocketWelcome = true;
                            messageLatch.countDown();
                        } else {
                            receiveWebSocketWelcome = false;
                        }
                    }

                });
                if (requesterUserInfo != null) {
                    try {
                        String aggregateCredentials = String.format("%s:%s", requesterUserInfo.getUsername(),
                                requesterUserInfo.getPassword());
                        String encodedCredentials = Base64.getEncoder()
                                .encodeToString(aggregateCredentials.getBytes());
                        session.getBasicRemote()
                                .sendText("{\n" + "  \"entity\": \"user\",\n"
                                        + "  \"action\": \"authentication\",\n" + "  \"data\": {\n"
                                        + "    \"authorization\": \"Basic " + encodedCredentials + "\"\n"
                                        + "  }\n" + "}");
                    } catch (IOException e) {
                        fail(e.getMessage());
                    }
                }
            }

        }, cec, new URI(uriStr));
        messageLatch.await(10, TimeUnit.SECONDS);
        session.close();
    } catch (Exception e) {
        if (expectSuccess) {
            fail(e.getMessage());
        } else {
            receiveWebSocketWelcome = false;
        }
    }
}