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:net.straylightlabs.archivo.model.Tivo.java

/**
 * Create a new Tivo object from a JSON String.
 *
 * @param json String containing the Tivo object in JSON
 * @param mak  Media access key to use for the resulting Tivo
 * @return A new Tivo object//from w ww.j  a v  a 2s . c om
 * @throws IllegalArgumentException
 */
public static Tivo fromJSON(final String json, final String mak) throws IllegalArgumentException {
    JSONObject jo = new JSONObject(json);
    String name = jo.getString(JSON_NAME);
    String tsn = jo.getString(JSON_TSN);
    int port = jo.getInt(JSON_PORT);
    JSONArray jsonAddresses = jo.getJSONArray(JSON_ADDRESSES);
    Set<InetAddress> addresses = new HashSet<>();
    Base64.Decoder decoder = Base64.getDecoder();
    for (int i = 0; i < jsonAddresses.length(); i++) {
        try {
            addresses.add(InetAddress.getByAddress(decoder.decode(jsonAddresses.getString(i))));
        } catch (UnknownHostException e) {
            throw new IllegalArgumentException("TiVo address in invalid: " + e.getLocalizedMessage());
        }
    }

    return new Builder().name(name).tsn(tsn).port(port).addresses(addresses).mak(mak).build();
}

From source file:com.antsdb.saltedfish.nosql.LogReplayer.java

private void run(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();
    CommandLine line = parser.parse(getOptions(), args);

    // help/*from  ww  w .j  av  a  2 s  .  c o m*/

    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("replay", getOptions());
        return;
    }

    // other options

    this.hexDump = line.hasOption("hex");
    this.notrx = line.hasOption("notrx");
    if (line.getOptionValue("table") != null) {
        this.tableId = Integer.parseInt(line.getOptionValue("table"));
    }
    if (line.getOptionValue("rowid") != null) {
        this.rowid = Long.parseLong(line.getOptionValue("rowid"));
    }
    Heap heap = new BluntHeap();
    if (line.getOptionValue("key") != null) {
        String keyText = line.getOptionValue("key");
        byte[] keyBytes = Base64.getDecoder().decode(keyText);
        KeyBytes key = KeyBytes.allocSet(heap, keyBytes);
        this.pKey = key.getAddress();
    }

    // start offset

    if (line.getOptionValue('s') != null) {
        String literal = line.getOptionValue('s');
        this.offset = Long.parseUnsignedLong(literal, 16);
    }

    // length

    if (line.getOptionValue('n') != null) {
        String literal = line.getOptionValue('n');
        this.length = Integer.parseInt(literal);
    }

    // now go

    if (line.getOptionValue("home") == null) {
        err.println("error: data directory is not specified");
        return;
    }
    this.home = new File(line.getOptionValue("home"));
    if (!home.isDirectory()) {
        err.println("error: invalid home directory");
        return;
    }
    if (!new File(this.home, "checkpoint.bin").exists()) {
        err.println("error: invalid home directory");
        return;
    }

    // go go go
    this.out.println("log location: {}", this.home);
    this.spaceman = new SpaceManager(home, false);
    spaceman.init();
    Gobbler gobbler = new Gobbler(spaceman, false);
    findStart();
    println("start position: %08x", this.offset);
    try {
        gobbler.replay(this.offset, true, this);
    } catch (JumpException ignored) {
    }
}

From source file:org.opendaylight.aaa.encrypt.AAAEncryptionServiceImpl.java

