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.adobe.ags.curly.test.ConnectionManagerTest.java

@Test
public void getAuthenticatedConnection() throws IOException {
    webserver.requireLogin = true;/*  w  w w .  ja va  2 s .c  o  m*/
    AuthHandler handler = new AuthHandler(new ReadOnlyStringWrapper("localhost:" + webserver.port),
            new ReadOnlyBooleanWrapper(false), new ReadOnlyStringWrapper(TEST_USER),
            new ReadOnlyStringWrapper(TEST_PASSWORD));
    CloseableHttpClient client = handler.getAuthenticatedClient();
    assertNotNull(client);
    HttpUriRequest request = new HttpGet("http://localhost:" + webserver.port + "/testUri");
    client.execute(request);
    Header authHeader = webserver.lastRequest.getFirstHeader("Authorization");
    assertNotNull(authHeader);
    String compareToken = "Basic "
            + Base64.getEncoder().encodeToString((TEST_USER + ":" + TEST_PASSWORD).getBytes());
    assertEquals("Auth token should be expected format", authHeader.getValue(), compareToken);
}

From source file:fr.ffremont.mytasks.rest.UserResource.java

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response login(@FormParam("login") String login, @FormParam("password") String password)
        throws NotFoundEntity {
    fr.ffremont.mytasks.model.User user = userRepo.findOneByEmail(login);

    if (user == null) {
        LOG.warn("chec de l'authentification : " + login + ":" + password);
        throw new WebApplicationException(Status.UNAUTHORIZED);
    }/*  w w w  . j  a  v  a  2  s  .  c  om*/

    byte[] hash = DigestUtils.sha256(login + password);
    String myHash = new String(Base64.getEncoder().encode(hash));

    if (!myHash.equals(user.getHash())) {
        LOG.warn("chec de l'authentification : " + login + ":" + password);
        throw new WebApplicationException(Status.UNAUTHORIZED);
    }

    user.setLastConnexion(new Date());
    userRepo.save(user);

    return Response.ok().entity(user).build();
}

From source file:eu.peppol.document.AsicFilterInputStreamTest.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./*from  www.  j a v  a 2  s  . co  m*/
 *
 * @throws Exception
 */
@Test
public void parseSampleSbdWithAsic() throws Exception {
    InputStream resourceAsStream = AsicFilterInputStreamTest.class.getClassLoader()
            .getResourceAsStream("sample-sbd-with-asic.xml");

    AsicFilterInputStream asicFilterInputStream = new AsicFilterInputStream(resourceAsStream);

    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);

    IOUtils.copy(asicFilterInputStream, base64OutputStream);
    log.debug("Wrote ASiC to:" + asicFile);
    log.debug("Digest: " + new String(Base64.getEncoder().encode(messageDigest.digest())));

}

From source file:org.owasp.webgoat.plugin.DisplayUser.java

protected String genUserHash(String username, String password) throws Exception {
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    // salting is good, but static & too predictable ... short too for a salt
    String salted = password + "DeliberatelyInsecure1234" + username;
    //md.update(salted.getBytes("UTF-8")); // Change this to "UTF-16" if needed
    byte[] hash = md.digest(salted.getBytes("UTF-8"));
    String encoded = Base64.getEncoder().encodeToString(hash);
    return encoded;
}

From source file:com.vsct.dt.strowgr.admin.nsq.producer.NSQDispatcher.java

/**
 * Send a {@link CommitRequested} message to commit_requested_[haproxyName] NSQ topic.
 *
 * @param commitRequestedEvent in commit requested event
 * @param haproxyName          name of the targeted entrypoint
 * @param application          of the targeted entrypoint
 * @param platform             of the targeted entrypoint
 * @param bind//from  ww w . jav  a2s.c om
 * @throws JsonProcessingException      during a Json serialization with Jackson
 * @throws NSQException                 during any problem with NSQ
 * @throws TimeoutException             during a too long response from NSQ
 * @throws UnsupportedEncodingException during the conversion to UTF-8
 */
