List of usage examples for java.util Base64 getUrlEncoder
public static Encoder getUrlEncoder()
From source file:com.ibm.zurich.Main.java
public static void main(String[] args) throws NoSuchAlgorithmException, IOException { Option help = new Option(HELP, "print this message"); Option version = new Option(VERSION, "print the version information"); Options options = new Options(); Option useCurve = Option.builder(USECURVE).hasArg().argName("curve") .desc("Specify the BN Curve. Options: " + curveOptions()).build(); Option isskeygen = Option.builder(IKEYGEN).numberOfArgs(3).argName("ipk><isk><RL") .desc("Generate Issuer key pair and empty revocation list and store it in files").build(); Option join1 = Option.builder(JOIN1).numberOfArgs(3).argName("ipk><authsk><msg1") .desc("Create an authenticator secret key and perform the first step of the join protocol").build(); Option join2 = Option.builder(JOIN2).numberOfArgs(4).argName("ipk><isk><msg1><msg2") .desc("Complete the join protocol").build(); Option verify = Option.builder(VERIFY).numberOfArgs(5).argName("ipk><sig><krd><appId><RL") .desc("Verify a signature").build(); Option sign = Option.builder(SIGN).numberOfArgs(6).argName("ipk><authsk><msg2><appId><krd><sig") .desc("create a signature").build(); options.addOption(help);/*from w w w .j a va 2 s . c o m*/ options.addOption(version); options.addOption(useCurve); options.addOption(isskeygen); options.addOption(sign); options.addOption(verify); options.addOption(join1); options.addOption(join2); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new DefaultParser(); //FIXME Choose a proper instantiation of SecureRandom depending on the platform SecureRandom random = new SecureRandom(); Base64.Encoder encoder = Base64.getUrlEncoder(); Base64.Decoder decoder = Base64.getUrlDecoder(); try { CommandLine line = parser.parse(options, args); BNCurveInstantiation instantiation = null; BNCurve curve = null; if (line.hasOption(HELP) || line.getOptions().length == 0) { formatter.printHelp(USAGE, options); } else if (line.hasOption(VERSION)) { System.out.println("Version " + Main.class.getPackage().getImplementationVersion()); } else if (line.hasOption(USECURVE)) { instantiation = BNCurveInstantiation.valueOf(line.getOptionValue(USECURVE)); curve = new BNCurve(instantiation); } else { System.out.println("Specify the curve to use."); return; } if (line.hasOption(IKEYGEN)) { String[] optionValues = line.getOptionValues(IKEYGEN); // Create secret key IssuerSecretKey sk = Issuer.createIssuerKey(curve, random); // Store pk writeToFile((new IssuerPublicKey(curve, sk, random)).toJSON(curve), optionValues[0]); // Store sk writeToFile(sk.toJson(curve), optionValues[1]); // Create empty revocation list and store HashSet<BigInteger> rl = new HashSet<BigInteger>(); writeToFile(Verifier.revocationListToJson(rl, curve), optionValues[2]); } else if (line.hasOption(SIGN)) { //("ipk><authsk><msg2><appId><krd><sig") String[] optionValues = line.getOptionValues(SIGN); IssuerPublicKey ipk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0])); BigInteger authsk = curve.bigIntegerFromB(decoder.decode(readFromFile(optionValues[1]))); JoinMessage2 msg2 = new JoinMessage2(curve, readStringFromFile(optionValues[2])); // setup a new authenticator Authenticator auth = new Authenticator(curve, ipk, authsk); auth.EcDaaJoin1(curve.getRandomModOrder(random)); if (auth.EcDaaJoin2(msg2)) { EcDaaSignature sig = auth.EcDaaSign(optionValues[3]); // Write krd to file writeToFile(sig.krd, optionValues[4]); // Write signature to file writeToFile(sig.encode(curve), optionValues[5]); System.out.println("Signature written to " + optionValues[5]); } else { System.out.println("JoinMsg2 invalid"); } } else if (line.hasOption(VERIFY)) { Verifier ver = new Verifier(curve); String[] optionValues = line.getOptionValues(VERIFY); String pkFile = optionValues[0]; String sigFile = optionValues[1]; String krdFile = optionValues[2]; String appId = optionValues[3]; String rlPath = optionValues[4]; byte[] krd = Files.readAllBytes(Paths.get(krdFile)); IssuerPublicKey pk = new IssuerPublicKey(curve, readStringFromFile(pkFile)); EcDaaSignature sig = new EcDaaSignature(Files.readAllBytes(Paths.get(sigFile)), krd, curve); boolean valid = ver.verify(sig, appId, pk, Verifier.revocationListFromJson(readStringFromFile(rlPath), curve)); System.out.println("Signature is " + (valid ? "valid." : "invalid.")); } else if (line.hasOption(JOIN1)) { String[] optionValues = line.getOptionValues(JOIN1); IssuerPublicKey ipk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0])); // Create authenticator key BigInteger sk = curve.getRandomModOrder(random); writeToFile(encoder.encodeToString(curve.bigIntegerToB(sk)), optionValues[1]); Authenticator auth = new Authenticator(curve, ipk, sk); JoinMessage1 msg1 = auth.EcDaaJoin1(curve.getRandomModOrder(random)); writeToFile(msg1.toJson(curve), optionValues[2]); } else if (line.hasOption(JOIN2)) { String[] optionValues = line.getOptionValues(JOIN2); // create issuer with the specified key IssuerPublicKey pk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0])); IssuerSecretKey sk = new IssuerSecretKey(curve, readStringFromFile(optionValues[1])); Issuer iss = new Issuer(curve, sk, pk); JoinMessage1 msg1 = new JoinMessage1(curve, readStringFromFile(optionValues[2])); // Note that we do not check for nonce freshness. JoinMessage2 msg2 = iss.EcDaaIssuerJoin(msg1, false); if (msg2 == null) { System.out.println("Join message invalid."); } else { System.out.println("Join message valid, msg2 written to file."); writeToFile(msg2.toJson(curve), optionValues[3]); } } } catch (ParseException e) { System.out.println("Error parsing input."); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:net.morimekta.idltool.IdlUtils.java
private static File getCacheDirectory(File cacheDir, String repository) throws IOException { if (!cacheDir.exists()) { if (!cacheDir.mkdirs()) { throw new IOException( "Unable to create cache directory " + cacheDir.getCanonicalFile().getAbsolutePath()); }//from www . j a v a 2 s .c o m } String hash = Base64.getUrlEncoder() .encodeToString(DigestUtils.sha1(repository.getBytes(StandardCharsets.UTF_8))); return new File(cacheDir, hash).getCanonicalFile().getAbsoluteFile(); }
From source file:com.adr.mimame.media.MpgClip.java
private String getCachedMp3File(String url) throws IOException, NoSuchAlgorithmException { if (url == null) { throw new IOException("Null url"); } else if (!"http:".equalsIgnoreCase(url.substring(0, 5)) && !"https:".equalsIgnoreCase(url.substring(0, 6)) && !"ftp:".equalsIgnoreCase(url.substring(0, 4)) && !"jar:".equalsIgnoreCase(url.substring(0, 4))) { // a local file return url; } else {//w ww . j a va 2 s . c o m // a remote file FileUtils.forceMkdir(CACHEFOLDER); MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(url.getBytes("UTF-8")); String cachefilename = Base64.getUrlEncoder().encodeToString(md.digest()); File cachefile = new File(CACHEFOLDER, cachefilename + ".mp3"); if (cachefile.exists()) { return cachefile.getPath(); } else { try (InputStream input = new URL(url).openStream(); OutputStream output = new FileOutputStream(cachefile)) { byte[] buffer = new byte[4096]; int n; while ((n = input.read(buffer)) != -1) { output.write(buffer, 0, n); } } return cachefile.getPath(); } } }
From source file:de.tor.tribes.io.TroopAmountElement.java
public String toBase64() { try {/*from w w w . ja v a2s . co m*/ return Base64.getUrlEncoder().encodeToString(toString().getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { logger.fatal("Wrong encoding", e); throw new RuntimeException("Unsupported encoding", e); } }
From source file:com.adr.mimame.PlatformList.java
public Image getCachedImage(String url) { if (url == null) { return null; } else if (!"http".equalsIgnoreCase(url.substring(0, 4)) && !"ftp".equalsIgnoreCase(url.substring(0, 3))) { // a local image return new Image(url, true); } else {/* w w w . ja v a 2s . c o m*/ // a remote image try { File cachedir = new File(mimamememuhome, "IMGCACHE"); FileUtils.forceMkdir(cachedir); MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(url.getBytes("UTF-8")); String cachefilename = Base64.getUrlEncoder().encodeToString(md.digest()); File cachefile = new File(cachedir, cachefilename + ".png"); File cachefilenull = new File(cachedir, cachefilename + ".null"); if (cachefilenull.exists()) { return null; } else if (cachefile.exists()) { return new Image(cachefile.toURI().toURL().toString(), true); } else { Image img = new Image(url, true); img.progressProperty().addListener( (ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> { if (newValue.doubleValue() == 1.0) { exec.execute(() -> { try { if (img.isError()) { cachefilenull.createNewFile(); } else { ImageIO.write(SwingFXUtils.fromFXImage(img, null), "png", cachefile); } } catch (IOException ex) { logger.log(Level.SEVERE, "Cannot save image cache.", ex); } }); } }); return img; } } catch (IOException | NoSuchAlgorithmException ex) { logger.log(Level.SEVERE, "Cannot create image cache.", ex); return new Image(url); } } }
From source file:com.joseflavio.uxiamarelo.rest.UxiAmareloREST.java
private Response solicitar0(HttpHeaders cabecalho, String comando, String copaiba, String classe, String metodo, String json) {/*from w w w. j a v a2 s. c om*/ try { JSON objeto = null; if (uxiAmarelo.isCookieEnviar()) { Map<String, Cookie> cookies = cabecalho.getCookies(); if (cookies.size() > 0) { if (objeto == null) objeto = new JSON(json); for (Cookie cookie : cookies.values()) { String nome = cookie.getName(); if (uxiAmarelo.cookieBloqueado(nome)) continue; if (!objeto.has(nome)) { try { objeto.put(nome, URLDecoder.decode(cookie.getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { objeto.put(nome, cookie.getValue()); } } } } } if (uxiAmarelo.isEncapsulamentoAutomatico()) { if (objeto == null) objeto = new JSON(json); final String sepstr = uxiAmarelo.getEncapsulamentoSeparador(); final char sep0 = sepstr.charAt(0); for (String chave : new HashSet<>(objeto.keySet())) { if (chave.indexOf(sep0) == -1) continue; String[] caminho = chave.split(sepstr); if (caminho.length > 1) { Util.encapsular(caminho, objeto.remove(chave), objeto); } } } if (objeto != null) json = objeto.toString(); String resultado; if (comando == null) { try (CopaibaConexao cc = uxiAmarelo.conectarCopaiba(copaiba)) { resultado = cc.solicitar(classe, json, metodo); if (resultado == null) resultado = ""; } } else if (comando.equals("voltar")) { resultado = json; comando = null; } else { resultado = ""; } if (comando == null) { return respostaEXITO(resultado); } else if (comando.startsWith("redirecionar")) { return Response .temporaryRedirect(new URI(Util.obterStringDeJSON("redirecionar", comando, resultado))) .build(); } else if (comando.startsWith("base64")) { String url = comando.substring("base64.".length()); return Response .temporaryRedirect( new URI(url + Base64.getUrlEncoder().encodeToString(resultado.getBytes("UTF-8")))) .build(); } else if (comando.startsWith("html_url")) { HttpURLConnection con = (HttpURLConnection) new URL( Util.obterStringDeJSON("html_url", comando, resultado)).openConnection(); con.setRequestProperty("User-Agent", "Uxi-amarelo"); if (con.getResponseCode() != HttpServletResponse.SC_OK) throw new IOException("HTTP = " + con.getResponseCode()); String conteudo = null; try (InputStream is = con.getInputStream()) { conteudo = IOUtils.toString(is); } con.disconnect(); return Response.status(Status.OK).type(MediaType.TEXT_HTML + "; charset=UTF-8").entity(conteudo) .build(); } else if (comando.startsWith("html")) { return Response.status(Status.OK).type(MediaType.TEXT_HTML + "; charset=UTF-8") .entity(Util.obterStringDeJSON("html", comando, resultado)).build(); } else { throw new IllegalArgumentException(comando); } } catch (Exception e) { return respostaERRO(e); } }
From source file:fr.ortolang.diffusion.api.content.ContentResource.java
private Response export(boolean connected, String followSymlink, String filename, String format, List<String> paths, String regex, SecurityContext securityContext) throws UnsupportedEncodingException { if (connected && securityContext.getUserPrincipal() == null) { LOGGER.log(Level.FINE, "user is not authenticated, redirecting to authentication"); Map<String, Object> params = new HashMap<>(); params.put("followSymlink", followSymlink); params.put("filename", filename); params.put("format", format); params.put("path", paths); params.put("regex", regex); String id = UUID.randomUUID().toString(); exportations.put(id, params);//from w w w.jav a 2 s. c o m String redirect = "/content/exportations/" + id; String encodedRedirect = Base64.getUrlEncoder().encodeToString(redirect.getBytes()); NewCookie rcookie = new NewCookie(AuthResource.REDIRECT_PATH_PARAM_NAME, encodedRedirect, OrtolangConfig.getInstance().getProperty(OrtolangConfig.Property.API_CONTEXT), uriInfo.getBaseUri().getHost(), 1, "Redirect path after authentication", 300, new Date(System.currentTimeMillis() + 300000), false, false); UriBuilder builder = UriBuilder.fromResource(ContentResource.class); builder.queryParam("followsymlink", followSymlink).queryParam("filename", filename) .queryParam("format", format).queryParam("path", paths); return Response .seeOther(uriInfo.getBaseUriBuilder().path(AuthResource.class) .queryParam(AuthResource.REDIRECT_PATH_PARAM_NAME, encodedRedirect).build()) .cookie(rcookie).build(); } Pattern pattern = null; if (regex != null) { pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); } ResponseBuilder builder = handleExport(false, filename, format, paths, pattern); return builder.build(); }
From source file:com.joseflavio.uxiamarelo.servlet.UxiAmareloServlet.java
@Override protected void doPost(HttpServletRequest requisicao, HttpServletResponse resposta) throws ServletException, IOException { String tipo = requisicao.getContentType(); if (tipo == null || tipo.isEmpty()) tipo = "text/plain"; String codificacao = requisicao.getCharacterEncoding(); if (codificacao == null || codificacao.isEmpty()) codificacao = "UTF-8"; resposta.setCharacterEncoding(codificacao); PrintWriter saida = resposta.getWriter(); try {//from w w w.jav a 2 s.co m JSON json; if (tipo.contains("json")) { json = new JSON(IOUtils.toString(requisicao.getInputStream(), codificacao)); } else { json = new JSON(); } Enumeration<String> parametros = requisicao.getParameterNames(); while (parametros.hasMoreElements()) { String chave = parametros.nextElement(); String valor = URLDecoder.decode(requisicao.getParameter(chave), codificacao); json.put(chave, valor); } if (tipo.contains("multipart")) { Collection<Part> arquivos = requisicao.getParts(); if (!arquivos.isEmpty()) { File diretorio = new File(uxiAmarelo.getDiretorio()); if (!diretorio.isAbsolute()) { diretorio = new File(requisicao.getServletContext().getRealPath("") + File.separator + uxiAmarelo.getDiretorio()); } if (!diretorio.exists()) diretorio.mkdirs(); String diretorioStr = diretorio.getAbsolutePath(); String url = uxiAmarelo.getDiretorioURL(); if (uxiAmarelo.isDiretorioURLRelativo()) { String url_esquema = requisicao.getScheme(); String url_servidor = requisicao.getServerName(); int url_porta = requisicao.getServerPort(); String url_contexto = requisicao.getContextPath(); url = url_esquema + "://" + url_servidor + ":" + url_porta + url_contexto + "/" + url; } if (url.charAt(url.length() - 1) == '/') { url = url.substring(0, url.length() - 1); } Map<String, List<JSON>> mapa_arquivos = new HashMap<>(); for (Part arquivo : arquivos) { String chave = arquivo.getName(); String nome_original = getNome(arquivo, codificacao); String nome = nome_original; if (nome == null || nome.isEmpty()) { try (InputStream is = arquivo.getInputStream()) { String valor = IOUtils.toString(is, codificacao); valor = URLDecoder.decode(valor, codificacao); json.put(chave, valor); continue; } } if (uxiAmarelo.getArquivoNome().equals("uuid")) { nome = UUID.randomUUID().toString(); } while (new File(diretorioStr + File.separator + nome).exists()) { nome = UUID.randomUUID().toString(); } arquivo.write(diretorioStr + File.separator + nome); List<JSON> lista = mapa_arquivos.get(chave); if (lista == null) { lista = new LinkedList<>(); mapa_arquivos.put(chave, lista); } lista.add((JSON) new JSON().put("nome", nome_original).put("endereco", url + "/" + nome)); } for (Entry<String, List<JSON>> entrada : mapa_arquivos.entrySet()) { List<JSON> lista = entrada.getValue(); if (lista.size() > 1) { json.put(entrada.getKey(), lista); } else { json.put(entrada.getKey(), lista.get(0)); } } } } String copaiba = (String) json.remove("copaiba"); if (StringUtil.tamanho(copaiba) == 0) { throw new IllegalArgumentException("copaiba = nome@classe@metodo"); } String[] copaibaParam = copaiba.split("@"); if (copaibaParam.length != 3) { throw new IllegalArgumentException("copaiba = nome@classe@metodo"); } String comando = (String) json.remove("uxicmd"); if (StringUtil.tamanho(comando) == 0) comando = null; if (uxiAmarelo.isCookieEnviar()) { Cookie[] cookies = requisicao.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { String nome = cookie.getName(); if (uxiAmarelo.cookieBloqueado(nome)) continue; if (!json.has(nome)) { try { json.put(nome, URLDecoder.decode(cookie.getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { json.put(nome, cookie.getValue()); } } } } } if (uxiAmarelo.isEncapsulamentoAutomatico()) { final String sepstr = uxiAmarelo.getEncapsulamentoSeparador(); final char sep0 = sepstr.charAt(0); for (String chave : new HashSet<>(json.keySet())) { if (chave.indexOf(sep0) == -1) continue; String[] caminho = chave.split(sepstr); if (caminho.length > 1) { Util.encapsular(caminho, json.remove(chave), json); } } } String resultado; if (comando == null) { try (CopaibaConexao cc = uxiAmarelo.conectarCopaiba(copaibaParam[0])) { resultado = cc.solicitar(copaibaParam[1], json.toString(), copaibaParam[2]); if (resultado == null) resultado = ""; } } else if (comando.equals("voltar")) { resultado = json.toString(); comando = null; } else { resultado = ""; } if (comando == null) { resposta.setStatus(HttpServletResponse.SC_OK); resposta.setContentType("application/json"); saida.write(resultado); } else if (comando.startsWith("redirecionar")) { resposta.sendRedirect(Util.obterStringDeJSON("redirecionar", comando, resultado)); } else if (comando.startsWith("base64")) { String url = comando.substring("base64.".length()); resposta.sendRedirect(url + Base64.getUrlEncoder().encodeToString(resultado.getBytes("UTF-8"))); } else if (comando.startsWith("html_url")) { HttpURLConnection con = (HttpURLConnection) new URL( Util.obterStringDeJSON("html_url", comando, resultado)).openConnection(); con.setRequestProperty("User-Agent", "Uxi-amarelo"); if (con.getResponseCode() != HttpServletResponse.SC_OK) throw new IOException("HTTP = " + con.getResponseCode()); resposta.setStatus(HttpServletResponse.SC_OK); resposta.setContentType("text/html"); try (InputStream is = con.getInputStream()) { saida.write(IOUtils.toString(is)); } con.disconnect(); } else if (comando.startsWith("html")) { resposta.setStatus(HttpServletResponse.SC_OK); resposta.setContentType("text/html"); saida.write(Util.obterStringDeJSON("html", comando, resultado)); } else { throw new IllegalArgumentException(comando); } } catch (Exception e) { resposta.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resposta.setContentType("application/json"); saida.write(Util.gerarRespostaErro(e).toString()); } saida.flush(); }
From source file:ch.rasc.edsutil.optimizer.WebResourceProcessor.java
private static String computeMD5andEncodeWithURLSafeBase64(final byte[] content) { try {/*www . j a v a 2 s. co m*/ MessageDigest md5Digest = MessageDigest.getInstance("MD5"); md5Digest.update(content); byte[] md5 = md5Digest.digest(); return Base64.getUrlEncoder().encodeToString(md5); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
From source file:fr.ortolang.diffusion.api.content.ContentResource.java
private Response redirectToAuth(String path, boolean login, Map<String, Object> params, SecurityContext securityContext) { if (securityContext.getUserPrincipal() == null || securityContext.getUserPrincipal().getName() .equals(MembershipService.UNAUTHENTIFIED_IDENTIFIER)) { if (login) { UriBuilder builder = UriBuilder.fromPath(path); for (Map.Entry<String, Object> param : params.entrySet()) { builder.queryParam(param.getKey(), param.getValue()); }// w ww .j a v a 2 s . com String redirect = builder.build().toString(); String encodedRedirect = Base64.getUrlEncoder().encodeToString(redirect.getBytes()); LOGGER.log(Level.FINE, "user is not authenticated, redirecting to authentication"); NewCookie rcookie = new NewCookie(AuthResource.REDIRECT_PATH_PARAM_NAME, encodedRedirect, OrtolangConfig.getInstance().getProperty(OrtolangConfig.Property.API_CONTEXT), uriInfo.getBaseUri().getHost(), 1, "Redirect path after authentication", 300, new Date(System.currentTimeMillis() + 300000), false, false); return Response .seeOther(uriInfo.getBaseUriBuilder().path(AuthResource.class) .queryParam(AuthResource.REDIRECT_PATH_PARAM_NAME, encodedRedirect).build()) .cookie(rcookie).build(); } else { LOGGER.log(Level.FINE, "user is not authenticated, but login redirect disabled"); return Response.status(Status.UNAUTHORIZED).entity("You are not authorized to access this content") .build(); } } else { LOGGER.log(Level.FINE, "user is already authenticated, access denied"); return Response.status(Status.UNAUTHORIZED).entity("You are not authorized to access this content") .build(); } }