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:com.github.horrorho.inflatabledonkey.requests.EscrowProxyRequestFactory.java

public HttpUriRequest srpInit(byte[] key) throws IOException {
    String uri = escrowProxyUrl + "/escrowproxy/api/srp_init";
    String authorization = AccessTokens.MOBILEMEAUTHTOKEN.token(dsPrsID, mmeAuthToken);
    String encodedKey = Base64.getEncoder().encodeToString(key);

    String post = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
            + "<plist version=\"1.0\">\n" + "<dict>\n" + "   <key>blob</key>\n" + "   <string>" + encodedKey
            + "</string>\n" + "   <key>command</key>\n" + "   <string>SRP_INIT</string>\n"
            + "   <key>label</key>\n" + "   <string>com.apple.protectedcloudstorage.record</string>\n"
            + "   <key>version</key>\n" + "   <integer>1</integer>\n" + "</dict>\n" + "</plist>";
    logger.trace("-- srpInit() - post: {}", post);

    HttpUriRequest request = RequestBuilder.post(uri)
            .addHeader(HttpHeaders.CONTENT_TYPE, "application/x-apple-plist")
            .addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
            .addHeader(HttpHeaders.AUTHORIZATION, authorization).addHeader(headers.get(Headers.USERAGENT))
            .addHeader(headers.get(Headers.XMMECLIENTINFO))
            .setEntity(new StringEntity(post, StandardCharsets.UTF_8)).build();

    return request;
}

From source file:bg.vitkinov.edu.services.JokeService.java

@RequestMapping(value = "/jokeImage/{id}", method = RequestMethod.GET, produces = { MediaType.IMAGE_PNG_VALUE })
public ResponseEntity<byte[]> getJokeImage(@PathVariable Long id,
        @RequestHeader(value = "Accept") String acceptType,
        @RequestParam(required = false, defaultValue = "Arial-14") String font,
        @RequestParam(required = false, defaultValue = "black") String foreColor,
        @RequestParam(required = false) String backColor) {
    Joke joke = jokeRepository.findOne(id);
    ServiceInstance instance = loadBalancerClient.choose("image-service");
    if (instance == null)
        return null;
    /*/*from  w  ww . ja va 2 s.co m*/
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.set("text", Base64.getEncoder().encodeToString(joke.getContent().getBytes()));
      params.set("Accept", acceptType);
      params.set("base64", "true");
      params.set("font", font);
      params.set("foreColor", foreColor);
      params.set("foreColor", foreColor);
      params.set("backColor", backColor);
      */
    HttpHeaders params = new HttpHeaders();
    MediaType requestAcceptType = acceptType == null || "".equals(acceptType) ? MediaType.IMAGE_PNG
            : MediaType.parseMediaType(acceptType);
    params.setAccept(Arrays.asList(requestAcceptType));
    params.add("text", Base64.getEncoder().encodeToString(joke.getContent().getBytes()));
    params.add("base64", "true");
    params.add("font", font);
    params.add("foreColor", foreColor);
    params.add("backColor", backColor);

    //        URI url = URI.create(String.format("%s/img", instance.getUri().toString()))
    URI url = instance.getUri().resolve("/img");
    HttpEntity<byte[]> entity = new HttpEntity<byte[]>(null, params);
    return restTemplate.exchange(url.toString(), HttpMethod.POST, entity, byte[].class);
}

From source file:org.codice.alliance.distribution.branding.AllianceBrandingPlugin.java

@Override
public String getBase64FavIcon() throws IOException {
    byte[] favIconAsBytes = IOUtils.toByteArray(AllianceBrandingPlugin.class.getResourceAsStream(getFavIcon()));
    if (favIconAsBytes.length > 0) {
        return Base64.getEncoder().encodeToString(favIconAsBytes);
    }/*from  ww w.ja v a 2s . co  m*/
    return "";
}

From source file:it.greenvulcano.gvesb.utils.ResultSetUtils.java

/**
 * Returns all values from the ResultSet as an XML.
 * For instance, if the ResultSet has 3 values, the returned XML will have following fields:
 *                                <RowSet>
 *                                  <data>
 *                                    <row>
 *                                      <col>value1</col>
 *                                      <col>value2</col>
 *                                      <col>value3</col>
 *                                    </row>
 *                                    <row>
 *                                      <col>value4</col>
 *                                      <col>value5</col>
 *                                      <col>value6</col>
 *                                    </row>
 *                                  ..//from  w w  w . j  ava 2  s.  c om
 *                                    <row>
 *                                      <col>valuex</col>
 *                                      <col>valuey</col>
 *                                      <col>valuez</col>
 *                                    </row>
 *                                  </data>
 *                                </RowSet>
 * @param rs
 * @return
 * @throws Exception
 */
