List of usage examples for java.util Base64 getEncoder
public static Encoder getEncoder()
From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditorTest.java
License:asdf
private void addPrivateKey(String alias, File file) throws KeystoreEditor.KeystoreEditorException, IOException { KeystoreEditor keystoreEditor = new KeystoreEditor(); FileInputStream fileInputStream = new FileInputStream(file); byte[] keyBytes = IOUtils.toByteArray(fileInputStream); IOUtils.closeQuietly(fileInputStream); keystoreEditor.addPrivateKey(alias, password, "blah", new String(Base64.getEncoder().encode(keyBytes)), "", file.toString());//from w ww . ja va 2 s. c o m }
From source file:com.netflix.spinnaker.halyard.deploy.provider.v1.kubernetes.KubernetesProviderInterface.java
private void upsertSecret(AccountDeploymentDetails<KubernetesAccount> details, Set<String> files, String secretName, String namespace) { KubernetesClient client = getClient(details.getAccount()); createNamespace(client, namespace);// w ww. j a v a 2 s . c om if (client.secrets().inNamespace(namespace).withName(secretName).get() != null) { client.secrets().inNamespace(namespace).withName(secretName).delete(); } Map<String, String> secretContents = new HashMap<>(); files.forEach(s -> { try { File f = new File(s); String name = f.getName(); String data = new String( Base64.getEncoder().encode(IOUtils.toString(new FileInputStream(f)).getBytes())); secretContents.putIfAbsent(name, data); } catch (IOException e) { throw new HalException( new ConfigProblemBuilder(Severity.ERROR, "Unable to read contents of \"" + s + "\": " + e) .build()); } }); SecretBuilder secretBuilder = new SecretBuilder(); secretBuilder = secretBuilder.withNewMetadata().withName(secretName).withNamespace(namespace).endMetadata() .withData(secretContents); log.info("Staging secret " + secretName + " in namespace " + namespace + " with contents " + files); client.secrets().inNamespace(namespace).create(secretBuilder.build()); }
From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java
@Test public void refreshAccessTokenHeaderTest() { MockHttpServletRequest req = new MockHttpServletRequest(); MockHttpServletResponse res = new MockHttpServletResponse(); Authenticate.unmock();/* w w w . ja v a 2s.c o m*/ 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.setTokens(generateToken(applicationUserSession), generateToken(applicationUserSession)); 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(REFRESH_TOKEN, applicationUserSession.getRefreshToken()); req.addParameter(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); req.setMethod("POST"); req.setPathInfo("/refresh_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:io.hops.hopsworks.common.user.AuthController.java
/** * Generates a salt value with SALT_LENGTH and DIGEST * * @return/*from www.j a v a 2s . co m*/ */ public String generateSalt() { byte[] bytes = new byte[SALT_LENGTH]; RANDOM.nextBytes(bytes); byte[] encodedSalt = Base64.getEncoder().encode(bytes); String salt = ""; try { salt = new String(encodedSalt, "UTF-8"); } catch (UnsupportedEncodingException ex) { LOGGER.log(Level.SEVERE, "Generate salt encoding failed", ex); } return salt; }
From source file:org.apache.nifi.registry.web.api.SecureLdapIT.java
private static String encodeCredentialsForBasicAuth(String username, String password) { final String credentials = username + ":" + password; final String base64credentials = new String( Base64.getEncoder().encode(credentials.getBytes(Charset.forName("UTF-8")))); return base64credentials; }
From source file:org.wso2.carbon.apimgt.core.impl.LogInKeyManagerImpl.java
@Override public AccessTokenInfo getTokenMetaData(String accessToken) throws KeyManagementException { AccessTokenInfo tokenInfo = new AccessTokenInfo(); URL url;//from www .j a v a2s .co m HttpURLConnection urlConn = null; try { createSSLConnection(); String introspectEndpoint = getKeyManagerEndPoint("/oauth2/introspect"); //System.getProperty("introspectEndpoint", "https://localhost:9443/oauth2/introspect"); url = new URL(introspectEndpoint); urlConn = (HttpURLConnection) url.openConnection(); urlConn.setDoOutput(true); urlConn.setRequestMethod("POST"); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String clientEncoded = Base64.getEncoder().encodeToString((System.getProperty("systemUsername", "admin") + ":" + System.getProperty("systemUserPwd", "admin")).getBytes(StandardCharsets.UTF_8)); urlConn.setRequestProperty("Authorization", "Basic " + clientEncoded); //temp fix urlConn.getOutputStream().write(("token=" + accessToken).getBytes("UTF-8")); String responseStr = new String(IOUtils.toByteArray(urlConn.getInputStream()), "UTF-8"); JsonParser parser = new JsonParser(); JsonObject jObj = parser.parse(responseStr).getAsJsonObject(); boolean active = jObj.getAsJsonPrimitive("active").getAsBoolean(); if (active) { //String consumerKey = jObj.getAsJsonPrimitive(KeyManagerConstants.OAUTH_CLIENT_ID).getAsString(); //String endUser = jObj.getAsJsonPrimitive(KeyManagerConstants.USERNAME).getAsString(); long exp = jObj.getAsJsonPrimitive(KeyManagerConstants.OAUTH2_TOKEN_EXP_TIME).getAsLong(); long issuedTime = jObj.getAsJsonPrimitive(KeyManagerConstants.OAUTH2_TOKEN_ISSUED_TIME).getAsLong(); String scopes = jObj.getAsJsonPrimitive(KeyManagerConstants.OAUTH_CLIENT_SCOPE).getAsString(); if (scopes != null) { String[] scopesArray = scopes.split(" "); tokenInfo.setScopes(scopesArray); } tokenInfo.setTokenValid(true); tokenInfo.setAccessToken(accessToken); //tokenInfo.setConsumerKey(consumerKey); //tokenInfo.setEndUserName(endUser); tokenInfo.setIssuedTime(issuedTime); // Convert Expiry Time to milliseconds. if (exp == Long.MAX_VALUE) { tokenInfo.setValidityPeriod(Long.MAX_VALUE); } else { tokenInfo.setValidityPeriod(exp * 1000); } } else { tokenInfo.setTokenValid(false); log.error("Invalid OAuth Token. "); tokenInfo.setErrorcode(KeyManagerConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS); return tokenInfo; } } catch (IOException e) { String msg = "Error while connecting to token introspect endpoint."; log.error(msg, e); throw new KeyManagementException(msg, e, ExceptionCodes.TOKEN_INTROSPECTION_FAILED); } catch (JsonSyntaxException e) { String msg = "Error while processing the response returned from token introspect endpoint."; log.error("Error while processing the response returned from token introspect endpoint.", e); throw new KeyManagementException(msg, e, ExceptionCodes.TOKEN_INTROSPECTION_FAILED); } catch (NoSuchAlgorithmException | java.security.KeyManagementException e) { String msg = "Error while connecting to the token introspect endpoint."; log.error("Error while connecting to the token introspect endpoint.", e); throw new KeyManagementException(msg, e, ExceptionCodes.TOKEN_INTROSPECTION_FAILED); } finally { if (urlConn != null) { urlConn.disconnect(); } } return tokenInfo; }
From source file:com.evolveum.midpoint.model.intest.TestNotifications.java
@Test public void test210SendSmsUsingPost() { final String TEST_NAME = "test210SendSmsUsingPost"; TestUtil.displayTestTitle(this, TEST_NAME); // GIVEN//w w w. j ava 2s . 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, "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=\"hello+world\"&To=%2B421905123456&From=%2B421999000999", httpHandler.lastRequest.body.get(0)); }
From source file:org.codice.ddf.security.idp.server.IdpEndpoint.java
@GET @Path("/login/metadata") @Produces("application/xml") public Response retrieveMetadata() throws WSSecurityException, CertificateEncodingException { List<String> nameIdFormats = new ArrayList<>(); nameIdFormats.add(SAML2Constants.NAMEID_FORMAT_PERSISTENT); nameIdFormats.add(SAML2Constants.NAMEID_FORMAT_UNSPECIFIED); nameIdFormats.add(SAML2Constants.NAMEID_FORMAT_X509_SUBJECT_NAME); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(systemCrypto.getSignatureCrypto().getDefaultX509Identifier()); X509Certificate[] certs = systemCrypto.getSignatureCrypto().getX509Certificates(cryptoType); X509Certificate issuerCert = null; if (certs != null && certs.length > 0) { issuerCert = certs[0];/*from w w w . j a va 2 s .co m*/ } cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(systemCrypto.getEncryptionCrypto().getDefaultX509Identifier()); certs = systemCrypto.getEncryptionCrypto().getX509Certificates(cryptoType); X509Certificate encryptionCert = null; if (certs != null && certs.length > 0) { encryptionCert = certs[0]; } EntityDescriptor entityDescriptor = SamlProtocol.createIdpMetadata( SystemBaseUrl.constructUrl("/idp/login", true), Base64.getEncoder().encodeToString(issuerCert != null ? issuerCert.getEncoded() : new byte[0]), Base64.getEncoder() .encodeToString(encryptionCert != null ? encryptionCert.getEncoded() : new byte[0]), nameIdFormats, SystemBaseUrl.constructUrl("/idp/login", true), SystemBaseUrl.constructUrl("/idp/login", true), SystemBaseUrl.constructUrl("/idp/logout", true)); Document doc = DOMUtils.createDocument(); doc.appendChild(doc.createElement("root")); return Response.ok(DOM2Writer.nodeToString(OpenSAMLUtil.toDom(entityDescriptor, doc, false))).build(); }
From source file:edu.kit.dama.mdm.content.oaipmh.impl.SimpleOAIPMHRepository.java
/** * Get all digital objects according to the arguments set at the provided * OAIPMHBuilder./*from w w w. j a v a 2 s . c o m*/ * * Depending of the values ot 'from', 'until' and 'metadataPrefix' set at * the OAIPMHBuilder the result list may contain all or a reduced list of * objects. The list might also be empty. In that case a proper OAI-PMH * error must be created by the caller. * * @param builder The OAIPMHBuilder. * * @return A list of entities which might be empty. */ private List<DigitalObject> getEntities(OAIPMHBuilder builder) { List<DigitalObject> results = new ArrayList<>(); String prefix = builder.getMetadataPrefix(); LOGGER.debug("Getting entities for metadata prefix {} from repository.", prefix); IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager(); mdm.setAuthorizationContext(getAuthorizationContext()); try { LOGGER.debug("Checking request for resumption token"); String resumptionToken = builder.getResumptionToken(); int currentCursor = 0; int overallCount = 0; //check resumption token if (resumptionToken != null) { String tokenValue = new String( Base64.getDecoder().decode(URLDecoder.decode(resumptionToken, "UTF-8"))); LOGGER.debug("Found token with value {}", tokenValue); String[] elements = tokenValue.split("/"); if (elements.length != 2) { LOGGER.error("Invalid resumption token. Returning OAI-PMH error BAD_RESUMPTION_TOKEN."); builder.addError(OAIPMHerrorcodeType.BAD_RESUMPTION_TOKEN, null); return new ArrayList<>(); } try { LOGGER.debug("Parsing token values."); currentCursor = Integer.parseInt(elements[0]); overallCount = Integer.parseInt(elements[1]); LOGGER.debug("Obtained {} as current cursor from token.", currentCursor); } catch (NumberFormatException ex) { //log error builder.addError(OAIPMHerrorcodeType.BAD_RESUMPTION_TOKEN, null); return new ArrayList<>(); } } else { LOGGER.debug("No resumption token found."); } if (DC_SCHEMA.getSchemaIdentifier().equals(prefix)) { LOGGER.debug("Using Dublin Core schema handling."); //handle default schema which is supported by ALL objects, so no complex query is needed. Date from = builder.getFromDate(); Date until = builder.getUntilDate(); if (from != null && until != null) { LOGGER.debug("Getting all digital objects from {} until {}.", from, until); results = mdm.findResultList( "SELECT o FROM DigitalObject o WHERE o.uploadDate>=?1 AND o.uploadDate <= ?2", new Object[] { from, until }, DigitalObject.class, currentCursor, maxElementsPerList); overallCount = (overallCount == 0) ? mdm.findSingleResult( "SELECT COUNT(o) FROM DigitalObject o WHERE o.uploadDate>=?1 AND o.uploadDate <= ?2", new Object[] { from, until }, Number.class).intValue() : overallCount; } else if (from != null && until == null) { LOGGER.debug("Getting all digital objects from {}.", from); results = mdm.findResultList("SELECT o FROM DigitalObject o WHERE o.uploadDate >= ?1", new Object[] { from }, DigitalObject.class, currentCursor, maxElementsPerList); overallCount = (overallCount == 0) ? mdm.findSingleResult("SELECT COUNT(o) FROM DigitalObject o WHERE o.uploadDate >= ?1", new Object[] { from }, Number.class).intValue() : overallCount; } else if (from == null && until != null) { LOGGER.debug("Getting all digital objects until {}.", until); results = mdm.findResultList("SELECT o FROM DigitalObject o WHERE o.uploadDate <= ?1", new Object[] { until }, DigitalObject.class, currentCursor, maxElementsPerList); overallCount = (overallCount == 0) ? mdm.findSingleResult("SELECT COUNT(o) FROM DigitalObject o WHERE o.uploadDate <= ?1", new Object[] { until }, Number.class).intValue() : overallCount; } else { LOGGER.debug("Getting all digital object."); results = mdm.findResultList("SELECT o FROM DigitalObject o", DigitalObject.class, currentCursor, maxElementsPerList); overallCount = (overallCount == 0) ? mdm.findSingleResult("SELECT COUNT(o) FROM DigitalObject o", Number.class).intValue() : overallCount; } } else { //@TODO Check where to obtain the metadata document if no MetadataIndexingTask entry is available, e.g. via DataOrganization? LOGGER.debug("Using custom schema handling for prefix {}.", prefix); //filter by special schema which might not be supported by all objects Date from = builder.getFromDate(); Date until = builder.getUntilDate(); if (from != null && until != null) { LOGGER.debug("Getting all digital objects from {} until {}.", from, until); results = mdm.findResultList( "SELECT o FROM DigitalObject o,MetadataIndexingTask t WHERE o.uploadDate>=?1 AND o.uploadDate <= ?2 AND t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?3", new Object[] { from, until, prefix }, DigitalObject.class, currentCursor, maxElementsPerList); overallCount = (overallCount == 0) ? mdm.findSingleResult( "SELECT o FROM DigitalObject o,MetadataIndexingTask t WHERE o.uploadDate>=?1 AND o.uploadDate <= ?2 AND t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?3", new Object[] { from, until, prefix }, Number.class).intValue() : overallCount; } else if (from != null && until == null) { LOGGER.debug("Getting all digital objects from {}.", from); results = mdm.findResultList( "SELECT o FROM DigitalObject o,MetadataIndexingTask t WHERE o.uploadDate>=?1 AND t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?2", new Object[] { from, prefix }, DigitalObject.class, currentCursor, maxElementsPerList); overallCount = (overallCount == 0) ? mdm.findSingleResult( "SELECT COUNT(o) FROM DigitalObject o,MetadataIndexingTask t WHERE o.uploadDate>=?1 AND t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?2", new Object[] { from, prefix }, Number.class).intValue() : overallCount; } else if (from == null && until != null) { LOGGER.debug("Getting all digital objects until {}.", until); results = mdm.findResultList( "SELECT o FROM DigitalObject o,MetadataIndexingTask t WHERE o.uploadDate <= ?1 AND t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?2", new Object[] { until, prefix }, DigitalObject.class, currentCursor, maxElementsPerList); overallCount = (overallCount == 0) ? mdm.findSingleResult( "SELECT COUNT(o) FROM DigitalObject o,MetadataIndexingTask t WHERE o.uploadDate <= ?1 AND t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?2", new Object[] { until, prefix }, Number.class).intValue() : overallCount; } else { LOGGER.debug("Getting all digital object."); results = mdm.findResultList( "SELECT o FROM DigitalObject o,MetadataIndexingTask t WHERE t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?1", new Object[] { prefix }, DigitalObject.class, currentCursor, maxElementsPerList); overallCount = (overallCount == 0) ? mdm.findSingleResult( "SELECT COUNT(o) FROM DigitalObject o,MetadataIndexingTask t WHERE t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?1", new Object[] { prefix }, Number.class).intValue() : overallCount; } } LOGGER.debug("Setting next resumption token."); if (currentCursor + maxElementsPerList > overallCount) { LOGGER.debug( "Cursor exceeds element count, no more elements available. Setting resumption token to 'null'."); //lsit complete, add no resumptiontoken builder.setResumptionToken(null); } else { ResumptionTokenType token = new ResumptionTokenType(); //set list size token.setCompleteListSize(BigInteger.valueOf(overallCount)); //set current cursor token.setCursor(BigInteger.valueOf(currentCursor + results.size())); LOGGER.debug("Setting new resumption token with cursor at position " + token.getCursor()); //we set no expiration as the token never expires String value = token.getCursor().intValue() + "/" + token.getCompleteListSize().intValue(); LOGGER.debug("Setting resumption token value to {}.", value); token.setValue(URLEncoder.encode(Base64.getEncoder().encodeToString(value.getBytes()), "UTF-8")); builder.setResumptionToken(token); } } catch (UnauthorizedAccessAttemptException | UnsupportedEncodingException ex) { //error LOGGER.error("Failed to get results from repository. Returning empty list.", ex); } finally { mdm.close(); } return results; }
From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java
@Test public void refreshAccessTokenWrongClientHeaderRefreshTest() { MockHttpServletRequest req = new MockHttpServletRequest(); MockHttpServletResponse res = new MockHttpServletResponse(); Authenticate.unmock();/* www .j a va 2 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.setTokens(generateToken(applicationUserSession), generateToken(applicationUserSession)); ApplicationUserAuthorization applicationUserAuthorization = new ApplicationUserAuthorization(user1, externalApp); applicationUserAuthorization.addSession(applicationUserSession); externalApp.addApplicationUserAuthorization(applicationUserAuthorization); String clientSecret = "fenixedu:fenixedu"; req.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString(clientSecret.getBytes(StandardCharsets.UTF_8))); req.addParameter(REFRESH_TOKEN, applicationUserSession.getRefreshToken()); req.addParameter(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); req.setMethod("POST"); req.setPathInfo("/refresh_token"); try { oauthServlet.service(req, res); Assert.assertEquals("must return status BAD_REQUEST", 400, res.getStatus()); } catch (ServletException | IOException e) { Assert.fail(e.getMessage()); } }