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:org.trustedanalytics.servicebroker.hive.config.ExternalConfiguration.java

public String getKeyTabLocation() throws IOException {

    String keyTabFilePath = String.format("%s/%s.keytab", keyTabsDir,
            PrincipalNameNormalizer.create().normalize(getHiveSuperUser()));
    LOGGER.info("Trying to write keytab file" + keyTabFilePath);
    Path path = Paths.get(keyTabFilePath);
    if (Files.notExists(path)) {
        Files.write(path, Base64.getDecoder().decode(getHiveSuperUserKeyTab()), StandardOpenOption.CREATE_NEW);
    } else if (Files.isDirectory(path)) {
        throw new IOException(
                String.format("Under path %s exists directory. It's path where hive superuser keytab "
                        + "is stored. Please move or delete this directory", keyTabFilePath));
    }/*  w w w .ja  va2 s .c om*/
    return keyTabFilePath;
}

From source file:br.com.ufjf.labredes.rest.EleitorResource.java

@POST
@Path("/votar/{voto}")
public String votar(@PathParam("voto") String vote) {
    byte[] voto_decoded = Base64.getDecoder().decode(vote);
    SealedObject aux = (SealedObject) SerializationUtils.deserialize(voto_decoded);
    Voto voto = null;//  w  w  w. j  a  v a  2s.  co  m
    voto = (Voto) rsa.decrypt(aux, client_aes);

    Response ans = new Response();

    if (voto != null) {
        eleitorService.votar(voto.getCpf(), voto.getNumero());
        ans.Ok("Voto computado");
        //3.1 Responde
        byte[] data = SerializationUtils.serialize(rsa.encrypt(ans, client_aes));
        String retorno = Base64.getEncoder().encodeToString(data);
        return retorno;
    } else {
        ans.Error("Erro ao decriptar chave");
        //3.1 Responde
        byte[] data = SerializationUtils.serialize(rsa.encrypt(ans, client_aes));
        String retorno = Base64.getEncoder().encodeToString(data);
        return retorno;
    }
}

From source file:com.antonjohansson.elasticsearchshell.client.PasswordEncrypter.java

/**
 * Decrypts the given password, using the username as salt.
 *
 * @param username The username, used for salt.
 * @param password The password to decrypt.
 * @return The decrypted password.//  w  w  w  .  ja  va  2 s.c  om
 */