public void sendCommitRequested(CommitRequestedEvent commitRequestedEvent, String haproxyName,
        String application, String platform, String bind)
        throws JsonProcessingException, NSQException, TimeoutException, UnsupportedEncodingException {
    String confBase64 = new String(
            Base64.getEncoder().encode(commitRequestedEvent.getConf().getBytes("UTF-8")));
    String syslogConfBase64 = new String(
            Base64.getEncoder().encode(commitRequestedEvent.getSyslogConf().getBytes("UTF-8")));
    CommitRequested payload = new CommitRequested(commitRequestedEvent.getCorrelationId(), application,
            platform, confBase64, syslogConfBase64, commitRequestedEvent.getConfiguration().getHapVersion(),
            bind);

    try {
        nsqProducer.produce("commit_requested_" + haproxyName, mapper.writeValueAsBytes(payload));
    } catch (NSQException | TimeoutException | JsonProcessingException e) {
        LOGGER.error("can't produce NSQ message to commit_requested_" + haproxyName, e);
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.servlets.filters.FenixOAuthToken.java

public String format() {
    String token = Joiner.on(":").join(appUserSession.getExternalId(), nounce);
    return Base64.getEncoder().encodeToString(token.getBytes());
}

From source file:com.matel.service.impl.OrderServiceImpl.java

@Override
public Orders createNewOrder(ShoppingCartData cartData, String salesReceiptId) {
    Orders order = null;/*from   w ww  . j a v  a  2 s . c om*/
    if (null != cartData) {
        UserPayment uPayment = new UserPayment();
        order = new Orders();

        order = prepareNewOrder(cartData, order);
        order.setPaymentId(Integer.parseInt(salesReceiptId));

        if (cartData.getBillingInfo() != null) {
            UserAddress billingAddress = prepareBillingAddress(cartData.getBillingInfo(),
                    cartData.getCustomer());
            billingAddress = orderDAO.saveBillingAddress(billingAddress);
            order.setBillingAddressId(billingAddress);
        }
        if (cartData.getShippingInfo() != null) {
            UserAddress shippingAddress = prepareShippingAddress(cartData.getShippingInfo(),
                    cartData.getCustomer());
            shippingAddress = orderDAO.saveShippingAddress(shippingAddress);
            order.setShippingAddressId(shippingAddress);
        }
        if (cartData.getCardInfo() != null) {
            String cCard = cartData.getCardInfo().getCreditCard();
            byte[] cCardBytes = cCard.getBytes(StandardCharsets.UTF_8);
            uPayment.setCreditCardNumber(Base64.getEncoder().encodeToString(cCardBytes)); //Encode Credit Card

            /*
             * To Decode Credit Card use the following code snippet
             * 
                byte[] ccDecodeBytes = Base64.getDecoder().decode(uPayment.getCreditCardNumber()); 
               String cCardDecoded = new String(ccDecodeBytes, StandardCharsets.UTF_8);
            */
            uPayment.setCardType(cartData.getCardInfo().getCardType());
            uPayment.setNameOnTheCard(cartData.getCardInfo().getCardHolderName());
        }
        order.setComments(cartData.getShippingInfo().getInstructions());
        order.setShippingAmount(cartData.getShippingMethodData().getShippingCharges());
        order = orderDAO.saveOrder(order);
        uPayment.setOrderId(order);
        uPayment = orderDAO.saveUserPayment(uPayment);
        saveOrderProducts(order, cartData);
    }
    return order;
}

From source file:org.teavm.classlib.java.lang.ClassLoaderNativeGenerator.java

private void generateSupplyResources(InjectorContext context) throws IOException {
    SourceWriter writer = context.getWriter();
    writer.append("{").indent();

    ClassLoader classLoader = context.getClassLoader();
    Set<String> resourceSet = new HashSet<>();
    SupplierContextImpl supplierContext = new SupplierContextImpl(context);
    for (ResourceSupplier supplier : ServiceLoader.load(ResourceSupplier.class, classLoader)) {
        String[] resources = supplier.supplyResources(supplierContext);
        if (resources != null) {
            resourceSet.addAll(Arrays.asList(resources));
        }//ww  w  . ja v  a 2s.com
    }

    boolean first = true;
    for (String resource : resourceSet) {
        try (InputStream input = classLoader.getResourceAsStream(resource)) {
            if (input == null) {
                continue;
            }
            if (!first) {
                writer.append(',');
            }
            first = false;
            writer.newLine();
            String data = Base64.getEncoder().encodeToString(IOUtils.toByteArray(input));
            writer.append("\"").append(RenderingUtil.escapeString(resource)).append("\"");
            writer.ws().append(':').ws();
            writer.append("\"").append(data).append("\"");
        }
    }

    if (!first) {
        writer.newLine();
    }
    writer.outdent().append('}');
}

From source file:keywhiz.auth.cookie.AuthenticatedEncryptedCookieFactory.java

/**
 * Produces an authenticating token.//from   w  w  w  . j a v  a 2 s. co  m
 *
 * @param user identity the token will authenticate.
 * @param expiration timestamp when token should expire.
 * @return token which can be used to authenticate as user until expiration.
 */
public String getSession(User user, ZonedDateTime expiration) {
    try {
        String cookieJson = mapper.writeValueAsString(new UserCookieData(user, expiration));
        byte[] cookieBody = encryptor.encrypt(cookieJson.getBytes(UTF_8));
        return Base64.getEncoder().encodeToString(cookieBody);
    } catch (AEADBadTagException e) {
        logger.error("Could not encrypt cookie", e);
        throw Throwables.propagate(e);
    } catch (JsonProcessingException e) {
        throw Throwables.propagate(e);
    }
}

From source file:top.lionxxw.zuulservice.filter.BookingCarPreFilter.java

private String encode(String origin) {
    byte[] encodedBytes = Base64.getEncoder().encode(origin.getBytes());
    return new String(encodedBytes);
}