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:com.github.horrorho.inflatabledonkey.cloud.escrow.EscrowOperationsRecover.java

static BlobA6 blobA6(String respBlob) {
    byte[] data = Base64.getDecoder().decode(respBlob);
    ByteBuffer buffer = ByteBuffer.wrap(data);
    return new BlobA6(buffer);
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.externalServices.OAuthAction.java

public ActionForward redirectToRedirectUrl(ActionMapping mapping, HttpServletRequest request,
        HttpServletResponse response, Person person, final Cookie cookie) {
    String cookieValue = new String(Base64.getDecoder().decode(cookie.getValue()));
    final int indexOf = cookieValue.indexOf("|");
    String clientApplicationId = cookieValue.substring(0, indexOf);
    String redirectUrl = cookieValue.substring(indexOf + 1, cookieValue.length());

    return redirectToRedirectUrl(mapping, request, response, person, clientApplicationId, redirectUrl);
}

From source file:org.apache.nifi.registry.web.api.SecureLdapIT.java

@Test
public void testTokenGenerationAndAccessStatus() throws Exception {

    // Note: this test intentionally does not use the token generated
    // for nifiadmin by the @Before method

    // Given: the client and server have been configured correctly for LDAP authentication
    String expectedJwtPayloadJson = "{" + "\"sub\":\"nobel\"," + "\"preferred_username\":\"nobel\","
            + "\"iss\":\"LdapIdentityProvider\"" + "}";
    String expectedAccessStatusJson = "{" + "\"identity\":\"nobel\"," + "\"anonymous\":false" + "}";

    // When: the /access/token/login endpoint is queried
    final String basicAuthCredentials = encodeCredentialsForBasicAuth("nobel", "password");
    final Response tokenResponse = client.target(createURL(tokenIdentityProviderPath)).request()
            .header("Authorization", "Basic " + basicAuthCredentials).post(null, Response.class);

    // Then: the server returns 200 OK with an access token
    assertEquals(201, tokenResponse.getStatus());
    String token = tokenResponse.readEntity(String.class);
    assertTrue(StringUtils.isNotEmpty(token));
    String[] jwtParts = token.split("\\.");
    assertEquals(3, jwtParts.length);/*www.  j av a 2s .co  m*/
    String jwtPayload = new String(Base64.getDecoder().decode(jwtParts[1]), "UTF-8");
    JSONAssert.assertEquals(expectedJwtPayloadJson, jwtPayload, false);

    // When: the token is returned in the Authorization header
    final Response accessResponse = client.target(createURL("access")).request()
            .header("Authorization", "Bearer " + token).get(Response.class);

    // Then: the server acknowledges the client has access
    assertEquals(200, accessResponse.getStatus());
    String accessStatus = accessResponse.readEntity(String.class);
    JSONAssert.assertEquals(expectedAccessStatusJson, accessStatus, false);

}

From source file:com.artglorin.web.utils.XmlByteExtractor.java

private List<Description> extract(String tagName, String valueAttr) throws ExtractionException {
    NodeList tags = document.getElementsByTagName(tagName);
    List<Description> result = new ArrayList<>(tags.getLength());
    byte[] data;//from  ww w. jav a2  s .  co m
    String type, extension, value, decodeType;
    Node node;
    for (int i = 0; i < tags.getLength(); i++) {
        node = tags.item(i);
        value = node.getAttributes().getNamedItem(valueAttr).getNodeValue();
        if (value.startsWith("data:")) {
            try {
                type = value.substring(value.indexOf(":") + 1, value.indexOf("/"));
            } catch (Exception e) {
                throw new InvalidTypeException(value);
            }
            try {
                extension = value.substring(value.indexOf("/") + 1, value.indexOf(";"));
            } catch (Exception e) {
                throw new InvalidExtensionException(value);
            }
            try {
                decodeType = value.substring(value.indexOf(";") + 1, value.indexOf(","));
            } catch (Exception e) {
                throw new InvalidDecodeTypeException(value);
            }
            if (decodeType.equals("base64")) {
                try {
                    data = Base64.getDecoder().decode(value.substring(value.indexOf(",") + 1));
                } catch (Exception e) {
                    throw new DecodeException(e.toString());
                }
            } else {
                throw new InvalidDecodeTypeException(decodeType);
            }
            result.add(new Description().setData(data).setExtension(extension).setNode(node).setType(type));
        } else if (value.startsWith("http:") || value.startsWith("https:")) {
            URL url;
            try {
                url = new URL(value);
            } catch (MalformedURLException e) {
                e.printStackTrace();
                throw new ExtractionException("Cannot create URL. Exception: " + e.toString());
            }
            URLConnection connection;
            try {
                connection = url.openConnection();
            } catch (IOException e) {
                throw new ExtractionException("Cannot open connection");
            }
            String contentType = connection.getContentType();

            if (contentType.toLowerCase().startsWith("image/") || contentType.toLowerCase().startsWith("audio/")
                    || contentType.toLowerCase().startsWith("video/")) {
                type = contentType.substring(0, contentType.indexOf("/"));
                extension = contentType.substring(contentType.indexOf("/") + 1);
                try {
                    data = IOUtils.toByteArray(connection.getInputStream());
                } catch (IOException e) {
                    throw new ExtractionException("Cannot get bytes from source: " + value);
                }
                result.add(new Description().setData(data).setExtension(extension).setType(type).setNode(node));
            } else {
                throw new InvalidTypeException(contentType);
            }
        } else {
            throw new UnsupportedFormatException(value);
        }
    }
    return result;
}

From source file:es.tid.keyserver.https.protocol.InputJSON.java

/**
 * This method is used to verify the integrity of the JSON
 * @return Null if all fields are correct, Otherwise this method returns the error name.
 *//*w ww  .  j  a va 2 s. c om*/
public String checkValidJSON() {
    // Extracting JSON fields
    String protocol = this.getProtocol();
    String method = this.getMethod();
    String hash = this.getHash();
    String spki = this.getSpki();
    String input = this.getInput();
    // Logger trace output
    LOGGER.trace("Method CheckJSON (fields): protocol='{}', method='{}', hash='{}', spki='{}', input='{}'",
            protocol, method, hash, spki, input);
    // Check if the JSON contains all fields "protocol", "method", "hash", 
    //  "spki" and "input" fields.
    if ((protocol == null) || (method == null) || (spki == null) || (input == null)) {
        LOGGER.debug("Input JSON: Some required fields are not present.");
        return ErrorJSON.ERR_MALFORMED_REQUEST;
    } else {
        LOGGER.debug("Input JSON: 'Mehtod', 'spky' and 'input' fields are present.");
    }
    // Parsing input field from base64 to array of bytes
    LOGGER.debug("JSON Input data to decode from base64: {}", input);
    byte inputDataB[] = Base64.getDecoder().decode(input.trim());
    LOGGER.trace("JSON Input Field number of Bytes: {}", inputDataB);
    // Check the length of input
    switch (method) {
    case InputJSON.RSA:
        if (inputDataB.length < 10) { // If it has some bytes (less than 10 for example)
            LOGGER.debug("Input JSON: RSA length too short ({} bytes).", inputDataB.length);
            return ErrorJSON.ERR_MALFORMED_REQUEST;
        }
        break;
    case InputJSON.ECDHE:
        // Check if HASH field is present (not null) and valid.
        if (hash == null) {
            LOGGER.debug("Input JSON: Hash field not valid ('{}').", hash);
            return ErrorJSON.ERR_MALFORMED_REQUEST;
        }
        // Check JSON input length.
        if (inputDataB.length != 133) { // 32+32+69 = 133 bytes 
            LOGGER.debug("Input JSON: ECDH length not valid ({} bytes).", inputDataB.length);
            return ErrorJSON.ERR_MALFORMED_REQUEST;
        }
        break;
    default:
        LOGGER.debug("Input JSON: Not valid 'method' field for this input JSON ('{}').", method);
        return ErrorJSON.ERR_MALFORMED_REQUEST;
    }
    return null;
}

From source file:org.apache.nifi.provenance.CryptoUtils.java

/**
 * Returns a map containing the key IDs and the parsed key from a key provider definition file.
 * The values in the file are decrypted using the master key provided. If the file is missing or empty,
 * cannot be read, or if no valid keys are read, a {@link KeyManagementException} will be thrown.
 *
 * @param filepath  the key definition file path
 * @param masterKey the master key used to decrypt each key definition
 * @return a Map of key IDs to SecretKeys
 * @throws KeyManagementException if the file is missing or invalid
 *//*w w w  .  j  ava  2s. com*/
public static Map<String, SecretKey> readKeys(String filepath, SecretKey masterKey)
        throws KeyManagementException {
    Map<String, SecretKey> keys = new HashMap<>();

    if (StringUtils.isBlank(filepath)) {
        throw new KeyManagementException("The key provider file is not present and readable");
    }
    File file = new File(filepath);
    if (!file.exists() || !file.canRead()) {
        throw new KeyManagementException("The key provider file is not present and readable");
    }

    try (BufferedReader br = new BufferedReader(new FileReader(file))) {
        AESKeyedCipherProvider masterCipherProvider = new AESKeyedCipherProvider();

        String line;
        int l = 1;
        while ((line = br.readLine()) != null) {
            String[] components = line.split("=", 2);
            if (components.length != 2 || StringUtils.isAnyEmpty(components)) {
                logger.warn("Line " + l + " is not properly formatted -- keyId=Base64EncodedKey...");
            }
            String keyId = components[0];
            if (StringUtils.isNotEmpty(keyId)) {
                try {
                    byte[] base64Bytes = Base64.getDecoder().decode(components[1]);
                    byte[] ivBytes = Arrays.copyOfRange(base64Bytes, 0, IV_LENGTH);

                    Cipher masterCipher = null;
                    try {
                        masterCipher = masterCipherProvider.getCipher(EncryptionMethod.AES_GCM, masterKey,
                                ivBytes, false);
                    } catch (Exception e) {
                        throw new KeyManagementException(
                                "Error building cipher to decrypt FileBaseKeyProvider definition at "
                                        + filepath,
                                e);
                    }
                    byte[] individualKeyBytes = masterCipher
                            .doFinal(Arrays.copyOfRange(base64Bytes, IV_LENGTH, base64Bytes.length));

                    SecretKey key = new SecretKeySpec(individualKeyBytes, "AES");
                    logger.debug("Read and decrypted key for " + keyId);
                    if (keys.containsKey(keyId)) {
                        logger.warn("Multiple key values defined for " + keyId + " -- using most recent value");
                    }
                    keys.put(keyId, key);
                } catch (IllegalArgumentException e) {
                    logger.error("Encountered an error decoding Base64 for " + keyId + ": "
                            + e.getLocalizedMessage());
                } catch (BadPaddingException | IllegalBlockSizeException e) {
                    logger.error("Encountered an error decrypting key for " + keyId + ": "
                            + e.getLocalizedMessage());
                }
            }
            l++;
        }

        if (keys.isEmpty()) {
            throw new KeyManagementException("The provided file contained no valid keys");
        }

        logger.info("Read " + keys.size() + " keys from FileBasedKeyProvider " + filepath);
        return keys;
    } catch (IOException e) {
        throw new KeyManagementException("Error reading FileBasedKeyProvider definition at " + filepath, e);
    }

}

From source file:ostepu.file.fileUtils.java

/**
 * dekodiert einen Base64 Text//  w w w.  ja  v a2s.  c om
 *
 * @param content der Base64 kodierte Text
 * @return der resultierende Text
 */
public static String decodeBase64(String content) {
    Decoder dec = Base64.getDecoder();
    return new String(dec.decode(content));
}

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

@RequestMapping(value = Routes.DOWNLOAD_DUMP_FILE_ROOT
        + "/{dumpFileId:[0-9]+}", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public @ResponseBody void download(@PathVariable Integer dumpFileId, HttpServletRequest request,
        HttpServletResponse resp, @RequestParam(value = "original", required = false) String original)
        throws IOException, DumpFileDeletedException {
    DatabaseDumpFile databaseDumpFile = getDatabaseDumpFile(dumpFileId);
    this.checkDbDumperServiceInstance(databaseDumpFile.getDbDumperServiceInstance());
    this.checkDatabaseDumpFile(databaseDumpFile);
    String userRequest = "";
    String passwordRequest = "";
    String authorization = request.getHeader("Authorization");
    if (authorization != null && authorization.startsWith("Basic")) {
        String base64Credentials = authorization.substring("Basic".length()).trim();
        String credentials = new String(Base64.getDecoder().decode(base64Credentials),
                Charset.forName("UTF-8"));
        String[] values = credentials.split(":", 2);
        userRequest = values[0];/*ww  w. j av  a2 s.  c o  m*/
        passwordRequest = values[1];
    } else {
        this.getErrorResponseEntityBasicAuth(resp);
        return;
    }

    if (!userRequest.equals(databaseDumpFile.getUser())
            || !passwordRequest.equals(databaseDumpFile.getPassword())) {
        this.getErrorResponseEntityBasicAuth(resp);
        return;
    }

    String fileName = DumpFileHelper.getFilePath(databaseDumpFile);
    resp.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
    resp.setContentLengthLong(this.filer.getContentLength(fileName));
    InputStream inputStream = null;
    if (original == null || original.isEmpty()) {
        inputStream = filer.retrieveWithOriginalStream(fileName);
    } else {
        inputStream = filer.retrieveWithStream(fileName);
        File file = new File(fileName);
        String[] filenames = file.getName().split("\\.");
        if (filenames.length >= 2) {
            fileName = filenames[0] + "." + filenames[1];
        }

    }
    inputStream = new BufferedInputStream(inputStream);
    File file = new File(fileName);
    resp.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

    OutputStream outputStream = null;
    outputStream = resp.getOutputStream();
    try {
        ByteStreams.copy(inputStream, outputStream);
    } finally {
        Closeables.closeQuietly(inputStream);
        outputStream.flush();
        resp.flushBuffer();
        Closeables.close(outputStream, true);
    }
}

From source file:org.zanata.magpie.api.service.impl.AccountResourceImpl.java

protected Optional<Pair<String, String>> processAuthHeader(@NotNull String authHeader) {
    Matcher headerMatcher = AUTH_HEADER_PATTERN.matcher(authHeader);
    if (headerMatcher.find() && headerMatcher.groupCount() == 1) {
        String base64Encoded = headerMatcher.group(1);
        byte[] decodedBytes = Base64.getDecoder().decode(base64Encoded);
        String decodedString = new String(decodedBytes, StandardCharsets.UTF_8);

        Matcher decodeMatcher = AUTH_DECODE_PATTERN.matcher(decodedString);
        if (decodeMatcher.find() && decodeMatcher.groupCount() == 2) {
            return Optional.of(Pair.of(decodeMatcher.group(1), decodeMatcher.group(2)));
        }/*from  w ww  .  j  a v a  2s. co  m*/
    }
    return Optional.empty();
}

From source file:org.wso2.is.portal.user.client.api.ChallengeQuestionManagerClientServiceImpl.java

@Override
public void setChallengeQuestionForUser(String userUniqueId, String questionId, String questionSetId,
        String answer, String actionId)
        throws IdentityStoreException, UserNotFoundException, IdentityRecoveryException {

    if (challengeQuestionManager == null || realmService == null) {
        throw new IdentityRecoveryException("Challenge question manager or Realm service is not available.");
    }//w w w.  j  a v  a2 s  .  c o  m

    User user = realmService.getIdentityStore().getUser(userUniqueId);

    List<UserChallengeAnswer> existingAnswers = challengeQuestionManager
            .getChallengeAnswersOfUser(userUniqueId);

    if (StringUtils.equals(actionId, "challengeQUpdate")) {
        Iterator<UserChallengeAnswer> existingAnswersIterator = existingAnswers.iterator();
        while (existingAnswersIterator.hasNext()) {
            ChallengeQuestion challengeQuestion = existingAnswersIterator.next().getQuestion();
            if (StringUtils.equals(challengeQuestion.getQuestionSetId(),
                    new String(Base64.getDecoder().decode(questionSetId.getBytes(Charset.forName("UTF-8"))),
                            Charset.forName("UTF-8")))
                    && StringUtils.equals(challengeQuestion.getQuestionId(), questionId)) {
                existingAnswersIterator.remove();
                break;
            }
        }
    }

    List<ChallengeQuestion> challengeQuestions = challengeQuestionManager.getAllChallengeQuestionsForUser(user);
    ChallengeQuestion challengeQuestion = challengeQuestions.stream()
            .filter(question -> StringUtils.equals(question.getQuestionId(), questionId) && StringUtils.equals(
                    question.getQuestionSetId(),
                    new String(Base64.getDecoder().decode(questionSetId.getBytes(Charset.forName("UTF-8"))),
                            Charset.forName("UTF-8"))))
            .findFirst().get();

    UserChallengeAnswer userChallengeAnswer = new UserChallengeAnswer(challengeQuestion, answer);
    existingAnswers.add(userChallengeAnswer);

    challengeQuestionManager.setChallengesOfUser(user, existingAnswers);
}