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:eu.peppol.outbound.transmission.As2MessageSender.java

SendResult send(InputStream inputStream, ParticipantId recipient, ParticipantId sender,
        PeppolDocumentTypeId peppolDocumentTypeId, SmpLookupManager.PeppolEndpointData peppolEndpointData,
        PeppolAs2SystemIdentifier as2SystemIdentifierOfSender) {

    if (peppolEndpointData.getCommonName() == null) {
        throw new IllegalArgumentException("No common name in EndPoint object. " + peppolEndpointData);
    }// w w  w. j  av a  2s. c  o  m
    X509Certificate ourCertificate = keystoreManager.getOurCertificate();

    SMimeMessageFactory sMimeMessageFactory = new SMimeMessageFactory(keystoreManager.getOurPrivateKey(),
            ourCertificate);
    MimeMessage signedMimeMessage = null;
    Mic mic = null;
    try {
        MimeBodyPart mimeBodyPart = MimeMessageHelper.createMimeBodyPart(inputStream,
                new MimeType("application/xml"));
        mic = MimeMessageHelper.calculateMic(mimeBodyPart);
        log.debug("Outbound MIC is : " + mic.toString());
        signedMimeMessage = sMimeMessageFactory.createSignedMimeMessage(mimeBodyPart);
    } catch (MimeTypeParseException e) {
        throw new IllegalStateException("Problems with MIME types: " + e.getMessage(), e);
    }

    String endpointAddress = peppolEndpointData.getUrl().toExternalForm();
    HttpPost httpPost = new HttpPost(endpointAddress);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {
        signedMimeMessage.writeTo(byteArrayOutputStream);

    } catch (Exception e) {
        throw new IllegalStateException("Unable to stream S/MIME message into byte array output stream");
    }

    httpPost.addHeader(As2Header.AS2_FROM.getHttpHeaderName(), as2SystemIdentifierOfSender.toString());
    try {
        httpPost.setHeader(As2Header.AS2_TO.getHttpHeaderName(),
                PeppolAs2SystemIdentifier.valueOf(peppolEndpointData.getCommonName()).toString());
    } catch (InvalidAs2SystemIdentifierException e) {
        throw new IllegalArgumentException(
                "Unable to create valid AS2 System Identifier for receiving end point: " + peppolEndpointData);
    }

    httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_TO.getHttpHeaderName(), "not.in.use@difi.no");
    httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_OPTIONS.getHttpHeaderName(),
            As2DispositionNotificationOptions.getDefault().toString());
    httpPost.addHeader(As2Header.AS2_VERSION.getHttpHeaderName(), As2Header.VERSION);
    httpPost.addHeader(As2Header.SUBJECT.getHttpHeaderName(), "AS2 message from OXALIS");

    TransmissionId transmissionId = new TransmissionId();
    httpPost.addHeader(As2Header.MESSAGE_ID.getHttpHeaderName(), transmissionId.toString());
    httpPost.addHeader(As2Header.DATE.getHttpHeaderName(), As2DateUtil.format(new Date()));

    // Inserts the S/MIME message to be posted.
    // Make sure we pass the same content type as the SignedMimeMessage, it'll end up as content-type HTTP header
    try {
        String contentType = signedMimeMessage.getContentType();
        ContentType ct = ContentType.create(contentType);
        httpPost.setEntity(new ByteArrayEntity(byteArrayOutputStream.toByteArray(), ct));
    } catch (Exception ex) {
        throw new IllegalStateException("Unable to set request header content type : " + ex.getMessage());
    }

    CloseableHttpResponse postResponse = null; // EXECUTE !!!!
    try {
        CloseableHttpClient httpClient = createCloseableHttpClient();
        log.debug("Sending AS2 from " + sender + " to " + recipient + " at " + endpointAddress + " type "
                + peppolDocumentTypeId);
        postResponse = httpClient.execute(httpPost);
    } catch (HttpHostConnectException e) {
        throw new IllegalStateException("The Oxalis server does not seem to be running at " + endpointAddress);
    } catch (Exception e) {
        throw new IllegalStateException(
                "Unexpected error during execution of http POST to " + endpointAddress + ": " + e.getMessage(),
                e);
    }

    if (postResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        log.error("AS2 HTTP POST expected HTTP OK, but got : " + postResponse.getStatusLine().getStatusCode()
                + " from " + endpointAddress);
        throw handleFailedRequest(postResponse);
    }

    // handle normal HTTP OK response
    log.debug("AS2 transmission " + transmissionId + " to " + endpointAddress
            + " returned HTTP OK, verify MDN response");
    MimeMessage mimeMessage = handleTheHttpResponse(transmissionId, mic, postResponse, peppolEndpointData);

    // Transforms the signed MDN into a generic a As2RemWithMdnTransmissionEvidenceImpl
    MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage);
    Map<String, String> mdnFields = mdnMimeMessageInspector.getMdnFields();
    String messageDigestAsBase64 = mdnFields.get(MdnMimeMessageFactory.X_ORIGINAL_MESSAGE_DIGEST);
    if (messageDigestAsBase64 == null) {
        messageDigestAsBase64 = new String(Base64.getEncoder().encode("null".getBytes()));
    }
    String receptionTimeStampAsString = mdnFields.get(MdnMimeMessageFactory.X_PEPPOL_TIME_STAMP);
    Date receptionTimeStamp = null;
    if (receptionTimeStampAsString != null) {
        receptionTimeStamp = As2DateUtil.parseIso8601TimeStamp(receptionTimeStampAsString);
    } else {
        receptionTimeStamp = new Date();
    }

    // Converts the Oxalis DocumentTypeIdentifier into the corresponding type for peppol-evidence
    DocumentTypeIdentifier documentTypeIdentifier = new DocumentTypeIdentifier(peppolDocumentTypeId.toString());

    @NotNull
    As2RemWithMdnTransmissionEvidenceImpl evidence = as2TransmissionEvidenceFactory.createEvidence(
            EventCode.DELIVERY, TransmissionRole.C_2, mimeMessage,
            new ParticipantIdentifier(recipient.stringValue()), // peppol-evidence uses it's own types
            new ParticipantIdentifier(sender.stringValue()), // peppol-evidence uses it's own types
            documentTypeIdentifier, receptionTimeStamp, Base64.getDecoder().decode(messageDigestAsBase64),
            transmissionId);

    ByteArrayOutputStream evidenceBytes;
    try {
        evidenceBytes = new ByteArrayOutputStream();
        IOUtils.copy(evidence.getInputStream(), evidenceBytes);
    } catch (IOException e) {
        throw new IllegalStateException(
                "Unable to transform transport evidence to byte array." + e.getMessage(), e);
    }

    return new SendResult(transmissionId, evidenceBytes.toByteArray());
}