public AAAEncryptionServiceImpl(AaaEncryptServiceConfig encrySrvConfig, final DataBroker dataBroker) {
    SecretKey tempKey = null;// w  ww .j a v a2s  .com
    IvParameterSpec tempIvSpec = null;
    if (encrySrvConfig.getEncryptSalt() == null) {
        throw new IllegalArgumentException(
                "null encryptSalt in AaaEncryptServiceConfig: " + encrySrvConfig.toString());
    }
    if (encrySrvConfig.getEncryptKey() != null && encrySrvConfig.getEncryptKey().isEmpty()) {
        LOG.debug("Set the Encryption service password and encrypt salt");
        String newPwd = RandomStringUtils.random(encrySrvConfig.getPasswordLength(), true, true);
        final Random random = new SecureRandom();
        byte[] salt = new byte[16];
        random.nextBytes(salt);
        String encodedSalt = Base64.getEncoder().encodeToString(salt);
        encrySrvConfig = new AaaEncryptServiceConfigBuilder(encrySrvConfig).setEncryptKey(newPwd)
                .setEncryptSalt(encodedSalt).build();
        updateEncrySrvConfig(newPwd, encodedSalt);
        initializeConfigDataTree(encrySrvConfig, dataBroker);
    }
    final byte[] enryptionKeySalt = Base64.getDecoder().decode(encrySrvConfig.getEncryptSalt());
    try {
        final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encrySrvConfig.getEncryptMethod());
        final KeySpec spec = new PBEKeySpec(encrySrvConfig.getEncryptKey().toCharArray(), enryptionKeySalt,
                encrySrvConfig.getEncryptIterationCount(), encrySrvConfig.getEncryptKeyLength());
        tempKey = keyFactory.generateSecret(spec);
        tempKey = new SecretKeySpec(tempKey.getEncoded(), encrySrvConfig.getEncryptType());
        tempIvSpec = new IvParameterSpec(enryptionKeySalt);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        LOG.error("Failed to initialize secret key", e);
    }
    key = tempKey;
    ivspec = tempIvSpec;
    Cipher cipher = null;
    try {
        cipher = Cipher.getInstance(encrySrvConfig.getCipherTransforms());
        cipher.init(Cipher.ENCRYPT_MODE, key, ivspec);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException
            | InvalidKeyException e) {
        LOG.error("Failed to create encrypt cipher.", e);
    }
    this.encryptCipher = cipher;
    cipher = null;
    try {
        cipher = Cipher.getInstance(encrySrvConfig.getCipherTransforms());
        cipher.init(Cipher.DECRYPT_MODE, key, ivspec);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException
            | InvalidKeyException e) {
        LOG.error("Failed to create decrypt cipher.", e);
    }
    this.decryptCipher = cipher;
}

From source file:dk.dma.msinm.user.security.oauth.GoogleOAuthProvider.java

/**
 * {@inheritDoc}/*from  ww  w  .j a v a2s.  c  o m*/
 */
@Override
public User authenticateUser(HttpServletRequest request) throws Exception {

    OAuthService service = getOAuthService(settings, app.getBaseUri());
    if (service == null) {
        log.warn("OAuth service not available for " + getOAuthProviderId());
        throw new Exception("OAuth service not available for " + getOAuthProviderId());
    }

    String oauthVerifier = request.getParameter("code");
    Verifier verifier = new Verifier(oauthVerifier);

    Token accessToken = service.getAccessToken(OAuthConstants.EMPTY_TOKEN, verifier);
    log.info("Access Granted to Google with token " + accessToken);

    // check
    // https://github.com/haklop/myqapp/blob/b005df2e100f8aff7c1529097b651b1fd7ce6a4c/src/main/java/com/infoq/myqapp/controller/GoogleController.java
    String idToken = GoogleApiProvider.getIdToken(accessToken.getRawResponse());
    String userIdToken = idToken.split("\\.")[1];
    log.info("Received ID token " + userIdToken);

    String profile = new String(Base64.getDecoder().decode(userIdToken));
    log.info("Decoded " + profile);

    try (JsonReader jsonReader = Json.createReader(new StringReader(profile))) {
        JsonObject json = jsonReader.readObject();

        String email = json.containsKey("email") ? json.getString("email") : null;
        String firstName = json.containsKey("given_name") ? json.getString("given_name") : null;
        String lastName = json.containsKey("family_name") ? json.getString("family_name") : null;
        if (StringUtils.isBlank(email)) {
            throw new Exception("No email found in OAuth token");
        }
        log.info("Email  " + email);

        User user = userService.findByEmail(email);
        if (user == null) {
            user = new User();
            user.setEmail(email);
            user.setLanguage("en");
            user.setFirstName(firstName);
            user.setLastName(StringUtils.isBlank(lastName) ? email : lastName);
            user = userService.registerOAuthOnlyUser(user);
        }
        return user;
    }
}

From source file:org.wso2.carbon.webapp.authenticator.framework.authenticator.BSTAuthenticator.java

