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.fenixedu.bennu.oauth.OAuthServletTest.java

private String generateToken(DomainObject domainObject) {
    String random = "fenix";
    String token = Joiner.on(":").join(domainObject.getExternalId(), random);
    return Base64.getEncoder().encodeToString(token.getBytes(StandardCharsets.UTF_8)).replace("=", "")
            .replace("+", "-").replace("/", "-");
}

From source file:com.github.cambierr.lorawanpacket.semtech.Rxpk.java

public JSONObject toJson() throws MalformedPacketException {
    JSONObject output = new JSONObject();

    output.put("time", time);
    output.put("tmst", tmst);
    output.put("freq", freq);
    output.put("chan", chan);
    output.put("rfch", rfch);
    output.put("stat", stat);
    output.put("modu", modu.name());

    if (modu.equals(Modulation.LORA)) {
        output.put("codr", codr);
        output.put("lsnr", lsnr);
    }// w ww .  j a  v a 2s  .  c  o m

    output.put("datr", datr);
    output.put("rssi", rssi);
    output.put("size", size);

    ByteBuffer bb = ByteBuffer.allocate(384);
    data.toRaw(bb);
    output.put("data", Base64.getEncoder()
            .encodeToString(Arrays.copyOfRange(bb.array(), 0, bb.capacity() - bb.remaining())));

    return output;
}

From source file:com.github.cambierr.lorawanpacket.semtech.Txpk.java

public JSONObject toJson() throws MalformedPacketException {
    JSONObject output = new JSONObject();

    output.put("imme", isImme());
    output.put("tmst", getTmst());
    output.put("time", getTime());
    output.put("freq", getFreq());
    output.put("rfch", getRfch());
    output.put("powe", getPowe());
    output.put("modu", getModu().name());

    if (getModu().equals(Modulation.LORA)) {
        output.put("codr", getCodr());
        output.put("ipol", isIpol());
    } else {/*ww  w  .  j  av  a 2 s  .c  o m*/
        output.put("fdev", getFdev());
    }

    output.put("datr", getDatr());
    output.put("prea", getPrea());
    output.put("size", getSize());
    output.put("ncrc", isNcrc());

    ByteBuffer bb = ByteBuffer.allocate(384);
    getData().toRaw(bb);
    output.put("data", Base64.getEncoder()
            .encodeToString(Arrays.copyOfRange(bb.array(), 0, bb.capacity() - bb.remaining())));

    return output;
}

From source file:org.apache.syncope.core.provisioning.java.job.report.ReconciliationReportlet.java

private Set<Object> getValues(final Attribute attr) {
    Set<Object> values;
    if (attr.getValue() == null || attr.getValue().isEmpty()) {
        values = Collections.emptySet();
    } else if (attr.getValue().get(0) instanceof byte[]) {
        values = new HashSet<>(attr.getValue().size());
        attr.getValue().forEach(single -> {
            values.add(Base64.getEncoder().encode((byte[]) single));
        });//from   w w w.  j a va2  s. c  o m
    } else {
        values = new HashSet<>(attr.getValue());
    }

    return values;
}

From source file:com.orange.clara.cloud.servicedbdumper.controllers.ManagerControllerTest.java

@Test
public void when_user_wants_to_download_dump_file_with_original_file_and_user_password_are_correct_it_should_download_the_content()
        throws Exception {

    //format to basic auth header
    String login = userShowable + ":" + passwordShowable;
    String loginEncoded = Base64.getEncoder().encodeToString(login.getBytes());

    mockMvc.perform(/*from  w  ww .j  av  a  2 s  . c o m*/
            get(Routes.MANAGE_ROOT + Routes.DOWNLOAD_DUMP_FILE_ROOT + "/" + databaseDumpFileShowable.getId()
                    + "?original=1").header("Authorization", "Basic " + loginEncoded))
            .andExpect(status().isOk()).andExpect(content().string(textForFiler));
}

From source file:co.runrightfast.vertx.demo.testHarness.jmx.DemoMXBeanImpl.java

@Override
public String encrypt(@NonNull final String data) {
    return Base64.getEncoder().encodeToString(encryption.apply(data.getBytes(UTF_8)));
}

