Example usage for java.util Base64 getDecoder

List of usage examples for java.util Base64 getDecoder

Introduction

In this page you can find the example usage for java.util Base64 getDecoder.

Prototype

public static Decoder getDecoder() 

Source Link

Document

Returns a Decoder that decodes using the Basic type base64 encoding scheme.

Usage

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

private String decodedScopedStreamName(String encodedScopedStreamName) {
    return new String(Base64.getDecoder().decode(encodedScopedStreamName));
}

From source file:org.kontalk.crypto.Coder.java

/**
 * Decrypt and verify the body of a message. Sets the encryption and signing
 * status of the message and errors that may occur are saved to the message.
 * @param message/*from w w  w .jav a 2  s .  c  om*/
 */
public static void processInMessage(InMessage message) {
    // signing requires also encryption
    if (!message.getCoderStatus().isEncrypted()) {
        LOGGER.warning("message not encrypted");
        return;
    }
    LOGGER.info("decrypting encrypted message...");

    // get keys
    KeysResult keys = getKeys(message.getUser());
    if (keys.myKey == null || keys.otherKey == null) {
        message.setSecurityErrors(keys.errors);
        return;
    }

    // decrypt
    String encryptedContent = message.getContent().getEncryptedContent();
    if (encryptedContent.isEmpty()) {
        LOGGER.warning("no encrypted data in encrypted message");
    }
    byte[] encryptedData = Base64.getDecoder().decode(encryptedContent);
    InputStream encryptedStream = new ByteArrayInputStream(encryptedData);
    DecryptionResult decResult = decryptAndVerify(encryptedStream, keys.myKey, keys.otherKey.encryptKey);
    EnumSet<Coder.Error> allErrors = decResult.errors;
    message.setSigning(decResult.signing);

    // parse
    ParsingResult parsingResult = null;
    if (decResult.decryptedStream.isPresent()) {
        // parse encrypted CPIM content
        String myUID = keys.myKey.getUserId();
        String senderUID = keys.otherKey.userID;
        String encrText = EncodingUtils.getString(decResult.decryptedStream.get().toByteArray(),
                CPIMMessage.CHARSET);
        parsingResult = parseCPIM(encrText, myUID, senderUID);
        allErrors.addAll(parsingResult.errors);
    }

    // set errors
    message.setSecurityErrors(allErrors);

    if (parsingResult != null && parsingResult.content != null) {
        // everything went better than expected
        LOGGER.info("decryption successful");
        message.setDecryptedContent(parsingResult.content);
    } else {
        LOGGER.warning("decryption failed");
    }
}