@Override
public AuthenticationInfo authenticate(Request request, Response response) {
    String requestUri = request.getRequestURI();
    String requestMethod = request.getMethod();
    AuthenticationInfo authenticationInfo = new AuthenticationInfo();
    if ((requestUri == null) || ("".equals(requestUri))) {
        authenticationInfo.setStatus(WebappAuthenticator.Status.CONTINUE);
        return authenticationInfo;
    }//from w  w w  .j a  v a2 s  .c om

    StringTokenizer tokenizer = new StringTokenizer(requestUri, "/");
    String context = tokenizer.nextToken();
    if ((context == null) || ("".equals(context))) {
        authenticationInfo.setStatus(WebappAuthenticator.Status.CONTINUE);
    }
    try {
        String bearerToken = new String(Base64.getDecoder().decode(request.getAttribute("BST").toString()));
        String resource = requestUri + ":" + requestMethod;
        OAuthValidationResponse oAuthValidationResponse = this.tokenValidator.validateToken(bearerToken,
                resource);
        authenticationInfo = Utils.setAuthenticationInfo(oAuthValidationResponse, authenticationInfo);
    } catch (AuthenticationException e) {
        log.error("Failed to authenticate the incoming request", e);
    } catch (OAuthTokenValidationException e) {
        log.error("Failed to authenticate the incoming request due to oauth token validation error.", e);
    }
    return authenticationInfo;
}

From source file:org.springframework.cloud.gcp.core.DefaultCredentialsProvider.java

/**
 * The credentials provided by this object originate from the following sources:
 * <ul>//from www.j av a  2s.  com
 *     <li>*.credentials.location: Credentials built from JSON content inside the file pointed
 *     to by this property,</li>
 *     <li>*.credentials.encoded-key: Credentials built from JSON String, encoded on
 *     base64,</li>
 *     <li>Google Cloud Client Libraries default credentials provider.</li>
 * </ul>
 *
 * <p>If credentials are provided by one source, the next sources are discarded.
 * @param credentialsSupplier provides properties that can override OAuth2
 * scopes list used by the credentials, and the location of the OAuth2 credentials private
 * key.
 * @throws IOException if an issue occurs creating the DefaultCredentialsProvider
 */
public DefaultCredentialsProvider(CredentialsSupplier credentialsSupplier) throws IOException {
    List<String> scopes = resolveScopes(credentialsSupplier.getCredentials().getScopes());
    Resource providedLocation = credentialsSupplier.getCredentials().getLocation();
    String encodedKey = credentialsSupplier.getCredentials().getEncodedKey();

    if (!StringUtils.isEmpty(providedLocation)) {
        this.wrappedCredentialsProvider = FixedCredentialsProvider
                .create(GoogleCredentials.fromStream(providedLocation.getInputStream()).createScoped(scopes));
    } else if (!StringUtils.isEmpty(encodedKey)) {
        this.wrappedCredentialsProvider = FixedCredentialsProvider.create(
                GoogleCredentials.fromStream(new ByteArrayInputStream(Base64.getDecoder().decode(encodedKey)))
                        .createScoped(scopes));
    } else {
        this.wrappedCredentialsProvider = GoogleCredentialsProvider.newBuilder().setScopesToApply(scopes)
                .build();
    }

    try {
        Credentials credentials = this.wrappedCredentialsProvider.getCredentials();

        if (LOGGER.isInfoEnabled()) {
            if (credentials instanceof UserCredentials) {
                LOGGER.info("Default credentials provider for user "
                        + ((UserCredentials) credentials).getClientId());
            } else if (credentials instanceof ServiceAccountCredentials) {
                LOGGER.info("Default credentials provider for service account "
                        + ((ServiceAccountCredentials) credentials).getClientEmail());
            } else if (credentials instanceof ComputeEngineCredentials) {
                LOGGER.info("Default credentials provider for Google Compute Engine.");
            }
            LOGGER.info("Scopes in use by default credentials: " + scopes.toString());
        }
    } catch (IOException ioe) {
        LOGGER.warn("No core credentials are set. Service-specific credentials "
                + "(e.g., spring.cloud.gcp.pubsub.credentials.*) should be used if your app uses "
                + "services that require credentials.");
    }
}

From source file:io.hakbot.providers.appspider.AppSpiderProvider.java