public static Document getResultSetAsDOM(ResultSet rs) throws Exception {
    XMLUtils xml = XMLUtils.getParserInstance();
    try {
        Document doc = xml.newDocument("RowSet");
        Element docRoot = doc.getDocumentElement();

        if (rs != null) {
            try {
                ResultSetMetaData metadata = rs.getMetaData();
                Element data = null;
                Element row = null;
                Element col = null;
                Text text = null;
                String textVal = null;
                while (rs.next()) {
                    boolean restartResultset = false;
                    for (int j = 1; j <= metadata.getColumnCount() && !restartResultset; j++) {
                        col = xml.createElement(doc, "col");
                        restartResultset = false;
                        switch (metadata.getColumnType(j)) {
                        case Types.CLOB: {
                            Clob clob = rs.getClob(j);
                            if (clob != null) {
                                Reader is = clob.getCharacterStream();
                                StringWriter strW = new StringWriter();

                                IOUtils.copy(is, strW);
                                is.close();
                                textVal = strW.toString();
                            } else {
                                textVal = "";
                            }
                        }
                            break;
                        case Types.BLOB: {
                            Blob blob = rs.getBlob(j);
                            if (blob != null) {
                                InputStream is = blob.getBinaryStream();
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                IOUtils.copy(is, baos);
                                is.close();
                                try {
                                    byte[] buffer = Arrays.copyOf(baos.toByteArray(), (int) blob.length());
                                    textVal = new String(Base64.getEncoder().encode(buffer));
                                } catch (SQLFeatureNotSupportedException exc) {
                                    textVal = new String(Base64.getEncoder().encode(baos.toByteArray()));
                                }
                            } else {
                                textVal = "";
                            }
                        }
                            break;
                        case -10: { // OracleTypes.CURSOR
                            Object obj = rs.getObject(j);
                            if (obj instanceof ResultSet) {
                                rs = (ResultSet) obj;
                                metadata = rs.getMetaData();
                            }
                            restartResultset = true;
                        }
                            break;
                        default: {
                            textVal = rs.getString(j);
                            if (textVal == null) {
                                textVal = "";
                            }
                        }
                        }
                        if (restartResultset) {
                            continue;
                        }
                        if (row == null || j == 1) {
                            row = xml.createElement(doc, "row");
                        }
                        if (textVal != null) {
                            text = doc.createTextNode(textVal);
                            col.appendChild(text);
                        }
                        row.appendChild(col);
                    }
                    if (row != null) {
                        if (data == null) {
                            data = xml.createElement(doc, "data");
                        }
                        data.appendChild(row);
                    }
                }
                if (data != null) {
                    docRoot.appendChild(data);
                }
            } finally {
                if (rs != null) {
                    try {
                        rs.close();
                    } catch (Exception exc) {
                        // do nothing
                    }
                    rs = null;
                }
            }
        }

        return doc;
    } finally {
        XMLUtils.releaseParserInstance(xml);
    }
}

From source file:org.codice.ddf.catalog.ui.security.app.UserApplication.java

private void setUserPreferences(Subject subject, Map<String, Object> preferences) {
    String json = GSON.toJson(preferences);

    LOGGER.trace("preferences JSON text:\n {}", json);

    String userid = subjectIdentity.getUniqueIdentifier(subject);

    LOGGER.trace("Update preferences for: {}", userid);

    PersistentItem item = new PersistentItem();
    item.addIdProperty(userid);/* www .  j  av  a 2s . c  o m*/
    item.addProperty("user", userid);
    item.addProperty("preferences_json", "_bin",
            Base64.getEncoder().encodeToString(json.getBytes(Charset.defaultCharset())));

    try {
        persistentStore.add(PersistenceType.PREFERENCES_TYPE.toString(), item);
    } catch (PersistenceException e) {
        LOGGER.info("PersistenceException while trying to persist preferences for user {}", userid, e);
    }
}

From source file:org.apache.nifi.registry.web.api.SecureKerberosIT.java

@Before
public void generateAuthToken() {
    String validTicket = new String(
            Base64.getEncoder().encode(validKerberosTicket.getBytes(Charset.forName("UTF-8"))));
    final String token = client.target(createURL("/access/token/kerberos")).request()
            .header("Authorization", "Negotiate " + validTicket).post(null, String.class);
    adminAuthToken = token;//from ww w  .ja va  2 s . c o  m
}

From source file:alfio.model.Ticket.java

private static String hmacSHA256Base64(String key, String code) {
    return Base64.getEncoder().encodeToString(new HmacUtils(HmacAlgorithms.HMAC_SHA_256, key).hmac(code));
}

From source file:com.thoughtworks.go.apiv3.datasharing.usagedata.UsageStatisticsControllerV3.java