From source file:ai.susi.server.api.aaa.PublicKeyRegistrationService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization,
        final JsonObjectWithDefault permissions) throws APIException {

    if (post.get("register", null) == null && !post.get("create", false) && !post.get("getParameters", false)) {
        throw new APIException(400, "Accepted parameters: 'register', 'create' or 'getParameters'");
    }/*  w w w  .  ja  va2 s .co  m*/

    JSONObject result = new JSONObject();

    // return algorithm parameters and users for whom we are allowed to register a key
    if (post.get("getParameters", false)) {
        result.put("self", permissions.getBoolean("self", false));
        result.put("users", permissions.getJSONObject("users"));
        result.put("userRoles", permissions.getJSONObject("userRoles"));

        JSONObject algorithms = new JSONObject();

        JSONObject rsa = new JSONObject();
        JSONArray keySizes = new JSONArray();
        for (int i : allowedKeySizesRSA) {
            keySizes.put(i);
        }
        rsa.put("sizes", keySizes);
        rsa.put("defaultSize", defaultKeySizeRSA);
        algorithms.put("RSA", rsa);
        result.put("algorithms", algorithms);

        JSONArray formats = new JSONArray();
        for (String format : allowedFormats) {
            formats.put(format);
        }
        result.put("formats", formats);

        return result;
    }

    // for which id?
    String id;
    if (post.get("id", null) != null)
        id = post.get("id", null);
    else
        id = authorization.getIdentity().getName();

    // check if we are allowed register a key
    if (!id.equals(authorization.getIdentity().getName())) { // if we don't want to register the key for the current user

        // create Authentication to check if the user id is a registered user
        ClientCredential credential = new ClientCredential(ClientCredential.Type.passwd_login, id);
        Authentication authentication = new Authentication(credential, DAO.authentication);

        if (authentication.getIdentity() == null) { // check if identity is valid
            authentication.delete();
            throw new APIException(400, "Bad request"); // do not leak if user exists or not
        }

        // check if the current user is allowed to create a key for the user in question
        boolean allowed = false;
        // check if the user in question is in 'users'
        if (permissions.getJSONObject("users", null).has(id)
                && permissions.getJSONObjectWithDefault("users", null).getBoolean(id, false)) {
            allowed = true;
        } else { // check if the user role of the user in question is in 'userRoles'
            Authorization auth = new Authorization(authentication.getIdentity(), DAO.authorization,
                    DAO.userRoles);
            for (String key : permissions.getJSONObject("userRoles").keySet()) {
                if (key.equals(auth.getUserRole().getName())
                        && permissions.getJSONObject("userRoles").getBoolean(key)) {
                    allowed = true;
                }
            }
        }
        if (!allowed)
            throw new APIException(400, "Bad request"); // do not leak if user exists or not
    } else { // if we want to register a key for this user, bad are not allowed to (for example anonymous users)
        if (!permissions.getBoolean("self", false))
            throw new APIException(403, "You are not allowed to register a public key");
    }

    // set algorithm. later, we maybe want to support other algorithms as well
    String algorithm = "RSA";
    if (post.get("algorithm", null) != null) {
        algorithm = post.get("algorithm", null);
    }

    if (post.get("create", false)) { // create a new key pair on the server

        if (algorithm.equals("RSA")) {
            int keySize = 2048;
            if (post.get("key-size", null) != null) {
                int finalKeyLength = post.get("key-size", 0);
                if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == finalKeyLength)) {
                    throw new APIException(400, "Invalid key size.");
                }
                keySize = finalKeyLength;
            }

            KeyPairGenerator keyGen;
            KeyPair keyPair;
            try {
                keyGen = KeyPairGenerator.getInstance(algorithm);
                keyGen.initialize(keySize);
                keyPair = keyGen.genKeyPair();
            } catch (NoSuchAlgorithmException e) {
                throw new APIException(500, "Server error");
            }

            registerKey(authorization.getIdentity(), keyPair.getPublic());

            String pubkey_pem = null, privkey_pem = null;
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PUBLIC KEY", keyPair.getPublic().getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                pubkey_pem = writer.toString();
            } catch (IOException e) {
            }
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PRIVATE KEY", keyPair.getPrivate().getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                privkey_pem = writer.toString();
            } catch (IOException e) {
            }

            result.put("publickey_DER_BASE64",
                    Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()));
            result.put("privatekey_DER_BASE64",
                    Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()));
            result.put("publickey_PEM", pubkey_pem);
            result.put("privatekey_PEM", privkey_pem);
            result.put("keyhash", IO.getKeyHash(keyPair.getPublic()));
            try {
                result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(keyPair.getPublic()), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
            }
            result.put("key-size", keySize);
            result.put("message",
                    "Successfully created and registered key. Make sure to copy the private key, it won't be saved on the server");

            return result;
        }
        throw new APIException(400, "Unsupported algorithm");
    } else if (post.get("register", null) != null) {

        if (algorithm.equals("RSA")) {
            String type = post.get("type", null);
            if (type == null)
                type = "DER";

            RSAPublicKey pub;
            String encodedKey;
            try {
                encodedKey = URLDecoder.decode(post.get("register", null), "UTF-8");
            } catch (Throwable e) {
                throw new APIException(500, "Server error");
            }
            Log.getLog().info("Key (" + type + "): " + encodedKey);

            if (type.equals("DER")) {
                try {
                    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(encodedKey));
                    pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec);
                } catch (Throwable e) {
                    throw new APIException(400, "Public key not readable (DER)");
                }
            } else if (type.equals("PEM")) {
                try {
                    PemReader pemReader = new PemReader(new StringReader(encodedKey));
                    PemObject pem = pemReader.readPemObject();
                    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pem.getContent());
                    pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec);
                } catch (Exception e) {
                    throw new APIException(400, "Public key not readable (PEM)");
                }
            } else {
                throw new APIException(400, "Invalid value for 'type'.");
            }

            // check key size (not really perfect yet)
            int keySize;
            int bitLength = pub.getModulus().bitLength();
            if (bitLength <= 512) {
                keySize = 512;
            } else if (bitLength <= 1024) {
                keySize = 1024;
            } else if (bitLength <= 2048) {
                keySize = 2048;
            } else if (bitLength <= 4096) {
                keySize = 4096;
            } else {
                keySize = 8192;
            }
            if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == keySize)) {
                throw new APIException(400, "Invalid key length.");
            }

            registerKey(authorization.getIdentity(), pub);

            String pubkey_pem = null;
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PUBLIC KEY", pub.getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                pubkey_pem = writer.toString();
            } catch (IOException e) {
            }

            result.put("publickey_DER_BASE64", Base64.getEncoder().encodeToString(pub.getEncoded()));
            result.put("publickey_PEM", pubkey_pem);
            result.put("keyhash", IO.getKeyHash(pub));
            try {
                result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(pub), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
            }
            result.put("message", "Successfully registered key.");

            return result;
        }
        throw new APIException(400, "Unsupported algorithm");
    }

    throw new APIException(400, "Invalid parameter");
}

