List of usage examples for java.util Base64 getEncoder
public static Encoder getEncoder()
From source file:org.egov.mrs.domain.service.MarriageRegistrationService.java
public void prepareDocumentsForView(final MarriageRegistration registration) { if (registration.getRegistrationDocuments() != null) registration.getRegistrationDocuments().forEach(appDoc -> { final File file = fileStoreService.fetch(appDoc.getFileStoreMapper().getFileStoreId(), MarriageConstants.FILESTORE_MODULECODE); try { appDoc.setBase64EncodedFile( Base64.getEncoder().encodeToString(FileCopyUtils.copyToByteArray(file))); } catch (final IOException e) { LOG.error("Error while preparing the document for view", e); }// w w w.ja va 2 s . c om }); if (registration.getMarriagePhotoFileStore() != null) { final File file = fileStoreService.fetch(registration.getMarriagePhotoFileStore().getFileStoreId(), MarriageConstants.FILESTORE_MODULECODE); try { registration.setEncodedMarriagePhoto( Base64.getEncoder().encodeToString(FileCopyUtils.copyToByteArray(file))); } catch (final IOException e) { LOG.error("Error while preparing the document for view", e); } } }
From source file:com.joyent.manta.http.EncryptionHttpHelper.java
/** * Attaches encrypted metadata (with e-* values) to the object. * * @param metadata metadata to append additional values to * @throws IOException thrown when there is a problem attaching metadata *//*ww w . j a v a2 s . c o m*/ public void attachEncryptedMetadata(final MantaMetadata metadata) throws IOException { // Create and add encrypted metadata Cipher metadataCipher = buildMetadataEncryptCipher(); metadata.put(MantaHttpHeaders.ENCRYPTION_CIPHER, cipherDetails.getCipherId()); String metadataIvBase64 = Base64.getEncoder().encodeToString(metadataCipher.getIV()); metadata.put(MantaHttpHeaders.ENCRYPTION_METADATA_IV, metadataIvBase64); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Encrypted metadata IV: {}", Hex.encodeHexString(metadataCipher.getIV())); } String metadataPlainTextString = EncryptedMetadataUtils.encryptedMetadataAsString(metadata); LOGGER.debug("Encrypted metadata plaintext:\n{}", metadataPlainTextString); LOGGER.debug("Encrypted metadata ciphertext: {}", metadataIvBase64); byte[] metadataCipherText = encryptMetadata(metadataPlainTextString, metadataCipher); String metadataCipherTextBase64 = Base64.getEncoder().encodeToString(metadataCipherText); if (metadataCipherTextBase64.length() > MAX_METADATA_CIPHERTEXT_BASE64_SIZE) { String msg = "Encrypted metadata exceeded the maximum size allowed"; MantaClientEncryptionException e = new MantaClientEncryptionException(msg); e.setContextValue("max_size", MAX_METADATA_CIPHERTEXT_BASE64_SIZE); e.setContextValue("actual_size", metadataCipherTextBase64.length()); throw e; } metadata.put(MantaHttpHeaders.ENCRYPTION_METADATA, metadataCipherTextBase64); if (!this.cipherDetails.isAEADCipher()) { final HMac hmac = this.cipherDetails.getAuthenticationHmac(); initHmac(this.secretKey, hmac); hmac.update(metadataCipherText, 0, metadataCipherText.length); byte[] checksum = new byte[hmac.getMacSize()]; hmac.doFinal(checksum, 0); String checksumBase64 = Base64.getEncoder().encodeToString(checksum); metadata.put(MantaHttpHeaders.ENCRYPTION_METADATA_HMAC, checksumBase64); LOGGER.debug("Encrypted metadata HMAC: {}", checksumBase64); } else { metadata.put(MantaHttpHeaders.ENCRYPTION_METADATA_AEAD_TAG_LENGTH, String.valueOf(this.cipherDetails.getAuthenticationTagOrHmacLengthInBytes())); } }
From source file:org.codice.ddf.security.idp.server.IdpEndpoint.java
private Response getSamlPostResponse(SignableSAMLObject samlObject, String targetUrl, String relayState, SamlProtocol.Type samlType) throws SimpleSign.SignatureException, WSSecurityException { Document doc = DOMUtils.createDocument(); doc.appendChild(doc.createElement("root")); LOGGER.debug("Signing SAML POST Response."); new SimpleSign(systemCrypto).signSamlObject(samlObject); LOGGER.debug("Converting SAML Response to DOM"); String assertionResponse = DOM2Writer.nodeToString(OpenSAMLUtil.toDom(samlObject, doc)); String encodedSamlResponse = Base64.getEncoder() .encodeToString(assertionResponse.getBytes(StandardCharsets.UTF_8)); return Response.ok(HtmlResponseTemplate.getPostPage(targetUrl, samlType, encodedSamlResponse, relayState)) .build();/*w w w . j av a 2s .c o m*/ }
From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java
@Test public void testOAuthServletAccessTokenRequestWithLoginExpired() { MockHttpServletRequest req = new MockHttpServletRequest(); MockHttpServletResponse res = new MockHttpServletResponse(); Authenticate.unmock();/* w w w . j a v a 2 s .c om*/ User user = createUser("testOAuthServletAccessTokenRequestWithLoginExpired", "John", "Doe", "John Doe", "john.doe@fenixedu.org"); user.closeLoginPeriod(); 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(user, 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 bad request", Status.BAD_REQUEST.getStatusCode(), res.getStatus()); user.openLoginPeriod(); res = new MockHttpServletResponse(); oauthServlet.service(req, res); final JsonObject token = new JsonParser().parse(res.getContentAsString()).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:com.joyent.manta.http.MantaHttpHeaders.java
/** * Sets the {@code authorization} header as specified in <a * href="http://tools.ietf.org/html/rfc2617#section-2">Basic Authentication Scheme</a>. * * <p>/*from w w w . j av a 2s . co m*/ * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @param username {@code java.lang.String} value for the username component of the authorization header * @param password {@code java.lang.String} value for the password component of the authorization header * @return this instance */ @Deprecated public MantaHttpHeaders setBasicAuthentication(final String username, final String password) { Validate.notNull(username, "Username must not be null"); Validate.notNull(password, "Password must not be null"); String userPass = String.format("%s:%s", username, password); String encoded = Base64.getEncoder().encodeToString(userPass.getBytes(StandardCharsets.UTF_8)); return setAuthorization("Basic " + encoded); }
From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java
@Test public void testOAuthServletRefreshTokenRequestWithLoginExpired() { MockHttpServletRequest req = new MockHttpServletRequest(); MockHttpServletResponse res = new MockHttpServletResponse(); Authenticate.unmock();// w ww. jav a 2s . c om User user = createUser("testOAuthServletRefreshTokenRequestWithLoginExpired", "John", "Doe", "John Doe", "john.doe@fenixedu.org"); user.closeLoginPeriod(); 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(user, 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 bad request", Status.BAD_REQUEST.getStatusCode(), res.getStatus()); user.openLoginPeriod(); res = new MockHttpServletResponse(); oauthServlet.service(req, res); final JsonObject token = new JsonParser().parse(res.getContentAsString()).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.opensingular.internal.lib.commons.xml.TestMElement.java
License:asdf
@Test public void testFromBase64OutPutStream() throws IOException { TempFileProvider.create(this, tmpProvider -> { MElement raiz = MElement.newInstance("raiz"); raiz.addElement("string", Base64.getEncoder().encodeToString("stringVal".getBytes())); File arquivoTemporario = tmpProvider.createTempFile(Long.toString(System.currentTimeMillis()) + ".txt"); FileOutputStream outputStream = new FileOutputStream(arquivoTemporario); raiz.getByteBASE64("string", outputStream); outputStream.close();/* www. ja v a 2 s .c o m*/ }); }
From source file:com.simiacryptus.mindseye.lang.Tensor.java
/** * To json json element.//from ww w . jav a 2 s. c o m * * @param resources the resources * @param dataSerializer the data serializer * @return the json element */ @Nonnull public JsonElement toJson(@Nullable Map<CharSequence, byte[]> resources, @Nonnull DataSerializer dataSerializer) { if (length() > 1024) { @Nonnull JsonObject obj = new JsonObject(); @Nonnull int[] dimensions = getDimensions(); obj.add("length", toJsonArray(dimensions)); if (null != id) obj.addProperty("id", id.toString()); @Nonnull byte[] bytes = getBytes(dataSerializer); obj.addProperty("precision", ((SerialPrecision) dataSerializer).name()); if (null != resources) { @Nonnull String id = UUID.randomUUID().toString(); obj.addProperty("resource", id); resources.put(id, bytes); } else { obj.addProperty("base64", Base64.getEncoder().encodeToString(bytes)); } return obj; } else { return toJson(new int[] {}); } }
From source file:com.vmware.admiral.adapter.docker.service.DockerAdapterService.java
private void fetchRegistryAuthState(String registryStateLink, RequestContext context, Runnable callback) { URI registryStateUri = UriUtils.buildUri(getHost(), registryStateLink, UriUtils.URI_PARAM_ODATA_EXPAND); Operation getRegistry = Operation.createGet(registryStateUri).setCompletion((o, ex) -> { if (ex != null) { context.operation.fail(ex);//from ww w .j av a2 s .co m return; } RegistryAuthState registryState = o.getBody(RegistryAuthState.class); if (registryState.authCredentials != null) { AuthCredentialsServiceState authState = registryState.authCredentials; AuthCredentialsType authType = AuthCredentialsType.valueOf(authState.type); if (AuthCredentialsType.Password.equals(authType)) { // create and encode AuthConfig AuthConfig authConfig = new AuthConfig(); authConfig.username = authState.userEmail; authConfig.password = EncryptionUtils.decrypt(authState.privateKey); authConfig.email = ""; authConfig.auth = ""; DockerImage image = DockerImage.fromImageName(context.containerDescription.image); authConfig.serveraddress = image.getHost(); String authConfigJson = Utils.toJson(authConfig); String authConfigEncoded = new String(Base64.getEncoder().encode(authConfigJson.getBytes())); context.commandInput.getProperties().put(DOCKER_IMAGE_REGISTRY_AUTH, authConfigEncoded); getHost().log(Level.INFO, "Detected registry requiring basic authn, %s header created.", DOCKER_IMAGE_REGISTRY_AUTH); } } callback.run(); }); sendRequest(getRegistry); }
From source file:com.joyent.manta.client.crypto.MantaEncryptedObjectInputStreamTest.java
private 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 ww . jav a 2 s. co m 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); }