List of usage examples for java.util Base64 getEncoder
public static Encoder getEncoder()
From source file:com.evolveum.midpoint.model.intest.TestNotifications.java
@Test public void test215SendSmsUsingGeneralPost() { final String TEST_NAME = "test215SendSmsUsingGeneralPost"; TestUtil.displayTestTitle(this, TEST_NAME); // GIVEN/*from w w w . jav a2s .c om*/ Task task = taskManager.createTaskInstance(TestNotifications.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); // WHEN TestUtil.displayWhen(TEST_NAME); Event event = new CustomEvent(lightweightIdentifierGenerator, "general-post", null, "hello world", EventOperationType.ADD, EventStatusType.SUCCESS, null); notificationManager.processEvent(event, task, result); // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("processEvent result", result); assertNotNull("No http request found", httpHandler.lastRequest); assertEquals("Wrong HTTP method", "POST", httpHandler.lastRequest.method); assertEquals("Wrong URI", "/send", httpHandler.lastRequest.uri.toString()); assertEquals("Wrong Content-Type header", singletonList("application/x-www-form-urlencoded"), httpHandler.lastRequest.headers.get("content-type")); assertEquals("Wrong X-Custom header", singletonList("test"), httpHandler.lastRequest.headers.get("x-custom")); String username = "a9038321"; String password = "5ecr3t"; String expectedAuthorization = "Basic " + Base64.getEncoder() .encodeToString((username + ":" + password).getBytes(StandardCharsets.ISO_8859_1)); assertEquals("Wrong Authorization header", singletonList(expectedAuthorization), httpHandler.lastRequest.headers.get("authorization")); assertEquals("Wrong 1st line of body", "Body=\"body\"&To=[%2B123, %2B456, %2B789]&From=from", httpHandler.lastRequest.body.get(0)); }
From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java
@Test public void getServiceAccessTokenHeaderEmptyTest() { MockHttpServletRequest req = new MockHttpServletRequest(); MockHttpServletResponse res = new MockHttpServletResponse(); Authenticate.unmock();/* w w w . ja v a 2 s . c om*/ String clientSecret = ""; req.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString(clientSecret.getBytes(StandardCharsets.UTF_8))); req.addParameter(GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS); req.setMethod("POST"); req.setPathInfo("/access_token"); try { oauthServlet.service(req, res); Assert.assertEquals("must return BAD_REQUEST", 400, res.getStatus()); } catch (ServletException | IOException e) { Assert.fail(e.getMessage()); } }
From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java
private void exhangeToken() throws IOException, URISyntaxException { this.renewTime = 0; String cookiesJson = "{\"cookies\":{\"." + getAmazonSite() + "\":[]}}"; String cookiesBase64 = Base64.getEncoder().encodeToString(cookiesJson.getBytes()); String exchangePostData = "di.os.name=iOS&app_version=2.2.223830.0&domain=." + getAmazonSite() + "&source_token=" + URLEncoder.encode(this.refreshToken, "UTF8") + "&requested_token_type=auth_cookies&source_token_type=refresh_token&di.hw.version=iPhone&di.sdk.version=6.10.0&cookies=" + cookiesBase64 + "&app_name=Amazon%20Alexa&di.os.version=11.4.1"; HashMap<String, String> exchangeTokenHeader = new HashMap<String, String>(); exchangeTokenHeader.put("Cookie", ""); String exchangeTokenJson = makeRequestAndReturnString("POST", "https://www." + getAmazonSite() + "/ap/exchangetoken", exchangePostData, false, exchangeTokenHeader);// w ww .j a va 2 s.c om JsonExchangeTokenResponse exchangeTokenResponse = gson.fromJson(exchangeTokenJson, JsonExchangeTokenResponse.class); org.openhab.binding.amazonechocontrol.internal.jsons.JsonExchangeTokenResponse.Response response = exchangeTokenResponse.response; if (response != null) { org.openhab.binding.amazonechocontrol.internal.jsons.JsonExchangeTokenResponse.Tokens tokens = response.tokens; if (tokens != null) { @Nullable Map<String, Cookie[]> cookiesMap = tokens.cookies; if (cookiesMap != null) { for (String domain : cookiesMap.keySet()) { Cookie[] cookies = cookiesMap.get(domain); for (Cookie cookie : cookies) { if (cookie != null) { HttpCookie httpCookie = new HttpCookie(cookie.Name, cookie.Value); httpCookie.setPath(cookie.Path); httpCookie.setDomain(domain); Boolean secure = cookie.Secure; if (secure != null) { httpCookie.setSecure(secure); } this.cookieManager.getCookieStore().add(null, httpCookie); } } } } } } if (!verifyLogin()) { throw new ConnectionException("Verify login failed after token exchange"); } this.renewTime = (long) (System.currentTimeMillis() + Connection.expiresIn * 1000d / 0.8d); // start renew at }
From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java
@Test public void getServiceAccessTokenHeaderTest() { MockHttpServletRequest req = new MockHttpServletRequest(); MockHttpServletResponse res = new MockHttpServletResponse(); Authenticate.unmock();/*from w w w . jav a 2 s. com*/ String clientSecret = serviceApplication.getExternalId() + ":" + serviceApplication.getSecret(); req.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString(clientSecret.getBytes(StandardCharsets.UTF_8))); req.addParameter(GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS); req.setMethod("POST"); req.setPathInfo("/access_token"); try { oauthServlet.service(req, res); Assert.assertEquals("must return status OK", 200, res.getStatus()); String tokenJson = res.getContentAsString(); final JsonObject token = new JsonParser().parse(tokenJson).getAsJsonObject(); Assert.assertTrue("response must be a valid json and have access_token field", token.has(ACCESS_TOKEN) && token.get(ACCESS_TOKEN).getAsString().length() > 0); } catch (ServletException | IOException e) { Assert.fail(e.getMessage()); } }
From source file:org.apache.flink.table.runtime.functions.SqlFunctionUtils.java
public static String toBase64(byte[] bytes) { return Base64.getEncoder().encodeToString(bytes); }
From source file:org.wso2.carbon.apimgt.core.impl.LogInKeyManagerImpl.java
/** * This method is called to revoke an existing access token which is used to log in to publisher,store or admin * apps.//from ww w. j av a 2s . co m * * @param tokenRequest AccessTokenRequest which encapsulates parameters sent from UI. * @throws KeyManagementException Exception while revoking the access token */ @Override public void revokeLogInAccessToken(AccessTokenRequest tokenRequest) throws KeyManagementException { if (tokenRequest == null) { log.warn("No information available to generate Token."); return; } //TO-DO -ADD A CONFIG FOR REVOKE ENDPOINT String revokeEndpoint = getKeyManagerEndPoint("/oauth2/revoke"); URL url; HttpURLConnection urlConn = null; if (tokenRequest.getTokenToRevoke() != null && !tokenRequest.getTokenToRevoke().isEmpty()) { //Revoke the Old Access Token try { createSSLConnection(); url = new URL(revokeEndpoint); urlConn = (HttpURLConnection) url.openConnection(); urlConn.setDoOutput(true); urlConn.setRequestMethod("POST"); String clientEncoded = Base64.getEncoder() .encodeToString((tokenRequest.getClientId() + ":" + tokenRequest.getClientSecret()) .getBytes(StandardCharsets.UTF_8)); urlConn.setRequestProperty("Authorization", "Basic " + clientEncoded); String postParams = KeyManagerConstants.OAUTH_TOKEN + "=" + tokenRequest.getTokenToRevoke(); urlConn.getOutputStream().write((postParams).getBytes("UTF-8")); int responseCode = urlConn.getResponseCode(); if (responseCode != 200) { //If token revoke failed throw new KeyManagementException("Token revoke failed : HTTP error code : " + responseCode, ExceptionCodes.ACCESS_TOKEN_REVOKE_FAILED); } else { APIUtils.logDebug( "Successfully submitted revoke request for old access token. HTTP status : 200", log); } } catch (IOException e) { String msg = "Error while revoking the existing token."; log.error(msg, e); throw new KeyManagementException(msg + e.getMessage(), e, ExceptionCodes.ACCESS_TOKEN_REVOKE_FAILED); } catch (NoSuchAlgorithmException | java.security.KeyManagementException e) { String msg = "Error while connecting with the revoke endpoint for revoking the existing token."; log.error(msg, e); throw new KeyManagementException(msg + e.getMessage(), e, ExceptionCodes.ACCESS_TOKEN_REVOKE_FAILED); } finally { if (urlConn != null) { urlConn.disconnect(); } } } }
From source file:org.apache.syncope.fit.core.UserIssuesITCase.java
@Test public void issueSYNCOPE357() throws IOException { // 1. create group with LDAP resource GroupTO groupTO = new GroupTO(); groupTO.setName("SYNCOPE357-" + getUUIDString()); groupTO.setRealm("/"); groupTO.getResources().add(RESOURCE_NAME_LDAP); groupTO = createGroup(groupTO).getEntity(); assertNotNull(groupTO);//from w ww. ja v a 2 s. c o m // 2. create user with membership of the above group UserTO userTO = UserITCase.getUniqueSampleTO("syncope357@syncope.apache.org"); userTO.getPlainAttrs().add(attrTO("obscure", "valueToBeObscured")); userTO.getPlainAttrs().add(attrTO("photo", Base64.getEncoder() .encodeToString(IOUtils.readBytesFromStream(getClass().getResourceAsStream("/favicon.jpg"))))); userTO.getMemberships().add(new MembershipTO.Builder().group(groupTO.getKey()).build()); userTO = createUser(userTO).getEntity(); assertTrue(userTO.getResources().contains(RESOURCE_NAME_LDAP)); assertNotNull(userTO.getPlainAttr("obscure")); assertNotNull(userTO.getPlainAttr("photo")); // 3. read user on resource ConnObjectTO connObj = resourceService.readConnObject(RESOURCE_NAME_LDAP, AnyTypeKind.USER.name(), userTO.getKey()); assertNotNull(connObj); AttrTO registeredAddress = connObj.getAttr("registeredAddress").get(); assertNotNull(registeredAddress); assertEquals(userTO.getPlainAttr("obscure").get().getValues(), registeredAddress.getValues()); Optional<AttrTO> jpegPhoto = connObj.getAttr("jpegPhoto"); assertTrue(jpegPhoto.isPresent()); assertEquals(userTO.getPlainAttr("photo").get().getValues().get(0), jpegPhoto.get().getValues().get(0)); // 4. remove group groupService.delete(groupTO.getKey()); // 5. try to read user on resource: fail try { resourceService.readConnObject(RESOURCE_NAME_LDAP, AnyTypeKind.USER.name(), userTO.getKey()); fail("This should not happen"); } catch (SyncopeClientException e) { assertEquals(ClientExceptionType.NotFound, e.getType()); } }
From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java
public String getLoginPage() throws IOException, URISyntaxException { // clear session data logout();/* ww w . ja va2 s. co m*/ logger.debug("Start Login to {}", alexaServer); String mapMdJson = "{\"device_user_dictionary\":[],\"device_registration_data\":{\"software_version\":\"1\"},\"app_identifier\":{\"app_version\":\"2.2.223830\",\"bundle_id\":\"com.amazon.echo\"}}"; String mapMdCookie = Base64.getEncoder().encodeToString(mapMdJson.getBytes()); cookieManager.getCookieStore().add(new URI("https://www.amazon.com"), new HttpCookie("map-md", mapMdCookie)); cookieManager.getCookieStore().add(new URI("https://www.amazon.com"), new HttpCookie("frc", frc)); String loginFormHtml = makeRequestAndReturnString("https://www.amazon.com" + "/ap/signin?openid.return_to=https://www.amazon.com/ap/maplanding&openid.assoc_handle=amzn_dp_project_dee_ios&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&pageId=amzn_dp_project_dee_ios&accountStatusPolicy=P1&openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select&openid.mode=checkid_setup&openid.ns.oa2=http://www.amazon.com/ap/ext/oauth/2&openid.oa2.client_id=device:" + deviceId + "&openid.ns.pape=http://specs.openid.net/extensions/pape/1.0&openid.oa2.response_type=token&openid.ns=http://specs.openid.net/auth/2.0&openid.pape.max_auth_age=0&openid.oa2.scope=device_auth_access"); logger.debug("Received login form {}", loginFormHtml); return loginFormHtml; }
From source file:com.joyent.manta.client.crypto.AbstractMantaEncryptedObjectInputStreamTest.java
protected MantaEncryptedObjectInputStream createEncryptedObjectInputStream(SecretKey key, InputStream in, long ciphertextSize, SupportedCipherDetails cipherDetails, byte[] iv, boolean authenticate, long plaintextSize, Long skipBytes, Long plaintextLength, boolean unboundedEnd) { String path = String.format("/test/stor/test-%s", UUID.randomUUID()); MantaHttpHeaders headers = new MantaHttpHeaders(); headers.put(MantaHttpHeaders.ENCRYPTION_CIPHER, cipherDetails.getCipherId()); headers.put(MantaHttpHeaders.ENCRYPTION_PLAINTEXT_CONTENT_LENGTH, plaintextSize); headers.put(MantaHttpHeaders.ENCRYPTION_KEY_ID, "unit-test-key"); if (cipherDetails.isAEADCipher()) { headers.put(MantaHttpHeaders.ENCRYPTION_AEAD_TAG_LENGTH, cipherDetails.getAuthenticationTagOrHmacLengthInBytes()); } else {//from w w w. j av a 2s . com final String hmacName = SupportedHmacsLookupMap .hmacNameFromInstance(cipherDetails.getAuthenticationHmac()); headers.put(MantaHttpHeaders.ENCRYPTION_HMAC_TYPE, hmacName); } headers.put(MantaHttpHeaders.ENCRYPTION_IV, Base64.getEncoder().encodeToString(iv)); headers.setContentLength(ciphertextSize); MantaMetadata metadata = new MantaMetadata(); MantaObjectResponse response = new MantaObjectResponse(path, headers, metadata); CloseableHttpResponse httpResponse = Mockito.mock(CloseableHttpResponse.class); EofSensorInputStream eofSensorInputStream = new EofSensorInputStream(in, null); MantaObjectInputStream mantaObjectInputStream = new MantaObjectInputStream(response, httpResponse, eofSensorInputStream); return new MantaEncryptedObjectInputStream(mantaObjectInputStream, cipherDetails, key, authenticate, skipBytes, plaintextLength, unboundedEnd); }
From source file:com.joyent.manta.http.EncryptionHttpHelper.java
/** * Adds headers related directly to the encrypted object being stored. * * @param metadata Manta metadata object * @param cipher cipher used to encrypt the object and metadata * @throws IOException thrown when unable to append metadata *//*from w w w . j a va2s . c o m*/ public void attachEncryptedEntityHeaders(final MantaMetadata metadata, final Cipher cipher) throws IOException { Validate.notNull(metadata, "Metadata object must not be null"); Validate.notNull(cipher, "Cipher object must not be null"); // IV Used to Encrypt byte[] iv = cipher.getIV(); Validate.notNull(iv, "Cipher IV must not be null"); String ivBase64 = Base64.getEncoder().encodeToString(iv); metadata.put(MantaHttpHeaders.ENCRYPTION_IV, ivBase64); if (LOGGER.isDebugEnabled()) { LOGGER.debug("IV: {}", Hex.encodeHexString(cipher.getIV())); } // AEAD Tag Length if AEAD Cipher if (cipherDetails.isAEADCipher()) { metadata.put(MantaHttpHeaders.ENCRYPTION_AEAD_TAG_LENGTH, String.valueOf(cipherDetails.getAuthenticationTagOrHmacLengthInBytes())); LOGGER.debug("AEAD tag length: {}", cipherDetails.getAuthenticationTagOrHmacLengthInBytes()); // HMAC Type because we are doing MtE } else { HMac hmac = cipherDetails.getAuthenticationHmac(); final String hmacName = SupportedHmacsLookupMap.hmacNameFromInstance(hmac); metadata.put(MantaHttpHeaders.ENCRYPTION_HMAC_TYPE, hmacName); LOGGER.debug("HMAC algorithm: {}", hmacName); } }