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:org.onosproject.protocol.rest.ctl.RestSBControllerImpl.java

@Override
public boolean patch(DeviceId device, String request, InputStream payload, String mediaType) {
    try {//  w  w w .jav a 2 s.  c  om
        log.debug("Url request {} ", getUrlString(device, request));
        HttpPatch httprequest = new HttpPatch(getUrlString(device, request));
        if (deviceMap.get(device).username() != null) {
            String pwd = deviceMap.get(device).password() == null ? ""
                    : COLON + deviceMap.get(device).password();
            String userPassword = deviceMap.get(device).username() + pwd;
            String base64string = Base64.getEncoder()
                    .encodeToString(userPassword.getBytes(StandardCharsets.UTF_8));
            httprequest.addHeader(AUTHORIZATION_PROPERTY, BASIC_AUTH_PREFIX + base64string);
        }
        if (payload != null) {
            StringEntity input = new StringEntity(IOUtils.toString(payload, StandardCharsets.UTF_8));
            input.setContentType(mediaType);
            httprequest.setEntity(input);
        }
        CloseableHttpClient httpClient;
        if (deviceMap.containsKey(device) && deviceMap.get(device).protocol().equals(HTTPS)) {
            httpClient = getApacheSslBypassClient();
        } else {
            httpClient = HttpClients.createDefault();
        }
        int responseStatusCode = httpClient.execute(httprequest).getStatusLine().getStatusCode();
        return checkStatusCode(responseStatusCode);
    } catch (IOException | NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        log.error("Cannot do PATCH {} request on device {}", request, device, e);
    }
    return false;
}

From source file:org.codice.ddf.security.idp.client.LogoutRequestService.java

private Response getSamlpPostLogoutRequest(String relayState, LogoutRequest logoutRequest)
        throws SimpleSign.SignatureException, WSSecurityException {
    LOGGER.debug("Configuring SAML LogoutRequest for POST.");
    Document doc = DOMUtils.createDocument();
    doc.appendChild(doc.createElement("root"));
    LOGGER.debug("Signing SAML POST LogoutRequest.");
    simpleSign.signSamlObject(logoutRequest);
    LOGGER.debug("Converting SAML Request to DOM");
    String assertionResponse = DOM2Writer.nodeToString(OpenSAMLUtil.toDom(logoutRequest, doc));
    String encodedSamlRequest = Base64.getEncoder()
            .encodeToString(assertionResponse.getBytes(StandardCharsets.UTF_8));
    String singleLogoutLocation = idpMetadata.getSingleLogoutLocation();
    String submitFormUpdated = String.format(submitForm, singleLogoutLocation, SAML_REQUEST, encodedSamlRequest,
            relayState);//from w w  w  .j  av a 2 s .c om
    Response.ResponseBuilder ok = Response.ok(submitFormUpdated);
    return ok.build();
}

From source file:org.jboss.as.test.integration.security.common.CoreUtils.java

public static String hash(String target, String algorithm, Coding coding) {
    MessageDigest md = null;/*  w w w .  ja  v  a  2s  .  c o  m*/
    try {
        md = MessageDigest.getInstance(algorithm);
    } catch (Exception e) {
        e.printStackTrace();
    }
    byte[] bytes = target.getBytes(StandardCharsets.UTF_8);
    byte[] byteHash = md.digest(bytes);

    String encodedHash = null;

    switch (coding) {
    case BASE_64:
        encodedHash = Base64.getEncoder().encodeToString(byteHash);
        break;
    case HEX:
        encodedHash = toHex(byteHash);
        break;
    default:
        throw new IllegalArgumentException("Unsuported coding:" + coding.name());
    }

    return encodedHash;
}