From source file:org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.java

/**
 * Inverse operation of decodeCookie./*from  ww  w  . ja  v a2 s  .com*/
 *
 * @param cookieTokens the tokens to be encoded.
 * @return base64 encoding of the tokens concatenated with the ":" delimiter.
 */
protected String encodeCookie(String[] cookieTokens) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < cookieTokens.length; i++) {
        try {
            sb.append(URLEncoder.encode(cookieTokens[i], StandardCharsets.UTF_8.toString()));
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }

        if (i < cookieTokens.length - 1) {
            sb.append(DELIMITER);
        }
    }

    String value = sb.toString();

    sb = new StringBuilder(new String(Base64.getEncoder().encode(value.getBytes())));

    while (sb.charAt(sb.length() - 1) == '=') {
        sb.deleteCharAt(sb.length() - 1);
    }

    return sb.toString();
}

From source file:org.loklak.api.aaa.PublicKeyRegistrationService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization,
        final JSONObjectWithDefault permissions) throws APIException {

    if (post.get("register", null) == null && !post.get("create", false) && !post.get("getParameters", false)) {
        throw new APIException(400, "Accepted parameters: 'register', 'create' or 'getParameters'");
    }//from   w  w  w.  ja  v a2  s  .c om

    JSONObject result = new JSONObject();

    // return algorithm parameters and users for whom we are allowed to register a key
    if (post.get("getParameters", false)) {
        result.put("self", permissions.getBoolean("self", false));
        result.put("users", permissions.getJSONObject("users"));
        result.put("userRoles", permissions.getJSONObject("userRoles"));

        JSONObject algorithms = new JSONObject();

        JSONObject rsa = new JSONObject();
        JSONArray keySizes = new JSONArray();
        for (int i : allowedKeySizesRSA) {
            keySizes.put(i);
        }
        rsa.put("sizes", keySizes);
        rsa.put("defaultSize", defaultKeySizeRSA);
        algorithms.put("RSA", rsa);
        result.put("algorithms", algorithms);

        JSONArray formats = new JSONArray();
        for (String format : allowedFormats) {
            formats.put(format);
        }
        result.put("formats", formats);

        return result;
    }

    // for which id?
    String id;
    if (post.get("id", null) != null)
        id = post.get("id", null);
    else
        id = authorization.getIdentity().getName();

    // check if we are allowed register a key
    if (!id.equals(authorization.getIdentity().getName())) { // if we don't want to register the key for the current user

        // create Authentication to check if the user id is a registered user
        ClientCredential credential = new ClientCredential(ClientCredential.Type.passwd_login, id);
        Authentication authentication = new Authentication(credential, DAO.authentication);

        if (authentication.getIdentity() == null) { // check if identity is valid
            authentication.delete();
            throw new APIException(400, "Bad request"); // do not leak if user exists or not
        }

        // check if the current user is allowed to create a key for the user in question
        boolean allowed = false;
        // check if the user in question is in 'users'
        if (permissions.getJSONObject("users", null).has(id)
                && permissions.getJSONObjectWithDefault("users", null).getBoolean(id, false)) {
            allowed = true;
        } else { // check if the user role of the user in question is in 'userRoles'
            Authorization auth = new Authorization(authentication.getIdentity(), DAO.authorization,
                    DAO.userRoles);
            for (String key : permissions.getJSONObject("userRoles").keySet()) {
                if (key.equals(auth.getUserRole().getName())
                        && permissions.getJSONObject("userRoles").getBoolean(key)) {
                    allowed = true;
                }
            }
        }
        if (!allowed)
            throw new APIException(400, "Bad request"); // do not leak if user exists or not
    } else { // if we want to register a key for this user, bad are not allowed to (for example anonymous users)
        if (!permissions.getBoolean("self", false))
            throw new APIException(403, "You are not allowed to register a public key");
    }

    // set algorithm. later, we maybe want to support other algorithms as well
    String algorithm = "RSA";
    if (post.get("algorithm", null) != null) {
        algorithm = post.get("algorithm", null);
    }

    if (post.get("create", false)) { // create a new key pair on the server

        if (algorithm.equals("RSA")) {
            int keySize = 2048;
            if (post.get("key-size", null) != null) {
                int finalKeyLength = post.get("key-size", 0);
                if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == finalKeyLength)) {
                    throw new APIException(400, "Invalid key size.");
                }
                keySize = finalKeyLength;
            }

            KeyPairGenerator keyGen;
            KeyPair keyPair;
            try {
                keyGen = KeyPairGenerator.getInstance(algorithm);
                keyGen.initialize(keySize);
                keyPair = keyGen.genKeyPair();
            } catch (NoSuchAlgorithmException e) {
                throw new APIException(500, "Server error");
            }

            registerKey(authorization.getIdentity(), keyPair.getPublic());

            String pubkey_pem = null, privkey_pem = null;
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PUBLIC KEY", keyPair.getPublic().getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                pubkey_pem = writer.toString();
            } catch (IOException e) {
            }
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PRIVATE KEY", keyPair.getPrivate().getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                privkey_pem = writer.toString();
            } catch (IOException e) {
            }

            result.put("publickey_DER_BASE64",
                    Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()));
            result.put("privatekey_DER_BASE64",
                    Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()));
            result.put("publickey_PEM", pubkey_pem);
            result.put("privatekey_PEM", privkey_pem);
            result.put("keyhash", IO.getKeyHash(keyPair.getPublic()));
            try {
                result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(keyPair.getPublic()), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
            }
            result.put("key-size", keySize);
            result.put("message",
                    "Successfully created and registered key. Make sure to copy the private key, it won't be saved on the server");

            return result;
        }
        throw new APIException(400, "Unsupported algorithm");
    } else if (post.get("register", null) != null) {

        if (algorithm.equals("RSA")) {
            String type = post.get("type", null);
            if (type == null)
                type = "DER";

            RSAPublicKey pub;
            String encodedKey;
            try {
                encodedKey = URLDecoder.decode(post.get("register", null), "UTF-8");
            } catch (Throwable e) {
                throw new APIException(500, "Server error");
            }
            Log.getLog().info("Key (" + type + "): " + encodedKey);

            if (type.equals("DER")) {
                try {
                    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(encodedKey));
                    pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec);
                } catch (Throwable e) {
                    throw new APIException(400, "Public key not readable (DER)");
                }
            } else if (type.equals("PEM")) {
                try {
                    PemReader pemReader = new PemReader(new StringReader(encodedKey));
                    PemObject pem = pemReader.readPemObject();
                    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pem.getContent());
                    pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec);
                } catch (Exception e) {
                    throw new APIException(400, "Public key not readable (PEM)");
                }
            } else {
                throw new APIException(400, "Invalid value for 'type'.");
            }

            // check key size (not really perfect yet)
            int keySize;
            int bitLength = pub.getModulus().bitLength();
            if (bitLength <= 512) {
                keySize = 512;
            } else if (bitLength <= 1024) {
                keySize = 1024;
            } else if (bitLength <= 2048) {
                keySize = 2048;
            } else if (bitLength <= 4096) {
                keySize = 4096;
            } else {
                keySize = 8192;
            }
            if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == keySize)) {
                throw new APIException(400, "Invalid key length.");
            }

            registerKey(authorization.getIdentity(), pub);

            String pubkey_pem = null;
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PUBLIC KEY", pub.getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                pubkey_pem = writer.toString();
            } catch (IOException e) {
            }

            result.put("publickey_DER_BASE64", Base64.getEncoder().encodeToString(pub.getEncoded()));
            result.put("publickey_PEM", pubkey_pem);
            result.put("keyhash", IO.getKeyHash(pub));
            try {
                result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(pub), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
            }
            result.put("message", "Successfully registered key.");

            return result;
        }
        throw new APIException(400, "Unsupported algorithm");
    }

    throw new APIException(400, "Invalid parameter");
}