public void process(Job job) {
    // Retrieve payload and extract scan config (which is currently Base64 encoded)
    final JsonObject payload = JsonUtil.toJsonObject(getProviderPayload(job).getContents());
    final String scanConfig = JsonUtil.getString(payload, "scanConfig");

    // Retrieve the remote instance defined during initialization
    final RemoteInstance remoteInstance = getRemoteInstance(job);

    final NTOService service = new NTOService(remoteInstance.getURL(), AppSpiderConstants.SERVICE_NAME);
    final NTOServiceSoap soap = service.getNTOServiceSoap();

    // Retrieve UUID from job and use it as the AppSpider scan token
    final String token = UuidUtil.stripHyphens(job.getUuid());
    setJobProperty(job, "token", token);

    // Decodes the scan config (should be XML)
    final String decodedScanConfig = new String(Base64.getDecoder().decode(scanConfig));

    // Parse the scanConfig and retrieve the scan name
    final String scanName = getScanName(decodedScanConfig);
    setJobProperty(job, "scanName", scanName);

    // Submit the scan request
    final Result submitResult = soap.runScanXml(remoteInstance.getUsername(), remoteInstance.getPassword(),
            token, decodedScanConfig, null, null);
    if (!submitResult.isSuccess()) {
        updateState(job, State.FAILED, "Failed to execute AppSpider job", submitResult.getErrorDescription());
    }//ww  w.  j  a  va2s. c  o  m
}

From source file:org.flowable.cmmn.engine.impl.history.async.json.transformer.VariableUpdatedHistoryJsonTransformer.java

@Override
public void transformJson(HistoryJobEntity job, ObjectNode historicalData, CommandContext commandContext) {
    HistoricVariableInstanceEntity historicVariable = getHistoricVariableInstanceEntity(historicalData,
            commandContext);//from  w  w w.  j  av a 2 s  . co m

    Date time = getDateFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_LAST_UPDATE_TIME);
    if (historicVariable.getLastUpdatedTime().after(time)) {
        // If the historic variable already has a later time, we don't need to change its details
        // to something that is already superseded by later data.
        return;
    }

    VariableTypes variableTypes = CommandContextUtil.getCmmnEngineConfiguration(commandContext)
            .getVariableTypes();
    VariableType variableType = variableTypes
            .getVariableType(getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_VARIABLE_TYPE));
    historicVariable.setVariableType(variableType);

    historicVariable.setTextValue(
            getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_VARIABLE_TEXT_VALUE));
    historicVariable.setTextValue2(
            getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_VARIABLE_TEXT_VALUE2));
    historicVariable.setDoubleValue(
            getDoubleFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_VARIABLE_DOUBLE_VALUE));
    historicVariable
            .setLongValue(getLongFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_VARIABLE_LONG_VALUE));

    String variableBytes = getStringFromJson(historicalData,
            CmmnAsyncHistoryConstants.FIELD_VARIABLE_BYTES_VALUE);
    if (StringUtils.isNotEmpty(variableBytes)) {
        historicVariable.setBytes(Base64.getDecoder().decode(variableBytes));
    }

    historicVariable.setLastUpdatedTime(time);
}

From source file:de.sainth.recipe.backend.security.AuthFilter.java

private Optional<RecipeManagerAuthenticationToken> parseBasicAuth(String header)
        throws IOException, ServletException {
    byte[] base64Token = header.substring(6).getBytes();
    CharBuffer decoded = StandardCharsets.UTF_8
            .decode(Base64.getDecoder().decode(ByteBuffer.wrap(base64Token)));
    char c = decoded.get();
    StringBuilder sBuilder = new StringBuilder();
    while (decoded.hasRemaining() && c != ':') {
        sBuilder.append(c);/*  w ww. j  a  v  a2s . com*/
        c = decoded.get();
    }
    String username = sBuilder.toString();
    Optional<String> encryptedPassword = userRepository.getEncryptedPassword(username);
    if (encryptedPassword.isPresent()) {
        sBuilder.setLength(0);
        while (decoded.hasRemaining()) {
            sBuilder.append(decoded.get());
        }
        boolean matches = ScryptPasswordEncoder.sMatches(sBuilder, encryptedPassword.get());
        if (matches) {
            User user = userRepository.findOne(username);
            return Optional.of(new RecipeManagerAuthenticationToken(user.getId(), user.getPermission().name()));
        } else {
            return Optional.empty();
        }
    } else {
        return Optional.empty();
    }
}

From source file:ste.web.http.HttpUtils.java

private static String getAuthString(final Header authorization) {
    if (authorization == null) {
        return null;
    }//from ww w .  jav  a2 s  .  co  m

    String value = authorization.getValue();

    if ((value == null) || !value.startsWith("Basic ") || (value.length() == 6)) {
        return null;
    }

    value = value.substring(6);

    try {
        return new String(Base64.getDecoder().decode(value), "UTF-8");
    } catch (UnsupportedEncodingException x) {
        return null;
    }
}