From source file:org.pentaho.di.kitchen.KitchenIT.java

@Test
public void testJobExecutionFromWithinProvidedZip() throws Exception {

    String testZipRelativePath = "test-kjb.zip";
    String testKJBWithinZip = "Job.kjb";

    File zipFile = null;/*from ww  w  . ja v  a  2s.  c o  m*/

    try {
        zipFile = new File(getClass().getResource(testZipRelativePath).toURI());
        String base64Zip = Base64.getEncoder().encodeToString(FileUtils.readFileToByteArray(zipFile));

        Kitchen.main(new String[] { "/file:" + testKJBWithinZip, "/level:Basic", "/zip:" + base64Zip });

    } catch (SecurityException e) {
        // All OK / expected: SecurityException is purposely thrown when Kitchen triggers System.exitJVM()
        Result result = Kitchen.getCommandExecutor().getResult();
        assertNotNull(result);
        assertEquals(CommandExecutorCodes.Kitchen.SUCCESS.getCode(), result.getExitStatus());
    }
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditorTest.java

License:asdf

private void addPrivateKey(KeystoreEditor keystoreEditor, File keyFile, String type)
        throws KeystoreEditor.KeystoreEditorException, IOException {
    FileInputStream fileInputStream = new FileInputStream(keyFile);
    byte[] keyBytes = IOUtils.toByteArray(fileInputStream);
    IOUtils.closeQuietly(fileInputStream);
    keystoreEditor.addPrivateKey("asdf", password, "", Base64.getEncoder().encodeToString(keyBytes), type,
            keyFile.toString());//  w w  w.j a  va 2s  .  co m
}

From source file:de.steilerdev.myVerein.server.model.User.java

@Transient
@JsonIgnore//from   w  w  w. j  av a 2s.  c  o  m
public String getDeviceTokenBase64Encoded() {
    if (deviceToken != null && deviceToken.length == 32) {
        return Base64.getEncoder().encodeToString(deviceToken);
    } else {
        return null;
    }
}

From source file:org.appverse.web.framework.backend.test.util.oauth2.tests.predefined.authorizationcode.Oauth2AuthorizationCodeFlowPredefinedTests.java

@Test
public void obtainTokenFromOuth2LoginEndpoint() throws Exception {
    obtainAuthorizationCode();//from  w  w  w .  j a  v a2  s.  co m
    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(authServerBaseUrl + oauth2TokenEndpointPath);
    // Here we don't authenticate the user, we authenticate the client and we pass the authcode proving that the user has accepted and loged in        
    builder.queryParam("client_id", getClientId());
    builder.queryParam("grant_type", "authorization_code");
    builder.queryParam("code", authorizationCode);
    builder.queryParam("redirect_uri", "http://anywhere");

    // Add Basic Authorization headers for CLIENT authentication (user was authenticated in previous request (authorization code)
    HttpHeaders headers = new HttpHeaders();
    Encoder encoder = Base64.getEncoder();
    headers.add("Authorization",
            "Basic " + encoder.encodeToString((getClientId() + ":" + getClientSecret()).getBytes()));

    HttpEntity<String> entity = new HttpEntity<>("", headers);
    ResponseEntity<OAuth2AccessToken> result2 = restTemplate.exchange(builder.build().encode().toUri(),
            HttpMethod.POST, entity, OAuth2AccessToken.class);

    // This means the user was correctly authenticated, then a redirection was performed to /oauth/authorize to obtain the token.
    // Then the token was sucessfully obtained (authenticating the client properly) and a last redirection was performed to the 
    // redirect_uri with the token after #
    assertEquals(HttpStatus.OK, result2.getStatusCode());

    // Obtain and keep the token
    accessToken = result2.getBody().getValue();
    assertNotNull(accessToken);

    refreshToken = result2.getBody().getRefreshToken().getValue();
    assertNotNull(refreshToken);
}

From source file:SdkUnitTests.java

@Test
public void EmbeddedSigningTest() {
    byte[] fileBytes = null;
    try {/*  w  w w  . j  a  v a2  s  . co  m*/
        //  String currentDir = new java.io.File(".").getCononicalPath();

        String currentDir = System.getProperty("user.dir");

        Path path = Paths.get(currentDir + SignTest1File);
        fileBytes = Files.readAllBytes(path);
    } catch (IOException ioExcp) {
        Assert.assertEquals(null, ioExcp);
    }

    // create an envelope to be signed
    EnvelopeDefinition envDef = new EnvelopeDefinition();
    envDef.setEmailSubject("Please Sign my Java SDK Envelope (Embedded Signer)");
    envDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope.");

    // add a document to the envelope
    Document doc = new Document();
    String base64Doc = Base64.getEncoder().encodeToString(fileBytes);
    doc.setDocumentBase64(base64Doc);
    doc.setName("TestFile.pdf");
    doc.setDocumentId("1");

    List<Document> docs = new ArrayList<Document>();
    docs.add(doc);
    envDef.setDocuments(docs);

    // Add a recipient to sign the document
    Signer signer = new Signer();
    signer.setEmail(UserName);
    String name = "Pat Developer";
    signer.setName(name);
    signer.setRecipientId("1");

    // this value represents the client's unique identifier for the signer
    String clientUserId = "2939";
    signer.setClientUserId(clientUserId);

    // Create a SignHere tab somewhere on the document for the signer to sign
    SignHere signHere = new SignHere();
    signHere.setDocumentId("1");
    signHere.setPageNumber("1");
    signHere.setRecipientId("1");
    signHere.setXPosition("100");
    signHere.setYPosition("100");

    List<SignHere> signHereTabs = new ArrayList<SignHere>();
    signHereTabs.add(signHere);
    Tabs tabs = new Tabs();
    tabs.setSignHereTabs(signHereTabs);
    signer.setTabs(tabs);

    // Above causes issue
    envDef.setRecipients(new Recipients());
    envDef.getRecipients().setSigners(new ArrayList<Signer>());
    envDef.getRecipients().getSigners().add(signer);

    // send the envelope (otherwise it will be "created" in the Draft folder
    envDef.setStatus("sent");

    try {

        ApiClient apiClient = new ApiClient();
        apiClient.setBasePath(BaseUrl);

        String creds = createAuthHeaderCreds(UserName, Password, IntegratorKey);
        apiClient.addDefaultHeader("X-DocuSign-Authentication", creds);
        Configuration.setDefaultApiClient(apiClient);

        AuthenticationApi authApi = new AuthenticationApi();
        LoginInformation loginInfo = authApi.login();

        Assert.assertNotSame(null, loginInfo);
        Assert.assertNotNull(loginInfo.getLoginAccounts());
        Assert.assertTrue(loginInfo.getLoginAccounts().size() > 0);
        List<LoginAccount> loginAccounts = loginInfo.getLoginAccounts();
        Assert.assertNotNull(loginAccounts.get(0).getAccountId());

        String accountId = loginInfo.getLoginAccounts().get(0).getAccountId();

        EnvelopesApi envelopesApi = new EnvelopesApi();
        EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId, envDef);

        Assert.assertNotNull(envelopeSummary);
        Assert.assertNotNull(envelopeSummary.getEnvelopeId());

        System.out.println("EnvelopeSummary: " + envelopeSummary);

        String returnUrl = "http://www.docusign.com/developer-center";
        RecipientViewRequest recipientView = new RecipientViewRequest();
        recipientView.setReturnUrl(returnUrl);
        recipientView.setClientUserId(clientUserId);
        recipientView.setAuthenticationMethod("email");
        recipientView.setUserName(name);
        recipientView.setEmail(UserName);

        ViewUrl viewUrl = envelopesApi.createRecipientView(loginInfo.getLoginAccounts().get(0).getAccountId(),
                envelopeSummary.getEnvelopeId(), recipientView);

        Assert.assertNotNull(viewUrl);
        Assert.assertNotNull(viewUrl.getUrl());

        // This Url should work in an Iframe or browser to allow signing
        System.out.println("ViewUrl is " + viewUrl);

    } catch (ApiException ex) {
        System.out.println("Exception: " + ex);
        Assert.assertEquals(null, ex);
    }

}

