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:org.codice.ddf.security.common.jaxrs.RestSecurity.java

public static void setUserOnClient(String username, String password, Client client)
        throws UnsupportedEncodingException {
    if (client != null && username != null && password != null) {
        if (!StringUtils.startsWithIgnoreCase(client.getCurrentURI().getScheme(), "https")) {
            if (Boolean.valueOf(System.getProperty("org.codice.allowBasicAuthOverHttp", "false"))) {
                LOGGER.warn("CAUTION: Passing username & password on an un-encrypted protocol [{}]."
                        + " This is a security issue. ", client.getCurrentURI());
                SecurityLogger.auditWarn("Passing username & password on an un-encrypted protocol ["
                        + client.getCurrentURI() + "].");
            } else {
                LOGGER.warn("Passing username & password is not allowed on an un-encrypted protocol [{}].",
                        client.getCurrentURI());
                return;
            }/*  ww w  .j  a v a  2 s  .co m*/
        }
        String basicCredentials = username + ":" + password;
        String encodedHeader = BASIC_HEADER_PREFIX
                + Base64.getEncoder().encodeToString(basicCredentials.getBytes(StandardCharsets.UTF_8));
        client.header(AUTH_HEADER, encodedHeader);

    }
}

From source file:com.adeptj.runtime.server.CredentialMatcher.java

private static char[] makeHash(char[] password) {
    if (ArrayUtils.isEmpty(password)) {
        return null;
    }/*  w  w  w .j  a v a 2s .  c om*/
    try {
        byte[] digest = MessageDigest.getInstance(SHA256).digest(new String(password).getBytes(UTF_8));
        byte[] encoded = Base64.getEncoder().encode(digest);
        return (PREFIX + new String(encoded, UTF_8)).toCharArray();
    } catch (Exception ex) { // NOSONAR
        LOGGER.error(ex.getMessage(), ex);
    }
    return null;
}

From source file:ai.grakn.engine.tasks.manager.redisqueue.RedisTaskStorage.java

@Override
public TaskId newState(TaskState state) throws GraknBackendException {
    try (Jedis jedis = redis.getResource(); Context ignore = updateTimer.time()) {
        String key = encodeKey.apply(state.getId().getValue());
        LOG.debug("New state {}", key);
        String value = new String(Base64.getEncoder().encode(SerializationUtils.serialize(state)),
                Charsets.UTF_8);/*from   w w w  . ja  va2s .  c  o m*/
        String status = jedis.set(key, value, "nx", "ex", 60 * 60/*expire time in seconds*/);
        if (status != null && status.equalsIgnoreCase("OK")) {
            return state.getId();
        } else {
            writeError.mark();
            LOG.error("Could not write state {} to redis. Returned: {}", key, status);
            throw GraknBackendException.stateStorage();
        }
    }
}

From source file:za.co.bronkode.jwtbroker.Tokenizer.java

public static String EncodeToken(Token token) {
    try (StringWriter hwriter = new StringWriter(); StringWriter cwriter = new StringWriter();) {
        ObjectMapper hmapper = new ObjectMapper();

        hmapper.writeValue(hwriter, token.getHeader());
        String header = hwriter.toString();
        hmapper.writeValue(cwriter, token.getClaim(claimClass));
        String claim = cwriter.toString();
        hwriter.close();//from www  . j a v a 2s. co m
        cwriter.close();
        String h64 = Base64.getEncoder().encodeToString(header.getBytes());
        String c64 = Base64.getEncoder().encodeToString(claim.getBytes());
        String signature = GetSignature(h64, c64);
        StringBuilder sb = new StringBuilder(h64);
        sb.append(".");
        sb.append(c64);
        sb.append(".");
        sb.append(signature);
        return sb.toString();
    } catch (IOException ex) {
        Logger.getLogger(Tokenizer.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}

From source file:io.vertx.core.json.Json.java

@SuppressWarnings("unchecked")
static Object checkAndCopy(Object val, boolean copy) {
    if (val == null) {
        // OK//  w  w  w.  j  ava 2s. co  m
    } else if (val instanceof Number && !(val instanceof BigDecimal)) {
        // OK
    } else if (val instanceof Boolean) {
        // OK
    } else if (val instanceof String) {
        // OK
    } else if (val instanceof Character) {
        // OK
    } else if (val instanceof CharSequence) {
        val = val.toString();
    } else if (val instanceof JsonObject) {
        if (copy) {
            val = ((JsonObject) val).copy();
        }
    } else if (val instanceof JsonArray) {
        if (copy) {
            val = ((JsonArray) val).copy();
        }
    } else if (val instanceof Map) {
        if (copy) {
            val = (new JsonObject((Map) val)).copy();
        } else {
            val = new JsonObject((Map) val);
        }
    } else if (val instanceof List) {
        if (copy) {
            val = (new JsonArray((List) val)).copy();
        } else {
            val = new JsonArray((List) val);
        }
    } else if (val instanceof byte[]) {
        val = Base64.getEncoder().encodeToString((byte[]) val);
    } else {
        throw new IllegalStateException("Illegal type in JsonObject: " + val.getClass());
    }
    return val;
}

From source file:io.openvidu.test.e2e.utils.CustomHttpClient.java

public void testAuthorizationError() {
    try {/*from   ww w  . ja v  a  2s.c om*/
        String wrongCredentials = "Basic "
                + Base64.getEncoder().encodeToString(("OPENVIDUAPP:WRONG_SECRET").getBytes());
        Assert.assertEquals("Expected 401 status (unauthorized)", HttpStatus.SC_UNAUTHORIZED, Unirest
                .get(openviduUrl + "/config").header("Authorization", wrongCredentials).asJson().getStatus());
    } catch (UnirestException e) {
        Assert.fail("Error testing UNAUTHORIZED rest method: " + e.getMessage());
    }
}

From source file:org.vas.test.rest.RestImpl.java

private String digestCredentials(String username, String password) {
    String credential = username + ":" + password;
    String digest = Base64.getEncoder().encodeToString(credential.getBytes());
    return "Basic " + digest;
}

From source file:am.ik.categolj2.app.authentication.AuthenticationHelper.java

public HttpEntity<MultiValueMap<String, Object>> createRopRequest(String username, String password) {
    MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    params.add("username", username);
    params.add("password", password);
    params.add("grant_type", "password");
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    byte[] clientInfo = (adminClientProperties.getClientId() + ":" + adminClientProperties.getClientSecret())
            .getBytes(StandardCharsets.UTF_8);
    String basic = new String(Base64.getEncoder().encode(clientInfo), StandardCharsets.UTF_8);
    headers.set(com.google.common.net.HttpHeaders.AUTHORIZATION, "Basic " + basic);
    return new HttpEntity<>(params, headers);
}

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

public static String encryptUsingAES(SecretKey secretKey, String dataToEncrypt) throws NoSuchPaddingException,
        NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.ENCRYPT_MODE, secretKey);
    byte[] byteCipherText = aesCipher.doFinal(dataToEncrypt.getBytes());
    return Base64.getEncoder().encodeToString(byteCipherText);
}

From source file:org.apache.james.util.SerializationUtilTest.java

@Test
void deserializeShouldThrowWhenNotSerializedBytesAreEncodedInBase64() {
    assertThatExceptionOfType(SerializationException.class).isThrownBy(
            () -> deserialize(Base64.getEncoder().encodeToString("abc".getBytes(StandardCharsets.UTF_8))));
}