From source file:org.loklak.api.cms.LoginService.java

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

    // login check for app
    if (post.get("checkLogin", false)) {
        JSONObject result = new JSONObject();
        if (authorization.getIdentity().isEmail()) {
            result.put("loggedIn", true);
            result.put("message", "You are logged in as " + authorization.getIdentity().getName());
        } else {/*from   www. j av  a2s  . co  m*/
            result.put("loggedIn", false);
            result.put("message", "Not logged in");
        }
        return result;
    }

    // do logout if requested
    if (post.get("logout", false)) { // logout if requested

        // invalidate session
        post.getRequest().getSession().invalidate();

        // delete cookie if set
        deleteLoginCookie(response);

        JSONObject result = new JSONObject();
        result.put("message", "Logout successful");
        return result;
    }

    // check login type by checking which parameters are set
    boolean passwordLogin = false;
    boolean pubkeyHello = false;
    boolean pubkeyLogin = false;

    if (post.get("login", null) != null && post.get("password", null) != null
            && post.get("type", null) != null) {
        passwordLogin = true;
    } else if (post.get("login", null) != null && post.get("keyhash", null) != null) {
        pubkeyHello = true;
    } else if (post.get("sessionID", null) != null && post.get("response", null) != null) {
        pubkeyLogin = true;
    } else {
        throw new APIException(400, "Bad login parameters.");
    }

    // check if user is blocked because of too many invalid login attempts
    checkInvalidLogins(post, authorization, permissions);

    if (passwordLogin) { // do login via password

        String login = post.get("login", null);
        String password = post.get("password", null);
        String type = post.get("type", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.passwd_login, login));
        ClientIdentity identity = authentication.getIdentity();

        // check if the password is valid
        String passwordHash;
        String salt;
        try {
            passwordHash = authentication.getString("passwordHash");
            salt = authentication.getString("salt");
        } catch (Throwable e) {
            Log.getLog().info("Invalid login try for user: " + identity.getName() + " from host: "
                    + post.getClientHost() + " : password or salt missing in database");
            throw new APIException(422, "Invalid credentials");
        }

        if (!passwordHash.equals(getHash(password, salt))) {

            // save invalid login in accounting object
            authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login");

            Log.getLog().info("Invalid login try for user: " + identity.getName() + " via passwd from host: "
                    + post.getClientHost());
            throw new APIException(422, "Invalid credentials");
        }

        JSONObject result = new JSONObject();

        switch (type) {
        case "session": // create a browser session
            post.getRequest().getSession().setAttribute("identity", identity);
            break;
        case "cookie": // set a long living cookie
            // create random string as token
            String loginToken = createRandomString(30);

            // create cookie
            Cookie loginCookie = new Cookie("login", loginToken);
            loginCookie.setPath("/");
            loginCookie.setMaxAge(defaultCookieTime.intValue());

            // write cookie to database
            ClientCredential cookieCredential = new ClientCredential(ClientCredential.Type.cookie, loginToken);
            JSONObject user_obj = new JSONObject();
            user_obj.put("id", identity.toString());
            user_obj.put("expires_on", Instant.now().getEpochSecond() + defaultCookieTime);
            DAO.authentication.put(cookieCredential.toString(), user_obj, cookieCredential.isPersistent());

            response.addCookie(loginCookie);
            break;
        case "access-token": // create and display an access token

            long valid_seconds;
            try {
                valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime);
            } catch (Throwable e) {
                throw new APIException(400, "Invalid value for 'valid_seconds'");
            }

            String token = createAccessToken(identity, valid_seconds);

            if (valid_seconds == -1)
                result.put("valid_seconds", "forever");
            else
                result.put("valid_seconds", valid_seconds);

            result.put("access_token", token);

            break;
        default:
            throw new APIException(400, "Invalid type");
        }

        Log.getLog().info(
                "login for user: " + identity.getName() + " via passwd from host: " + post.getClientHost());

        result.put("message", "You are logged in as " + identity.getName());
        return result;
    } else if (pubkeyHello) { // first part of pubkey login: if the key hash is known, create a challenge

        String login = post.get("login", null);
        String keyHash = post.get("keyhash", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.passwd_login, login));
        ClientIdentity identity = authentication.getIdentity();

        if (!DAO.login_keys.has(identity.toString())
                || !DAO.login_keys.getJSONObject(identity.toString()).has(keyHash))
            throw new APIException(400, "Unknown key");

        String challengeString = createRandomString(30);
        String newSessionID = createRandomString(30);

        ClientCredential credential = new ClientCredential(ClientCredential.Type.pubkey_challange,
                newSessionID);
        Authentication challenge_auth = new Authentication(credential, DAO.authentication);
        challenge_auth.setIdentity(identity);
        challenge_auth.put("activated", true);

        challenge_auth.put("challenge", challengeString);
        challenge_auth.put("key", DAO.login_keys.getJSONObject(identity.toString()).getString(keyHash));
        challenge_auth.setExpireTime(60 * 10);

        JSONObject result = new JSONObject();
        result.put("challenge", challengeString);
        result.put("sessionID", newSessionID);
        result.put("message",
                "Found valid key for this user. Sign the challenge with you public key and send it back, together with the sessionID");
        return result;
    } else if (pubkeyLogin) { // second part of pubkey login: verify if the response to the challange is valid

        String sessionID = post.get("sessionID", null);
        String challangeResponse = post.get("response", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.pubkey_challange, sessionID));
        ClientIdentity identity = authentication.getIdentity();

        String challenge = authentication.getString("challenge");
        PublicKey key = IO.decodePublicKey(authentication.getString("key"), "RSA");

        Signature sig;
        boolean verified;
        try {
            sig = Signature.getInstance("SHA256withRSA");
            sig.initVerify(key);
            sig.update(challenge.getBytes());
            verified = sig.verify(Base64.getDecoder().decode(challangeResponse));
        } catch (NoSuchAlgorithmException e) {
            throw new APIException(400, "No such algorithm");
        } catch (InvalidKeyException e) {
            throw new APIException(400, "Invalid key");
        } catch (Throwable e) {
            throw new APIException(400, "Bad signature");
        }

        if (verified) {
            long valid_seconds;
            try {
                valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime);
            } catch (Throwable e) {
                throw new APIException(400, "Invalid value for 'valid_seconds'");
            }

            String token = createAccessToken(identity, valid_seconds);

            JSONObject result = new JSONObject();

            if (valid_seconds == -1)
                result.put("valid_seconds", "forever");
            else
                result.put("valid_seconds", valid_seconds);

            result.put("access_token", token);
            return result;
        } else {
            authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login");
            throw new APIException(400, "Bad Signature");
        }
    }
    throw new APIException(500, "Server error");
}