From source file:authorize.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Logger logger = LogManager.getLogger(authorize.class);
    logger.trace("START");
    PrintWriter out = response.getWriter();
    Connection conn = null;//from www.j  a  v a  2 s .c  om
    Statement stmt = null;
    ResultSet rs = null;
    HttpSession session = request.getSession(false);
    String response_type = request.getParameter("response_type");
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String prompt = request.getParameter("prompt");
    String login_hint = request.getParameter("login_hint");
    String max_age = request.getParameter("max_age");
    String client_id = request.getParameter("client_id");
    String redirect_uri = request.getParameter("redirect_uri");
    String scope = request.getParameter("scope");
    String state = request.getParameter("state");
    String nonce = request.getParameter("nonce");
    String consent = request.getParameter("consent");
    String client_scope = null;
    String access_token = null;
    String id_token = null;
    String passwd = null;
    String db_redirect_uri = null;
    String path = null;
    String sql = null;
    String uri = null;
    String issuer = null;
    String keyname = null;
    String kit = "public.key";
    boolean redirect_uri_check = true;
    int access_token_time = 60;
    if (scope == null) {
        scope = "openid";
    } else if (scope.equals("consent")) {
        scope = null;
        if (null != request.getParameter("openid")) {
            scope = "openid";
            if (null != request.getParameter("profile"))
                scope += " profile";
            if (null != request.getParameter("email"))
                scope += " email";
            if (null != request.getParameter("phone"))
                scope += " phone";
            if (null != request.getParameter("address"))
                scope += " address";
        }
    }
    logger.trace(scope);
    if (prompt != null && prompt.contains("login") && consent == null && session != null)
        session.invalidate();
    try {
        ServletContext context = this.getServletContext();
        path = context.getRealPath("/WEB-INF/oauth2");
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
        conn = DriverManager.getConnection("jdbc:derby:" + path);
        stmt = conn.createStatement();
        logger.trace("connect()");
        sql = "SELECT scope,redirect_uri FROM client WHERE client_id='" + client_id + "'";
        rs = stmt.executeQuery(sql);
        while (rs.next()) {
            client_scope = rs.getString("scope");
            db_redirect_uri = rs.getString("redirect_uri");
        }
        logger.trace(sql);
        if (redirect_uri == null)
            redirect_uri = db_redirect_uri;
        sql = "SELECT passwd FROM profile WHERE uid='" + username + "'";
        rs = stmt.executeQuery(sql);
        while (rs.next()) {
            passwd = rs.getString("passwd");
        }
        logger.trace(sql);
        path = context.getRealPath("/WEB-INF/config.json");
        InputStream input = new FileInputStream(path);
        JsonParser parser = Json.createParser(input);
        while (parser.hasNext()) {
            JsonParser.Event event = parser.next();
            switch (event) {
            case KEY_NAME:
                keyname = parser.getString();
                break;
            case VALUE_NUMBER:
                access_token_time = parser.getInt();
                break;
            case VALUE_TRUE:
                redirect_uri_check = true;
                break;
            case VALUE_FALSE:
                redirect_uri_check = false;
                break;
            case VALUE_STRING:
                if (keyname.equals("issuer"))
                    issuer = parser.getString();
                if (keyname.equals("kit"))
                    kit = parser.getString();
                break;
            default:
                break;
            }
        }
        java.util.Date dt = new java.util.Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(dt);
        if (client_scope != null && passwd != null) {
            byte[] cipher_byte;
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(password.getBytes());
            cipher_byte = md.digest();
            String sha256_password = Base64.getEncoder().withoutPadding().encodeToString(cipher_byte);
            StringTokenizer strToken = new StringTokenizer(scope, " ");
            while (strToken.hasMoreTokens()) {
                String token = strToken.nextToken().toString();
                logger.trace(token);
                if (!client_scope.contains(token))
                    throw new Exception("out of scope");
            }
            if (passwd.contains(sha256_password)
                    && (!redirect_uri_check || db_redirect_uri.equals(redirect_uri))) {
                if (prompt != null && prompt.contains("consent") && !consent.equals("false")) {
                    username = "null";
                    password = "null";
                    consent = "true";
                    throw new Exception("consent is true");
                }
                access_token = RandomStringUtils.randomAlphanumeric(32);
                logger.trace(access_token);
                sql = "insert into session(uid,access_token,issued_in,scope,client_id) values ('" + username
                        + "','" + access_token + "','" + currentTime + "','" + scope + "','" + client_id + "')";
                stmt.executeUpdate(sql);
                md.update(access_token.getBytes());
                cipher_byte = md.digest();
                byte[] half_cipher_byte = Arrays.copyOf(cipher_byte, (cipher_byte.length / 2));
                String at_hash = Base64.getEncoder().withoutPadding().encodeToString(half_cipher_byte);
                path = context.getRealPath("/WEB-INF/private.der");
                File filePrivateKey = new File(path);
                FileInputStream fis = new FileInputStream(path);
                byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
                fis.read(encodedPrivateKey);
                fis.close();
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
                PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
                Calendar exp = Calendar.getInstance();
                exp.add(Calendar.SECOND, access_token_time);
                if (nonce == null || nonce.equals("null")) {
                    if (response_type.contains("id_token")) {
                        uri = redirect_uri;
                        uri += "#error=invalid_request&error_description=nonce%20is%20not%20valid.";
                        response.sendRedirect(uri);
                        logger.info(uri);
                        return;
                    }
                } else {
                    id_token = Jwts.builder().setHeaderParam("alg", "RS256").setHeaderParam("typ", "JWT")
                            .setHeaderParam("kid", kit).setIssuer(issuer).claim("at_hash", at_hash)
                            .setSubject(username).setAudience(client_id).claim("nonce", nonce)
                            .setSubject(username).setExpiration(exp.getTime())
                            .setIssuedAt(Calendar.getInstance().getTime())
                            .claim("auth_time",
                                    String.valueOf(Calendar.getInstance().getTime().getTime()).substring(0, 10))
                            .signWith(SignatureAlgorithm.RS256, privateKey).compact();
                    logger.trace(id_token);
                }
                uri = redirect_uri;
                if (response_type.equals("token"))
                    uri += "#access_token=" + access_token + "&token_type=bearer&expires_in="
                            + access_token_time;
                if (response_type.equals("id_token"))
                    uri += "#id_token=" + id_token;
                if (response_type.equals("token id_token") || response_type.equals("id_token token"))
                    uri += "#access_token=" + access_token + "&token_type=bearer&expires_in="
                            + access_token_time + "&id_token=" + id_token;
                if (state != null && !state.equals("null"))
                    uri += "&state=" + state;
                response.sendRedirect(uri);
                logger.info(uri);
                return;
            }
        }
    } catch (Exception e) {
        logger.trace(e.getMessage());
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (stmt != null)
                stmt.close();
            if (conn != null)
                conn.close();
            logger.trace("close()");
        } catch (SQLException e) {
            logger.trace(e.getMessage());
        }
    }
    if (redirect_uri != null || redirect_uri.equals("null"))
        uri = redirect_uri;
    else
        uri = "/myop/error";
    if (username != null && !username.equals("null") && password != null && !password.equals("null")) {
        uri += "#error=access_denied&error_description=User%20authentication%20failed.";
        session = request.getSession(false);
        if (session != null)
            session.invalidate();
    } else if (scope == null) {
        uri += "#error=invalid_scope&error_description=The%20scope%20value%20is%20not%20supported.";
    } else if (client_scope == null || client_scope.equals("null")) {
        uri += "#error=unauthorized_clienti&error_description=Client%20authentication%20failed.";
    } else if (response_type == null || response_type.equals("null")
            || !(response_type.equals("token") || response_type.equals("id_token")
                    || response_type.equals("token id_token") || response_type.equals("id_token token"))) {
        uri += "#error=unsupported_response_type&error_description==The%20response_type%20value%20%22"
                + response_type + "%22%20is%20not%20supported.";
    } else if (redirect_uri_check && !db_redirect_uri.equals(redirect_uri)) {
        uri += "#error=invalid_request&error_description=redirect_uri%20is%20not%20valid.";
    } else {
        uri = "/myop/login?response_type=" + URLEncoder.encode(response_type, "UTF-8") + "&client_id="
                + client_id + "&redirect_uri=" + URLEncoder.encode(redirect_uri, "UTF-8") + "&scope="
                + URLEncoder.encode(scope, "UTF-8");
        if (nonce != null && !nonce.equals("null"))
            uri += "&nonce=" + nonce;
        if (prompt != null && !prompt.equals("null"))
            uri += "&prompt=" + prompt;
        if (login_hint != null && !login_hint.equals("null"))
            uri += "&login_hint=" + login_hint;
        if (max_age != null && !max_age.equals("null"))
            uri += "&max_age=" + max_age;
        if (consent != null && consent.equals("true"))
            uri += "&consent=" + consent;
    }
    if (state != null && !state.equals("null"))
        uri += "&state=" + state;
    response.sendRedirect(uri);
    logger.info(uri);
    logger.trace("END");
}