From source file:com.exalttech.trex.ui.controllers.daemon.TRexDaemonDialogController.java

private void startTRex() {
    Boolean configUploaded = false;
    try {//from   w  w  w  .  j  a  va2 s .c om
        configUploaded = client.createRequest().id(getId()).method("push_file")
                .param("filename", configFilename)
                .param("bin_data",
                        Base64.getEncoder()
                                .encodeToString(userConfigModel.getYAMLString().getBytes(Charsets.US_ASCII)))
                .returnAs(Boolean.class).execute();

        if (!configUploaded) {
            log(LogType.ERROR, "Config upload to TRex host failed (TRex Daemon IO error)");
        }

        log(LogType.INFO, "Config uploaded successfully");
    } catch (RuntimeException ex) {
        log(LogType.ERROR, MessageFormat.format("Config upload to TRex host failed: {0}", ex));
    } catch (JsonProcessingException ex) {
        log(LogType.ERROR, MessageFormat.format("Config serialization failed: {0}", ex));
    }

    Map<String, Object> cmdParams = new HashMap<>();

    if (configUploaded) {
        try {
            String files_path = client.createRequest().id(getId()).method("get_files_path")
                    .returnAs(String.class).execute();

            cmdParams.put("cfg", Paths.get(files_path, configFilename));
        } catch (RuntimeException ex) {
            log(LogType.ERROR, MessageFormat.format("Unable to get user configs path: {0}", ex));
        }
    }

    try {
        Integer trexSessionHandler = client.createRequest().id(getId()).method("start_trex")
                .param("trex_cmd_options", cmdParams).param("user", System.getProperty("user.name"))
                .param("stateless", true).returnAs(Integer.class).param("timeout", 15).execute();
        log(LogType.INFO, "TRex started successfully");
    } catch (RuntimeException ex) {
        log(LogType.ERROR, MessageFormat.format("Unable to start TRex: {0} ", ex));
    }
}