From source file:com.floreantpos.license.FiveStarPOSLicenseManager.java

private boolean verify(byte[] message, String signature, PublicKey publicKey) throws LicenseException {
    try {/*from  w ww.j  a va2s  . com*/

        Signature dsa = Signature.getInstance("SHA/DSA");
        dsa.initVerify(publicKey);
        dsa.update(message);

        byte[] decoded = Base64.getDecoder().decode(signature);
        return dsa.verify(decoded);

    } catch (Exception e) {
        throw new LicenseException("Invalid license key! Please contact our support.", e);
    }
}

From source file:org.pentaho.di.base.AbstractBaseCommandExecutor.java

/**
 * Decodes the provided base64String into the specified filePath. Parent directories must already exist.
 *
 * @param base64Zip BASE64 representation of a file
 * @param filePath String The path to which the base64String is to be decoded
 * @return File the newly created File//from  w  w  w . j a v a2 s .c o m
 */
public File decodeBase64ToZipFile(Serializable base64Zip, String filePath) throws IOException {

    if (base64Zip == null || Utils.isEmpty(base64Zip.toString())) {
        return null;
    }

    //Decode base64String to byte[]
    byte[] decodedBytes = Base64.getDecoder().decode(base64Zip.toString());
    File file = new File(filePath);

    //Try-with-resources, write to file, ensure fos is always closed
    try (FileOutputStream fos = new FileOutputStream(file)) {
        fos.write(decodedBytes);
    } catch (IOException e) {
        throw e;
    }

    return file;
}

From source file:org.wso2.carbon.siddhi.editor.core.internal.ServiceComponent.java

@GET
@Path("/workspace/list")
@Produces("application/json")
public Response directoriesInPath(@QueryParam("path") String path) {
    try {/*  www.j  a v  a 2s. c o  m*/
        return Response.status(Response.Status.OK)
                .entity(workspace.listDirectoriesInPath(new String(Base64.getDecoder().decode(path))))
                .type(MediaType.APPLICATION_JSON).build();
    } catch (IOException e) {
        return Response.serverError().entity("failed." + e.getMessage()).build();
    } catch (Throwable ignored) {
        return Response.serverError().entity("failed").build();
    }
}

From source file:org.elasticsearch.bwc.QueryBuilderBWCIT.java

public void testQueryBuilderBWC() throws Exception {
    String index = "queries";
    if (runningAgainstOldCluster) {
        XContentBuilder mappingsAndSettings = jsonBuilder();
        mappingsAndSettings.startObject();
        {/*from   w  w w  . ja va2s  . co m*/
            mappingsAndSettings.startObject("settings");
            mappingsAndSettings.field("number_of_shards", 1);
            mappingsAndSettings.field("number_of_replicas", 0);
            mappingsAndSettings.endObject();
        }
        {
            mappingsAndSettings.startObject("mappings");
            mappingsAndSettings.startObject("doc");
            mappingsAndSettings.startObject("properties");
            {
                mappingsAndSettings.startObject("query");
                mappingsAndSettings.field("type", "percolator");
                mappingsAndSettings.endObject();
            }
            {
                mappingsAndSettings.startObject("keyword_field");
                mappingsAndSettings.field("type", "keyword");
                mappingsAndSettings.endObject();
            }
            {
                mappingsAndSettings.startObject("long_field");
                mappingsAndSettings.field("type", "long");
                mappingsAndSettings.endObject();
            }
            mappingsAndSettings.endObject();
            mappingsAndSettings.endObject();
            mappingsAndSettings.endObject();
        }
        mappingsAndSettings.endObject();
        Request request = new Request("PUT", "/" + index);
        request.setJsonEntity(Strings.toString(mappingsAndSettings));
        Response rsp = client().performRequest(request);
        assertEquals(200, rsp.getStatusLine().getStatusCode());

        for (int i = 0; i < CANDIDATES.size(); i++) {
            request = new Request("PUT", "/" + index + "/doc/" + Integer.toString(i));
            request.setJsonEntity((String) CANDIDATES.get(i)[0]);
            rsp = client().performRequest(request);
            assertEquals(201, rsp.getStatusLine().getStatusCode());
        }
    } else {
        NamedWriteableRegistry registry = new NamedWriteableRegistry(
                new SearchModule(Settings.EMPTY, false, Collections.emptyList()).getNamedWriteables());

        for (int i = 0; i < CANDIDATES.size(); i++) {
            QueryBuilder expectedQueryBuilder = (QueryBuilder) CANDIDATES.get(i)[1];
            Request request = new Request("GET", "/" + index + "/_search");
            request.setJsonEntity("{\"query\": {\"ids\": {\"values\": [\"" + Integer.toString(i) + "\"]}}, "
                    + "\"docvalue_fields\" : [\"query.query_builder_field\"]}");
            Response rsp = client().performRequest(request);
            assertEquals(200, rsp.getStatusLine().getStatusCode());
            Map<?, ?> hitRsp = (Map<?, ?>) ((List<?>) ((Map<?, ?>) toMap(rsp).get("hits")).get("hits")).get(0);
            String queryBuilderStr = (String) ((List<?>) ((Map<?, ?>) hitRsp.get("fields"))
                    .get("query.query_builder_field")).get(0);
            byte[] qbSource = Base64.getDecoder().decode(queryBuilderStr);
            try (InputStream in = new ByteArrayInputStream(qbSource, 0, qbSource.length)) {
                try (StreamInput input = new NamedWriteableAwareStreamInput(new InputStreamStreamInput(in),
                        registry)) {
                    input.setVersion(oldClusterVersion);
                    QueryBuilder queryBuilder = input.readNamedWriteable(QueryBuilder.class);
                    assert in.read() == -1;
                    assertEquals(expectedQueryBuilder, queryBuilder);
                }
            }
        }
    }
}