String decrypt(String username, String password) {
    try {
        String key = rightPad(username, KEY_SIZE).substring(0, KEY_SIZE);
        Key spec = new SecretKeySpec(key.getBytes(), algorithm);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(DECRYPT_MODE, spec);
        byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(password));
        return new String(decrypted);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:tk.jomp16.plugin.codecutils.CodecUtils.java

@Command("decode")
public void decode(CommandEvent commandEvent) throws Exception {
    if (commandEvent.getArgs().size() >= 2) {
        switch (commandEvent.getArgs().get(0).toLowerCase()) {
        case "base64":
            commandEvent.respond(new String(Base64.getDecoder().decode(commandEvent.getArgs().get(1))));
            break;
        case "hex":
            commandEvent.respond(new String(Hex.decodeHex(commandEvent.getArgs().get(1).toCharArray())));
            break;
        case "binary":
            commandEvent.respond(new String(
                    BinaryCodec.fromAscii(commandEvent.getArgs().get(1).replace(" ", "").getBytes())));
            break;
        default:/*from   w  ww  .j a v  a2  s  . c  o m*/
            commandEvent.showUsage(this, "decode");
            break;
        }
    } else {
        commandEvent.showUsage(this, "decode");
    }
}

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

public static boolean verifyRSASignature(String subordinatePublicKeyContent, String signatureContent,
        String masterPublicKeyContent) throws NoSuchProviderException, NoSuchAlgorithmException, IOException,
        InvalidKeySpecException, InvalidKeyException, SignatureException {
    PublicKey masterPublicKey = getRSAPublicKeyFrom(masterPublicKeyContent);
    signatureContent = signatureContent.replace("\n", "");
    Signature signature = Signature.getInstance("SHA512withRSA");
    signature.initVerify(masterPublicKey);
    signature.update(subordinatePublicKeyContent.getBytes());
    return signature.verify(Base64.getDecoder().decode(signatureContent.getBytes()));
}

From source file:bg.vitkinov.edu.services.ImageService.java

@RequestMapping(value = "/img", method = { RequestMethod.POST }, produces = { MediaType.IMAGE_PNG_VALUE,
        MediaType.IMAGE_GIF_VALUE, MediaType.IMAGE_JPEG_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE })
public byte[] convertToInlineTextImage(@RequestHeader(value = "Accept") String acceptType,
        @RequestParam String text, @RequestParam(required = false, defaultValue = "false") String base64,
        @RequestParam(required = false, defaultValue = "Arial-14") String font,
        @RequestParam(required = false, defaultValue = "black") String foreColor,
        @RequestParam(required = false) String backColor) {
    logger.info(acceptType);/*from   w  w  w  .  j  ava2  s . c  o  m*/
    logger.info("Text: " + text);
    return convert(Boolean.valueOf(base64) ? new String(Base64.getDecoder().decode(text)) : text,
            new TextToGraphicsConverter(createGraphicsProperties(font, foreColor, backColor)),
            GraphicsType.value(acceptType));
}

From source file:io.gumga.presentation.api.voice.VoiceReceiverAPI.java

@RequestMapping(value = "/voice", method = RequestMethod.POST)
public Map recebeSom(HttpServletRequest httpRequest) throws IOException {
    String som = convertStreamToString(httpRequest.getInputStream());
    System.out.println("----->" + som);
    Map<String, Object> problemas = new HashMap<>();
    try {/*from ww  w  .j  a v a2 s  .c o m*/
        som = som.replaceFirst("data:audio/wav;base64,", "");
        byte[] decode = Base64.getDecoder().decode(som.substring(0, 512));
        int sampleRate = unsignedToBytes(decode[27]) * 256 * 256 * 256 + unsignedToBytes(decode[26]) * 256 * 256
                + unsignedToBytes(decode[25]) * 256 + unsignedToBytes(decode[24]) * 1;

        RestTemplate restTemplate = new GumgaJsonRestTemplate();
        Map<String, Object> config = new HashMap<>();

        config.put("encoding", "LINEAR16");
        config.put("sampleRate", "" + sampleRate);
        config.put("languageCode", "pt-BR");
        config.put("maxAlternatives", "1");
        config.put("profanityFilter", "false");
        Map<String, Object> context = new HashMap<>();
        context.put("phrases", CONTEXT);
        config.put("speechContext", context); //EXPLORAR DEPOIS COM FRASES PARA "AJUDAR" o reconhecedor
        Map<String, Object> audio = new HashMap<>();
        audio.put("content", som);
        Map<String, Object> request = new HashMap<>();
        request.put("config", config);
        request.put("audio", audio);
        Map resposta = restTemplate.postForObject(
                "https://speech.googleapis.com/v1beta1/speech:syncrecognize?key=AIzaSyC7E4dZ4EneRmSzVMs2qhyJYGoTK49FCYM",
                request, Map.class);
        List<Object> analiseSintatica = analiseSintatica(resposta);
        resposta.put("objects", analiseSintatica);
        return resposta;
    } catch (Exception ex) {
        problemas.put("exception", ex);
    }
    return problemas;
}

From source file:com.netflix.spinnaker.orca.front50.tasks.SavePipelineTask.java

@SuppressWarnings("unchecked")
@Override//  w  ww . j  av  a2s .  c o m
public TaskResult execute(Stage stage) {
    if (front50Service == null) {
        throw new UnsupportedOperationException(
                "Front50 is not enabled, no way to save pipeline. Fix this by setting front50.enabled: true");
    }

    if (!stage.getContext().containsKey("pipeline")) {
        throw new IllegalArgumentException("pipeline context must be provided");
    }

    if (!(stage.getContext().get("pipeline") instanceof String)) {
        throw new IllegalArgumentException(
                "'pipeline' context key must be a base64-encoded string: Ensure you're on the most recent version of gate");
    }

    byte[] pipelineData;
    try {
        pipelineData = Base64.getDecoder().decode((String) stage.getContext().get("pipeline"));
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException("pipeline must be encoded as base64", e);
    }
    log.info("Expanded encoded pipeline:" + new String(pipelineData));

    Map<String, Object> pipeline = (Map<String, Object>) stage.decodeBase64("/pipeline", Map.class);

    if (!pipeline.containsKey("index")) {
        Map<String, Object> existingPipeline = fetchExistingPipeline(pipeline);
        if (existingPipeline != null) {
            pipeline.put("index", existingPipeline.get("index"));
        }
    }

    pipelineModelMutators.stream().filter(m -> m.supports(pipeline)).forEach(m -> m.mutate(pipeline));

    Response response = front50Service.savePipeline(pipeline);

    Map<String, Object> outputs = new HashMap<>();
    outputs.put("notification.type", "savepipeline");
    outputs.put("application", pipeline.get("application"));
    outputs.put("pipeline.name", pipeline.get("name"));

    if (pipeline.containsKey("id")) {
        // a newly created pipeline will not yet have an `id`
        outputs.put("pipeline.id", pipeline.get("id"));
    }

    return new TaskResult((response.getStatus() == HttpStatus.OK.value()) ? ExecutionStatus.SUCCEEDED
            : ExecutionStatus.TERMINAL, outputs);
}

From source file:org.kie.workbench.common.forms.jbpm.server.service.impl.documents.storage.impl.UploadedDocumentStorageImpl.java

@Override
public void uploadContentChunk(DocumentUploadChunk chunk) throws Exception {
    File docFolder = resolveDocStorage(chunk.getDocumentId());

    File chunkFile = docFolder.toPath().resolve(PARTS_FOLDER).resolve(resolveChunkFileName(chunk)).toFile();

    FileUtils.writeByteArrayToFile(chunkFile, Base64.getDecoder().decode(chunk.getContent()));

    chunk.clearContent();//ww  w.j a v a2  s. c o  m
}

From source file:org.apache.syncope.core.workflow.java.AbstractUserWorkflowAdapter.java

protected String decrypt(final String crypted) {
    byte[] decrypted = EncryptorFactory.getInstance().getDefaultEncryptor()
            .decrypt(Base64.getDecoder().decode(crypted));
    return new String(decrypted);
}