public String getEncryptedUsageStatistics(Request request, Response response) throws Exception {
    HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();

    Map<String, Object> body = readRequestBodyAsJSON(request);
    String signature = (String) body.get(SIGNATURE_KEY);
    String publicKey = (String) body.get(SUBORDINATE_PUBLIC_KEY);

    boolean isVerified = verifySignatureAndPublicKey(signature, publicKey, result);

    if (isVerified) {
        SecretKey secretKey = EncryptionHelper.generateAESKey();
        String aesEncryptedData = EncryptionHelper.encryptUsingAES(secretKey,
                getUsageStatistics(request, response));
        String rsaEncryptedKey = EncryptionHelper
                .encryptUsingRSA(Base64.getEncoder().encodeToString(secretKey.getEncoded()), publicKey);

        return jsonizeAsTopLevelObject(request,
                writer -> EncryptedDataRepresenter.toJSON(writer, aesEncryptedData, rsaEncryptedKey));
    }//from ww  w.ja  v  a2  s  . c o  m

    return renderHTTPOperationResult(result, request, response);
}

From source file:com.thoughtworks.go.server.util.EncryptionHelperTest.java

@Test
void shouldEncryptAndDecryptChunkUsingAESandRSA() throws Exception {
    String chunk = StringUtils.repeat("Encryption is awesome!", 150);

    File privateKeyFile = new File(
            getClass().getClassLoader().getResource("rsa/subordinate-private.pem").getFile());
    File publicKeyFile = new File(
            getClass().getClassLoader().getResource("rsa/subordinate-public.pem").getFile());

    SecretKey secretKey = EncryptionHelper.generateAESKey();

    String aesEncryptedData = EncryptionHelper.encryptUsingAES(secretKey, chunk);
    String rsaEncryptedAESKey = EncryptionHelper.encryptUsingRSA(
            Base64.getEncoder().encodeToString(secretKey.getEncoded()),
            FileUtils.readFileToString(publicKeyFile, "utf8"));

    String secretKeyContent = EncryptionHelper.decryptUsingRSA(rsaEncryptedAESKey,
            FileUtils.readFileToString(privateKeyFile, "utf8"));
    byte[] decryptedKey = Base64.getDecoder().decode(secretKeyContent);
    secretKey = new SecretKeySpec(decryptedKey, 0, decryptedKey.length, "AES");

    String decryptedData = EncryptionHelper.decryptUsingAES(secretKey, aesEncryptedData);

    assertThat(chunk, is(decryptedData));
}

From source file:eu.peppol.document.PayloadParserTest.java

/**
 * Takes a file holding an SBD/SBDH with an ASiC archive in base64 as payload and extracts the ASiC archive in binary format, while
 * calculating the message digest./* w w  w. j a va  2 s  . c o  m*/
 *
 * @throws Exception
 */
@Test
public void parseSampleSbdWithAsic() throws Exception {

    InputStream resourceAsStream = PayloadParserTest.class.getClassLoader()
            .getResourceAsStream("sample-sbd-with-asic.xml");
    assertNotNull(resourceAsStream);

    Path xmlFile = Files.createTempFile("unit-test", ".xml");

    XMLEventReader xmlEventReader = XMLInputFactory.newInstance().createXMLEventReader(resourceAsStream,
            "UTF-8");
    FileOutputStream outputStream = new FileOutputStream(xmlFile.toFile());
    XMLEventWriter xmlEventWriter = XMLOutputFactory.newInstance().createXMLEventWriter(outputStream, "UTF-8");

    Path asicFile = Files.createTempFile("unit-test", ".asice");
    OutputStream asicOutputStream = Files.newOutputStream(asicFile);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");

    DigestOutputStream digestOutputStream = new DigestOutputStream(asicOutputStream, messageDigest);
    Base64OutputStream base64OutputStream = new Base64OutputStream(digestOutputStream, false);

    boolean insideAsicElement = false;

    while (xmlEventReader.hasNext()) {
        XMLEvent xmlEvent = xmlEventReader.nextEvent();

        switch (xmlEvent.getEventType()) {
        case XMLEvent.START_ELEMENT:
            String localPart = xmlEvent.asStartElement().getName().getLocalPart();
            if ("asic".equals(localPart)) {
                insideAsicElement = true;
            }
            break;
        case XMLEvent.END_ELEMENT:
            localPart = xmlEvent.asEndElement().getName().getLocalPart();
            if ("asic".equals(localPart)) {
                insideAsicElement = false;
            }
            break;

        case XMLEvent.CHARACTERS:
            // Whenever we are inside the ASiC XML element, spit
            // out the base64 encoded data into the base64 decoding output stream.
            if (insideAsicElement) {
                Characters characters = xmlEvent.asCharacters();
                base64OutputStream.write(characters.getData().getBytes("UTF-8"));
            }
            break;
        }
        xmlEventWriter.add(xmlEvent);
    }

    asicOutputStream.close();
    outputStream.close();
    log.debug("Wrote xml output to: " + xmlFile);
    log.debug("Wrote ASiC to:" + asicFile);
    log.debug("Digest: " + new String(Base64.getEncoder().encode(messageDigest.digest())));
}