List of usage examples for java.util Base64 getEncoder
public static Encoder getEncoder()
From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java
@Test public void testTokenTypeInHeader() { MockHttpServletRequest req = new MockHttpServletRequest(); MockHttpServletResponse res = new MockHttpServletResponse(); Authenticate.unmock();//from w w w . j a v a 2s . com ExternalApplication externalApp = new ExternalApplication(); externalApp.setAuthor(user1); externalApp.setName("Test External Application"); externalApp.setDescription("This is a test external application"); externalApp.setRedirectUrl("http://test.url/callback"); externalApp.addScopes(externalApplicationScope); ApplicationUserSession applicationUserSession = new ApplicationUserSession(); applicationUserSession.setCode("fenixedu"); ApplicationUserAuthorization applicationUserAuthorization = new ApplicationUserAuthorization(user1, externalApp); applicationUserAuthorization.addSession(applicationUserSession); externalApp.addApplicationUserAuthorization(applicationUserAuthorization); String clientSecret = externalApp.getExternalId() + ":" + externalApp.getSecret(); req.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString(clientSecret.getBytes(StandardCharsets.UTF_8))); req.addParameter(REDIRECT_URI, externalApp.getRedirectUrl()); req.addParameter(CODE, applicationUserSession.getCode()); req.addParameter(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); 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); Assert.assertTrue("response must be a valid json and have " + TOKEN_TYPE + " field", token.has(TOKEN_TYPE) && token.get(TOKEN_TYPE).getAsString().length() > 0); String accessToken = token.get(ACCESS_TOKEN).getAsString(); String tokenType = token.get(TOKEN_TYPE).getAsString(); String result = target("bennu-oauth").path("test").path("test-scope").request() .header(HttpHeaders.AUTHORIZATION, tokenType + " " + accessToken).get(String.class); Assert.assertEquals("this is an endpoint with TEST scope user1", result); } catch (ServletException | IOException e) { Assert.fail(e.getMessage()); } }
From source file:com.thoughtworks.go.server.controller.AgentRegistrationControllerTest.java
private String token(String uuid, String tokenGenerationKey) { try {// w ww .j a v a2s. c o m Mac mac = Mac.getInstance("HmacSHA256"); SecretKeySpec secretKey = new SecretKeySpec(tokenGenerationKey.getBytes(), "HmacSHA256"); mac.init(secretKey); return Base64.getEncoder().encodeToString(mac.doFinal(uuid.getBytes())); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new RuntimeException(e); } }
From source file:org.jboss.as.test.integration.security.loginmodules.negotiation.SPNEGOLoginModuleTestCase.java
/** * Kerberos simple scenario. Client provides a valid Kerberos token (without SPNEGO envelope) in the first round. See * <a href="https://tools.ietf.org/html/rfc4121">RFC-4121</a>. *//* ww w .j a v a 2s . co m*/ @Test @OperateOnDeployment("WEB") public void testPlainKerberosWorkflow(@ArquillianResource URL webAppURL) throws Exception { final URI uri = getServletURI(webAppURL, SimpleSecuredServlet.SERVLET_PATH); final byte[] kerberosToken = createNewKerberosTicketForHttp(uri); try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { final HttpGet httpGet = new HttpGet(uri); HttpResponse response = httpClient.execute(httpGet); assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); assertHttpHeader(response, HEADER_WWW_AUTHENTICATE, "Negotiate"); EntityUtils.consume(response.getEntity()); httpGet.setHeader(HEADER_AUTHORIZATION, "Negotiate " + Base64.getEncoder().encodeToString(kerberosToken)); response = httpClient.execute(httpGet); if (LOGGER.isTraceEnabled()) { LOGGER.trace( "Negotiate response in HTTP header:\n" + KerberosTestUtils.dumpNegotiateHeader(response)); } assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); assertEquals("Unexpected response body", SimpleSecuredServlet.RESPONSE_BODY, EntityUtils.toString(response.getEntity())); } }
From source file:com.exalttech.trex.util.Util.java
/** * Serialize object to string//from w w w.j ava 2 s . co m * * @param objectToSer * @return * @throws IOException */ public static String serializeObjectToString(Serializable objectToSer) throws IOException { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(objectToSer); oos.close(); return Base64.getEncoder().encodeToString(baos.toByteArray()); } catch (IOException ex) { LOG.error("Error serializing object", ex); return ""; } }
From source file:com.bgh.myopeninvoice.jsf.jsfbeans.InvoiceBean.java
public String getImageAttachment(AttachmentEntity attachmentEntity) throws IOException, ImageReadException { if (attachmentEntity != null && attachmentEntity.getContent().length > 0) { if (attachmentEntity.getLoadProxy()) { return "/images/" + attachmentEntity.getFileExtension() + ".png"; } else {//from ww w . j a v a 2 s .c o m selectedAttachmentEntity = attachmentEntity; ImageFormat mimeType = Sanselan.guessFormat(attachmentEntity.getContent()); if (mimeType != null && !"UNKNOWN".equalsIgnoreCase(mimeType.name)) { return "data:image/" + mimeType.extension.toLowerCase() + ";base64," + Base64.getEncoder().encodeToString(attachmentEntity.getContent()); } else if (attachmentEntity.getImageData() != null && attachmentEntity.getImageData().length > 0) { return "data:image/png;base64," + Base64.getEncoder().encodeToString(attachmentEntity.getImageData()); } else if ("pdf".equalsIgnoreCase(attachmentEntity.getFileExtension())) { ByteArrayOutputStream baos = null; PDDocument document = null; try { document = PDDocument.load(attachmentEntity.getContent()); final PDPage page = document.getPage(0); PDFRenderer pdfRenderer = new PDFRenderer(document); final BufferedImage bufferedImage = pdfRenderer.renderImage(0); baos = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "png", baos); baos.flush(); attachmentEntity.setImageData(baos.toByteArray()); } finally { if (document != null) { document.close(); } if (baos != null) { baos.close(); } } return "data:image/png;base64," + Base64.getEncoder().encodeToString(attachmentEntity.getImageData()); } else { return null; } } } else if (selectedAttachmentEntity != null && selectedAttachmentEntity.getImageData() != null && selectedAttachmentEntity.getImageData().length > 0) { return "data:image/png;base64," + Base64.getEncoder().encodeToString(selectedAttachmentEntity.getImageData()); } else { return null; } }
From source file:org.wso2.carbon.apimgt.core.impl.LogInKeyManagerImpl.java
/** * This method is to generate a new application access token * * @param tokenRequest AccessTokenRequest which encapsulates parameters sent from Store UI. * @return AccessTokenInfo which wraps application access token data * @throws org.wso2.carbon.apimgt.core.exception.KeyManagementException -throws KeyManagementException type *///from ww w.ja va2s.c om @Override public AccessTokenInfo getNewApplicationAccessToken(AccessTokenRequest tokenRequest) throws KeyManagementException { String newAccessToken, refreshToken = null; long validityPeriod; AccessTokenInfo tokenInfo = null; if (tokenRequest == null) { log.warn("No information available to generate Token."); return null; } //TO-DO -ADD A CONFIG FOR TOKEN ENDPOINT String tokenEndpoint = getKeyManagerEndPoint("/oauth2/token"); //System.getProperty("TokenEndpoint", "https://localhost:9443/oauth2/token"); //TO-DO -ADD A CONFIG FOR REVOKE ENDPOINT String revokeEndpoint = getKeyManagerEndPoint("/oauth2/revoke"); //System.getProperty("RevokeEndpoint", "https://localhost:9443/oauth2/revoke"); ; // Call the /revoke only if there's a token to be revoked. URL url; HttpURLConnection urlConn = null; if (tokenRequest.getTokenToRevoke() != null && !"".equals(tokenRequest.getTokenToRevoke())) { //Revoke the Old Access Token try { createSSLConnection(); url = new URL(revokeEndpoint); urlConn = (HttpURLConnection) url.openConnection(); urlConn.setDoOutput(true); urlConn.setRequestMethod("POST"); String postParams = KeyManagerConstants.OAUTH_CLIENT_ID + "=" + tokenRequest.getClientId() + KeyManagerConstants.OAUTH_CLIENT_SECRET + "=" + tokenRequest.getClientSecret() + 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 RuntimeException("Token revoke failed : HTTP error code : " + responseCode); } else { APIUtils.logDebug( "Successfully submitted revoke request for old application 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.APPLICATION_TOKEN_GENERATION_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.APPLICATION_TOKEN_GENERATION_FAILED); } finally { if (urlConn != null) { urlConn.disconnect(); } } } //get default application access token name from config. //TO-DO -DEFINE APPICATION TOKEN SCOPES String applicationTokenScope = ""; // When validity time set to a negative value, a token is considered never to expire. if (tokenRequest.getValidityPeriod() == -1L) { // Setting a different -ve value if the set value is -1 (-1 will be ignored by TokenValidator) tokenRequest.setValidityPeriod(-2); } //Generate New Access Token by client credentials grant type with calling Token API try { createSSLConnection(); url = new URL(tokenEndpoint); urlConn = (HttpURLConnection) url.openConnection(); urlConn.setDoOutput(true); urlConn.setRequestMethod("POST"); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String clientEncoded = Base64.getEncoder() .encodeToString((tokenRequest.getClientId() + ":" + tokenRequest.getClientSecret()) .getBytes(StandardCharsets.UTF_8)); urlConn.setRequestProperty("Authorization", "Basic " + clientEncoded); StringBuilder builder = new StringBuilder(); builder.append(applicationTokenScope); for (String scope : tokenRequest.getScopes()) { builder.append(' ').append(scope); } String postParams = ""; if (PASSWORD_GRANT_TYPE.equals(tokenRequest.getGrantType())) { postParams = KeyManagerConstants.OAUTH_CLIENT_GRANT + "=" + PASSWORD_GRANT_TYPE + "&username=" + tokenRequest.getResourceOwnerUsername() + "&password=" + tokenRequest.getResourceOwnerPassword(); } else if (REFRESH_GRANT_TYPE.equals(tokenRequest.getGrantType())) { postParams = KeyManagerConstants.OAUTH_CLIENT_GRANT + "=" + REFRESH_GRANT_TYPE + "&" + OAUTH_RESPONSE_REFRESH_TOKEN + "=" + tokenRequest.getRefreshToken(); } else { postParams = KeyManagerConstants.OAUTH_CLIENT_GRANT + "=" + GRANT_TYPE_VALUE; } if (tokenRequest.getScopes().length > 0) { postParams += "&" + KeyManagerConstants.OAUTH_CLIENT_SCOPE + "=" + builder.toString(); } postParams += "&" + GRANT_TYPE_PARAM_VALIDITY + "=" + Long.toString(tokenRequest.getValidityPeriod()); // + "&" + // GRANT_TYPE_PARAM_VALIDITY + "=" + Long.toString(tokenRequest.getValidityPeriod()) + "&" + // KeyManagerConstants.OAUTH_CLIENT_ID + "=" + tokenRequest.getClientId() + "&" + // KeyManagerConstants.OAUTH_CLIENT_SECRET + "=" + tokenRequest.getClientSecret() + "&" + // KeyManagerConstants.OAUTH_CLIENT_SCOPE + "=" + builder.toString(); urlConn.getOutputStream().write((postParams).getBytes("UTF-8")); int responseCode = urlConn.getResponseCode(); if (responseCode == 404) { //If token endpoint not found throw new KeyManagementException( "Error occurred while calling token endpoint: HTTP error code : " + responseCode); } else if (responseCode == 401) { //If token generation failed throw new KeyManagementException("Invalid credentials provided. HTTP status code: " + responseCode, ExceptionCodes.INVALID_CREDENTIALS); } else if (responseCode == 200) { APIUtils.logDebug( "Successfully submitted token request for old application token. HTTP status : 200", log); tokenInfo = new AccessTokenInfo(); String responseStr = new String(IOUtils.toByteArray(urlConn.getInputStream()), "UTF-8"); JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(responseStr).getAsJsonObject(); newAccessToken = obj.get(OAUTH_RESPONSE_ACCESSTOKEN).getAsString(); if (obj.has(OAUTH_RESPONSE_REFRESH_TOKEN)) { refreshToken = obj.get(OAUTH_RESPONSE_REFRESH_TOKEN).getAsString(); } validityPeriod = Long.parseLong(obj.get(OAUTH_RESPONSE_EXPIRY_TIME).toString()); if (obj.has(KeyManagerConstants.OAUTH_CLIENT_SCOPE)) { tokenInfo.setScopes( (obj.getAsJsonPrimitive(KeyManagerConstants.OAUTH_CLIENT_SCOPE).getAsString()) .split(" ")); } tokenInfo.setAccessToken(newAccessToken); tokenInfo.setValidityPeriod(validityPeriod); tokenInfo.setRefreshToken(refreshToken); } else { throw new KeyManagementException( "Error occurred while getting token for grant type : " + tokenRequest.getGrantType(), ExceptionCodes.APPLICATION_TOKEN_GENERATION_FAILED); } } catch (IOException e) { String msg = "Error while creating the new token for token regeneration."; log.error(msg, e); throw new KeyManagementException(msg + e.getMessage(), e, ExceptionCodes.APPLICATION_TOKEN_GENERATION_FAILED); } catch (JsonSyntaxException e) { String msg = "Error while processing the response returned from token generation call."; log.error(msg, e); throw new KeyManagementException(msg + e.getMessage(), e, ExceptionCodes.APPLICATION_TOKEN_GENERATION_FAILED); } catch (NoSuchAlgorithmException | java.security.KeyManagementException e) { String msg = "Error while connecting to the token generation endpoint."; log.error(msg, e); throw new KeyManagementException(msg + e.getMessage(), e, ExceptionCodes.APPLICATION_TOKEN_GENERATION_FAILED); } finally { if (urlConn != null) { urlConn.disconnect(); } } return tokenInfo; }
From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditorTest.java
License:asdf
@Test public void testDeleteTrustedCert() throws KeystoreEditor.KeystoreEditorException, IOException { KeystoreEditor keystoreEditor = new KeystoreEditor(); FileInputStream fileInputStream = new FileInputStream(crtFile); byte[] crtBytes = IOUtils.toByteArray(fileInputStream); IOUtils.closeQuietly(fileInputStream); keystoreEditor.addTrustedCertificate("asdf", password, "", new String(Base64.getEncoder().encode(crtBytes)), KeystoreEditor.PEM_TYPE, crtFile.toString()); List<Map<String, Object>> truststore = keystoreEditor.getTruststore(); Assert.assertThat(truststore.size(), Is.is(1)); List<Map<String, Object>> keystore = keystoreEditor.getKeystore(); Assert.assertThat(keystore.size(), Is.is(0)); keystoreEditor.deleteTrustedCertificate("asdf"); truststore = keystoreEditor.getTruststore(); Assert.assertThat(truststore.size(), Is.is(0)); keystore = keystoreEditor.getKeystore(); Assert.assertThat(keystore.size(), Is.is(0)); }
From source file:EnrollFingerprint.Enroll.java
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed try {// w w w .j a va 2s. c o m // Page 36 -37 Serialization / Deserialization // Escribo un archivo en memoria ByteArrayOutputStream fileInMemory = new ByteArrayOutputStream(); fileInMemory.write(getTemplate().serialize()); fpglobal = fileInMemory; // Codifico el ByteArray de memoria en Base64 byte[] fpdata = Base64.getEncoder().encode(fpglobal.toByteArray()); String apiURL = "http://localhost:3012/api/v1/fingerprints"; new Requestor().postFingerprint(apiURL, fpdata, "1", "1"); } catch (Exception e) { System.out.println(e); } }
From source file:alfio.util.TemplateResource.java
public static Map<String, Object> buildModelForTicketPDF(Organization organization, Event event, TicketReservation ticketReservation, TicketCategory ticketCategory, Ticket ticket, Optional<ImageData> imageData, String reservationId) { String qrCodeText = ticket.ticketCode(event.getPrivateKey()); ////w w w. j a v a2 s . c o m Map<String, Object> model = new HashMap<>(); model.put("ticket", ticket); model.put("reservation", ticketReservation); model.put("ticketCategory", ticketCategory); model.put("event", event); model.put("organization", organization); model.put("reservationId", reservationId); fillTicketValidity(event, ticketCategory, model); model.put("qrCodeDataUri", "data:image/png;base64," + Base64.getEncoder().encodeToString(createQRCode(qrCodeText))); imageData.ifPresent(iData -> { model.put("eventImage", iData.getEventImage()); model.put("imageWidth", iData.getImageWidth()); model.put("imageHeight", iData.getEventImage()); }); model.put("deskPaymentRequired", Optional.ofNullable(ticketReservation.getPaymentMethod()) .orElse(PaymentProxy.STRIPE).isDeskPaymentRequired()); return model; }
From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java
@Test public void getAccessTokenHeaderTest() { MockHttpServletRequest req = new MockHttpServletRequest(); MockHttpServletResponse res = new MockHttpServletResponse(); Authenticate.unmock();//from w w w. j a v a2 s .c om ExternalApplication externalApp = new ExternalApplication(); externalApp.setAuthor(user1); externalApp.setName("Test External Application"); externalApp.setDescription("This is a test external application"); externalApp.setRedirectUrl("http://test.url/callback"); ApplicationUserSession applicationUserSession = new ApplicationUserSession(); applicationUserSession.setCode("fenixedu"); ApplicationUserAuthorization applicationUserAuthorization = new ApplicationUserAuthorization(user1, externalApp); applicationUserAuthorization.addSession(applicationUserSession); externalApp.addApplicationUserAuthorization(applicationUserAuthorization); String clientSecret = externalApp.getExternalId() + ":" + externalApp.getSecret(); req.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString(clientSecret.getBytes(StandardCharsets.UTF_8))); req.addParameter(REDIRECT_URI, externalApp.getRedirectUrl()); req.addParameter(CODE, applicationUserSession.getCode()); req.addParameter(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); 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()); } }