From source file:org.onosproject.protocol.http.ctl.HttpSBControllerImpl.java

@Override
public boolean patch(DeviceId device, String request, InputStream payload, String mediaType) {
    String type = typeOfMediaType(mediaType);

    try {//from   www. ja  va 2  s . co m
        log.debug("Url request {} ", getUrlString(device, request));
        HttpPatch httprequest = new HttpPatch(getUrlString(device, request));
        if (deviceMap.get(device).username() != null) {
            String pwd = deviceMap.get(device).password() == null ? ""
                    : COLON + deviceMap.get(device).password();
            String userPassword = deviceMap.get(device).username() + pwd;
            String base64string = Base64.getEncoder()
                    .encodeToString(userPassword.getBytes(StandardCharsets.UTF_8));
            httprequest.addHeader(AUTHORIZATION_PROPERTY, BASIC_AUTH_PREFIX + base64string);
        }
        if (payload != null) {
            StringEntity input = new StringEntity(IOUtils.toString(payload, StandardCharsets.UTF_8));
            input.setContentType(type);
            httprequest.setEntity(input);
        }
        CloseableHttpClient httpClient;
        if (deviceMap.containsKey(device) && deviceMap.get(device).protocol().equals(HTTPS)) {
            httpClient = getApacheSslBypassClient();
        } else {
            httpClient = HttpClients.createDefault();
        }
        int responseStatusCode = httpClient.execute(httprequest).getStatusLine().getStatusCode();
        return checkStatusCode(responseStatusCode);
    } catch (IOException | NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        log.error("Cannot do PATCH {} request on device {}", request, device, e);
    }
    return false;
}