From source file:org.wso2.carbon.siddhi.editor.core.internal.EditorMicroservice.java

@POST
@Path("/workspace/exists/workspace")
@Produces("application/json")
public Response fileExistsAtWorkspace(String payload) {
    try {/*from  w  ww . jav  a 2s.c  o m*/
        String configName = "";
        String[] splitConfigContent = payload.split("configName=");
        if (splitConfigContent.length > 1) {
            configName = splitConfigContent[1];
        }
        byte[] base64ConfigName = Base64.getDecoder().decode(configName);
        String location = (Paths.get(Constants.RUNTIME_PATH, Constants.DIRECTORY_DEPLOYMENT)).toString();

        return Response.status(Response.Status.OK)
                .entity(workspace.exists(SecurityUtil.resolvePath(Paths.get(location).toAbsolutePath(),
                        Paths.get(new String(base64ConfigName, Charset.defaultCharset())))))
                .type(MediaType.APPLICATION_JSON).build();
    } catch (IOException e) {
        return Response.serverError().entity("failed." + e.getMessage()).build();
    } catch (Throwable ignored) {
        return Response.serverError().entity("failed").build();
    }
}

From source file:com.cinnober.msgcodec.json.TypeScannerJsonParser.java

@Override
public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException {
    if (currentToken != null) {
        String text = currentToken.getText();
        return Base64.getDecoder().decode(text); // PENDING: howto deal with the variant?
    } else {/*from ww w  .j a v  a 2 s. co  m*/
        return p.getBinaryValue(b64variant);
    }
}

From source file:com.streamsets.pipeline.lib.http.oauth2.OAuth2ConfigBean.java

private static PrivateKey parseRSAKey(String key, Stage.Context context, List<Stage.ConfigIssue> issues) {
    String privKeyPEM = key.replace("-----BEGIN PRIVATE KEY-----\n", "");
    privKeyPEM = privKeyPEM.replace("-----END PRIVATE KEY-----", "");
    privKeyPEM = privKeyPEM.replace("\n", "");
    privKeyPEM = privKeyPEM.replace("\r", "");

    try {//from  w w  w. j  a v  a 2 s.c  o  m
        // Base64 decode the data
        byte[] encoded = Base64.getDecoder().decode(privKeyPEM.getBytes());

        // PKCS8 decode the encoded RSA private key
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);

        KeyFactory kf = KeyFactory.getInstance(RSA);
        return kf.generatePrivate(keySpec);
    } catch (NoSuchAlgorithmException ex) {
        LOG.error(Utils.format("'{}' algorithm not available", RSA), ex);
        issues.add(context.createConfigIssue(CONFIG_GROUP, PREFIX + "algorithm", HTTP_25));
    } catch (InvalidKeySpecException ex) {
        LOG.error(Utils.format("'{}' algorithm not available", RSA), ex);
        issues.add(context.createConfigIssue(CONFIG_GROUP, PREFIX + "key", HTTP_26));
    } catch (IllegalArgumentException ex) {
        LOG.error("Invalid key", ex);
        issues.add(context.createConfigIssue(CONFIG_GROUP, PREFIX + "key", HTTP_27, ex.toString()));
    }
    return null;
}