From source file:io.pravega.controller.store.stream.ZKStreamMetadataStore.java

private String encodedScopedStreamName(String scope, String stream) {
    String scopedStreamName = getScopedStreamName(scope, stream);
    return Base64.getEncoder().encodeToString(scopedStreamName.getBytes());
}

From source file:cd.go.contrib.elasticagents.dockerswarm.elasticagent.DockerServiceElasticAgentTest.java

@Test
public void shouldStartContainerWithSecret() throws Exception {
    requireDockerApiVersionAtLeast("1.26", "Swarm secret support");

    final String secretName = UUID.randomUUID().toString();
    final SecretCreateResponse secret = docker.createSecret(SecretSpec.builder().name(secretName)
            .data(Base64.getEncoder().encodeToString("some-random-junk".getBytes()))
            .labels(Collections/*from w  w  w . j a  v  a  2  s .  c  o m*/
                    .singletonMap("cd.go.contrib.elasticagents.dockerswarm.elasticagent.DockerPlugin", ""))
            .build());

    final List<String> command = Arrays.asList("/bin/sh", "-c", "cat /run/secrets/" + secretName);
    Map<String, String> properties = new HashMap<>();
    properties.put("Image", "alpine:latest");
    properties.put("Secrets", "src=" + secretName);
    properties.put("Command", StringUtils.join(command, "\n"));

    DockerService service = DockerService.create(
            new CreateAgentRequest("key", properties, "prod", new JobIdentifier(100L)), createSettings(),
            docker);
    services.add(service.name());

    final Service inspectService = docker.inspectService(service.name());
    final SecretBind secretBind = inspectService.spec().taskTemplate().containerSpec().secrets().get(0);

    assertThat(secretBind.secretName(), is(secretName));
    assertThat(secretBind.secretId(), is(secret.id()));
}

From source file:com.rapid7.Plugin.java

/**
 * @return the endpoint//from w w w . ja  va2 s.  c  o m
 */
private String getBasicAuth() {
    String token = getUsername() + ":" + getPassword();
    return "Basic " + Base64.getEncoder().encodeToString(token.getBytes());
}

From source file:ai.susi.server.AbstractAPIHandler.java

/**
 * Create a hash for an input an salt//from ww w .  j  av  a  2 s. c om
 * @param input
 * @param salt
 * @return String hash
 */
public static String getHash(String input, String salt) {
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update((salt + input).getBytes());
        return Base64.getEncoder().encodeToString(md.digest());
    } catch (NoSuchAlgorithmException e) {
        Log.getLog().warn(e);
    }
    return null;
}