From source file:ru.anr.base.facade.web.api.RestClient.java

/**
 * Setting Basic Authorization header to apply
 * //from   www. j  a va2 s.  co m
 * @param user
 *            A user
 * @param password
 *            A password
 */
public void setBasicCredentials(String user, String password) {

    String s = user + ":" + password;
    this.basicCredentials = "Basic " + utf8(Base64.getEncoder().encode(utf8(s)));
}

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()));
                        }//from   ww w  .j  a  v  a 2 s  .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:de.treichels.hott.mdlviewer.swt.SwtCurveImageGenerator.java

@NotNull
@Override/*from  w  w w.  j  a va2 s. c  om*/
public String getImageSource(@NotNull final Curve curve, final double scale, final boolean description) {
    final Image image = getImage(curve, scale, description);
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final ImageLoader imageLoader = new ImageLoader();
    try {
        imageLoader.data = new ImageData[] { image.getImageData() };
        imageLoader.save(baos, SWT.IMAGE_PNG);
    } catch (final Exception e) {
        if (Util.INSTANCE.getDEBUG())
            e.printStackTrace();
    }

    return CurveImageGenerator.Companion.PREFIX + Base64.getEncoder().encodeToString(baos.toByteArray());
}

From source file:name.wramner.jmstools.analyzer.DataProvider.java

/**
 * Get a base64-encoded image for inclusion in an img tag with a chart with number of produced and consumed messages
 * per minute.//  w  w w. j a v  a 2  s .  co m
 *
 * @return chart as base64 string.
 */
public String getBase64MessagesPerMinuteImage() {
    TimeSeries timeSeriesConsumed = new TimeSeries("Consumed");
    TimeSeries timeSeriesProduced = new TimeSeries("Produced");
    TimeSeries timeSeriesTotal = new TimeSeries("Total");
    for (PeriodMetrics m : getMessagesPerMinute()) {
        Minute minute = new Minute(m.getPeriodStart());
        timeSeriesConsumed.add(minute, m.getConsumed());
        timeSeriesProduced.add(minute, m.getProduced());
        timeSeriesTotal.add(minute, m.getConsumed() + m.getProduced());
    }
    TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection(timeSeriesConsumed);
    timeSeriesCollection.addSeries(timeSeriesProduced);
    timeSeriesCollection.addSeries(timeSeriesTotal);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        JFreeChart chart = ChartFactory.createTimeSeriesChart("Messages per minute", "Time", "Messages",
                timeSeriesCollection);
        chart.getPlot().setBackgroundPaint(Color.WHITE);
        ChartUtilities.writeChartAsPNG(bos, chart, 1024, 500);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
    return "data:image/png;base64," + Base64.getEncoder().encodeToString(bos.toByteArray());
}

From source file:org.openhab.binding.loxone.internal.core.LxWsSecurityToken.java

@Override
boolean execute() {
    logger.debug("[{}] Starting token-based authentication.", debugId);
    if (!initialize()) {
        return false;
    }//  w  ww .  j  a va 2 s. c  o m
    if ((token == null || token.isEmpty()) && (password == null || password.isEmpty())) {
        return setError(LxOfflineReason.UNAUTHORIZED, "Enter password to acquire token.");
    }
    // Get Miniserver's public key - must be over http, not websocket
    String msg = socket.httpGet(CMD_GET_PUBLIC_KEY);
    LxJsonSubResponse resp = socket.getSubResponse(msg);
    if (resp == null) {
        return setError(LxOfflineReason.COMMUNICATION_ERROR, "Get public key failed - null response.");
    }
    // RSA cipher to encrypt our AES-256 key using Miniserver's public key
    Cipher rsaCipher = getRsaCipher(resp.value.getAsString());
    if (rsaCipher == null) {
        return false;
    }
    // Generate session key
    byte[] sessionKey = generateSessionKey(rsaCipher);
    if (sessionKey == null) {
        return false;
    }
    // Exchange keys
    resp = socket.sendCmdWithResp(CMD_KEY_EXCHANGE + Base64.getEncoder().encodeToString(sessionKey), true,
            false);
    if (!checkResponse(resp)) {
        return setError(null, "Key exchange failed.");
    }
    logger.debug("[{}] Keys exchanged.", debugId);
    encryptionReady = true;

    if (token == null || token.isEmpty()) {
        if (!acquireToken()) {
            return false;
        }
        logger.debug("[{}] Authenticated - acquired new token.", debugId);
    } else {
        if (!useToken()) {
            return false;
        }
        logger.debug("[{}] Authenticated - used stored token.", debugId);
    }

    return true;
}