List of usage examples for java.util.zip DeflaterOutputStream flush
public void flush() throws IOException
From source file:com.barrybecker4.common.util.Base64Codec.java
/** * take a String and compress it./*w w w. j ava 2s .c om*/ * See @decompress for reversing the compression. * @param data a string to compress. * @return compressed string representation. */ public static synchronized String compress(final String data) { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(512); Deflater deflater = new Deflater(); DeflaterOutputStream oStream = new DeflaterOutputStream(byteOut, deflater); try { oStream.write(data.getBytes(CONVERTER_UTF8)); oStream.flush(); oStream.close(); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("Unsupported encoding exception :" + e.getMessage(), e); } catch (IOException e) { throw new IllegalStateException("io error :" + e.getMessage(), e); } return new String(Base64.encodeBase64(byteOut.toByteArray())); }
From source file:com.tremolosecurity.unison.u2f.util.U2fUtil.java
public static String encode(List<SecurityKeyData> devices, String encyrptionKeyName) throws Exception { ArrayList<KeyHolder> keys = new ArrayList<KeyHolder>(); for (SecurityKeyData dr : devices) { KeyHolder kh = new KeyHolder(); kh.setCounter(dr.getCounter());//from w w w . ja v a 2s .com kh.setEnrollmentTime(dr.getEnrollmentTime()); kh.setKeyHandle(dr.getKeyHandle()); kh.setPublicKey(dr.getPublicKey()); kh.setTransports(dr.getTransports()); keys.add(kh); } String json = gson.toJson(keys); EncryptedMessage msg = new EncryptedMessage(); SecretKey key = GlobalEntries.getGlobalEntries().getConfigManager().getSecretKey(encyrptionKeyName); if (key == null) { throw new Exception("Queue message encryption key not found"); } Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); msg.setMsg(cipher.doFinal(json.getBytes("UTF-8"))); msg.setIv(cipher.getIV()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DeflaterOutputStream compressor = new DeflaterOutputStream(baos, new Deflater(Deflater.BEST_COMPRESSION, true)); compressor.write(gson.toJson(msg).getBytes("UTF-8")); compressor.flush(); compressor.close(); String b64 = new String(Base64.encodeBase64(baos.toByteArray())); return b64; }
From source file:ZipUtil.java
public static void zipFileToFile(File flSource, File flTarget) throws IOException { Deflater oDeflate = new Deflater(Deflater.DEFLATED, false); FileInputStream stmFileIn = new FileInputStream(flSource); FileOutputStream stmFileOut = new FileOutputStream(flTarget); DeflaterOutputStream stmDeflateOut = new DeflaterOutputStream(stmFileOut, oDeflate); try {// ww w . j a v a2 s .com // FileUtil.inputStreamToOutputStream(stmFileIn, stmDeflateOut); } //end try finally { stmDeflateOut.finish(); stmDeflateOut.flush(); stmDeflateOut.close(); stmFileOut.close(); stmFileIn.close(); } }
From source file:com.uber.hoodie.common.HoodieJsonPayload.java
private byte[] compressData(String jsonData) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION); DeflaterOutputStream dos = new DeflaterOutputStream(baos, deflater, true); try {/*from w w w. jav a2s . com*/ dos.write(jsonData.getBytes()); } finally { dos.flush(); dos.close(); // Its important to call this. // Deflater takes off-heap native memory and does not release until GC kicks in deflater.end(); } return baos.toByteArray(); }
From source file:com.uber.hoodie.common.TestRawTripPayload.java
private byte[] compressData(String jsonData) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DeflaterOutputStream dos = new DeflaterOutputStream(baos, new Deflater(Deflater.BEST_COMPRESSION), true); try {/*from w ww. ja v a2 s.co m*/ dos.write(jsonData.getBytes()); } finally { dos.flush(); dos.close(); } return baos.toByteArray(); }
From source file:com.tremolosecurity.proxy.auth.saml2.Saml2SingleLogout.java
@Override public void handleLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException { if (request == null || response == null) { //do nothing return;/* w w w . j av a 2 s. c o m*/ } String xmlAlg = SAML2Auth.xmlDigSigAlgs.get(digSigAlg); if (xmlAlg == null) { throw new ServletException("Unknown Signiture algorithm : '" + digSigAlg + "'"); } String javaAlg = SAML2Auth.javaDigSigAlgs.get(digSigAlg); UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG); ConfigManager cfgMgr = holder.getConfig(); LogoutRequestBuilder lrb = new LogoutRequestBuilder(); LogoutRequest lr = lrb.buildObject(); DateTime dt = new DateTime(); lr.setIssueInstant(dt); lr.setDestination(logoutURL); byte[] idBytes = new byte[20]; random.nextBytes(idBytes); String id = "f" + Hex.encodeHexString(idBytes); lr.setID(id); IssuerBuilder ib = new IssuerBuilder(); Issuer issuer = ib.buildObject(); issuer.setValue(assertionConsumerServiceURL); lr.setIssuer(issuer); NameIDBuilder nidbpb = new NameIDBuilder(); NameID nid = nidbpb.buildObject(); //nidp.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified"); nid.setFormat(nameIDFormat); //nid.setSPNameQualifier(assertionConsumerServiceURL); nid.setValue(nameID); lr.setNameID(nid); SessionIndexBuilder sib = new SessionIndexBuilder(); SessionIndex si = sib.buildObject(); si.setSessionIndex(sessionIndex); lr.getSessionIndexes().add(si); try { // Get the Subject marshaller Marshaller marshaller = new LogoutRequestMarshaller(); // Marshall the Subject //Element assertionElement = marshaller.marshall(lr); String xml = OpenSAMLUtils.xml2str(lr); xml = xml.substring(xml.indexOf("?>") + 2); if (logger.isDebugEnabled()) { logger.debug("=======AuthnRequest============"); logger.debug(xml); logger.debug("=======AuthnRequest============"); } byte[] bxml = xml.getBytes("UTF-8"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DeflaterOutputStream compressor = new DeflaterOutputStream(baos, new Deflater(Deflater.BEST_COMPRESSION, true)); compressor.write(bxml); compressor.flush(); compressor.close(); String b64 = new String(Base64.encodeBase64(baos.toByteArray())); StringBuffer redirURL = new StringBuffer(); StringBuffer query = new StringBuffer(); idBytes = new byte[20]; random.nextBytes(idBytes); query.append("SAMLRequest=").append(URLEncoder.encode(b64, "UTF-8")).append("&RelayState=") .append(URLEncoder.encode(Hex.encodeHexString(idBytes), "UTF-8")); query.append("&SigAlg=").append(URLEncoder.encode(xmlAlg, "UTF-8")); //http://www.w3.org/2000/09/xmldsig#rsa-sha1 java.security.Signature signer = java.security.Signature.getInstance(javaAlg); PrivateKey sigKey = cfgMgr.getPrivateKey(signingKeyAlias); if (sigKey == null) { throw new ServletException("Signing Key : '" + signingKeyAlias + "' not found"); } signer.initSign(sigKey); signer.update(query.toString().getBytes("UTF-8")); String base64Sig = new String(Base64.encodeBase64(signer.sign())); query.append("&Signature=").append(URLEncoder.encode(base64Sig, "UTF-8")); redirURL.append(logoutURL).append("?").append(query.toString()); if (logger.isDebugEnabled()) { logger.debug("Logout URL : '" + redirURL.toString() + "'"); } //((ProxyResponse) response).removeHeader("Location"); response.sendRedirect(redirURL.toString()); } catch (Exception e) { throw new ServletException("Could not generate logout request", e); } }
From source file:com.tremolosecurity.idp.providers.OpenIDConnectIdP.java
private String encryptToken(String codeTokenKeyName, Gson gson, UUID refreshToken) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException { byte[] bjson = refreshToken.toString().getBytes("UTF-8"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, GlobalEntries.getGlobalEntries().getConfigManager().getSecretKey(codeTokenKeyName)); byte[] encJson = cipher.doFinal(bjson); String base64d = new String(org.bouncycastle.util.encoders.Base64.encode(encJson)); Token token = new Token(); token.setEncryptedRequest(base64d);/*from www. j a v a 2 s. c o m*/ token.setIv(new String(org.bouncycastle.util.encoders.Base64.encode(cipher.getIV()))); byte[] bxml = gson.toJson(token).getBytes("UTF-8"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DeflaterOutputStream compressor = new DeflaterOutputStream(baos, new Deflater(Deflater.BEST_COMPRESSION, true)); compressor.write(bxml); compressor.flush(); compressor.close(); String b64 = new String(org.bouncycastle.util.encoders.Base64.encode(baos.toByteArray())); return b64; }
From source file:com.tremolosecurity.proxy.auth.SAML2Auth.java
public void initializeSSO(HttpServletRequest req, HttpServletResponse resp, HttpSession session, boolean isJump, String jumpPage) throws MalformedURLException, ServletException { {/* www .j av a 2 s . c o m*/ RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder(); HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session .getAttribute(ProxyConstants.AUTH_MECH_PARAMS); boolean isMultiIdp = authParams.get("isMultiIdP") != null && authParams.get("isMultiIdP").getValues().get(0).equalsIgnoreCase("true"); String postAuthnReqTo = ""; String redirAuthnReqTo = ""; String assertionConsumerServiceURL = ""; boolean signAuthnReq = false; String uri = (String) req.getAttribute(ProxyConstants.AUTH_REDIR_URI); if (uri == null) { uri = req.getRequestURI(); } if (isMultiIdp) { URL url = new URL(req.getRequestURL().toString()); String hostName = url.getHost(); String dn = authParams.get("idpDir").getValues().get(0); try { StringBuffer b = new StringBuffer(); LDAPSearchResults res = cfgMgr.getMyVD().search(dn, 2, equal("hostname", hostName).toString(), new ArrayList<String>()); if (!res.hasMore()) { throw new ServletException("No IdP found"); } LDAPEntry entry = res.next(); postAuthnReqTo = entry.getAttribute("idpURL").getStringValue(); redirAuthnReqTo = entry.getAttribute("idpRedirURL").getStringValue(); assertionConsumerServiceURL = ProxyTools.getInstance().getFqdnUrl(uri, req); signAuthnReq = entry.getAttribute("signAuthnReq").getStringValue().equalsIgnoreCase("1"); } catch (LDAPException e) { throw new ServletException("Could not load IdP data", e); } } else { postAuthnReqTo = authParams.get("idpURL").getValues().get(0);// "http://idp.partner.domain.com:8080/opensso/SSOPOST/metaAlias/testSaml2Idp"; redirAuthnReqTo = authParams.get("idpRedirURL").getValues().get(0); assertionConsumerServiceURL = ProxyTools.getInstance().getFqdnUrl(uri, req);// "http://sp.localdomain.com:8080/SampleSP/echo"; if (authParams.get("forceToSSL") != null && authParams.get("forceToSSL").getValues().get(0).equalsIgnoreCase("true")) { if (!assertionConsumerServiceURL.startsWith("https")) { assertionConsumerServiceURL = assertionConsumerServiceURL.replace("http://", "https://"); } } signAuthnReq = authParams.get("signAuthnReq") != null && authParams.get("signAuthnReq").getValues().get(0).equalsIgnoreCase("true"); } ConfigManager cfg = (ConfigManager) req.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ); AuthnRequestBuilder authnBuilder = new AuthnRequestBuilder(); AuthnRequest authn = authnBuilder.buildObject(); authn.setAssertionConsumerServiceURL(assertionConsumerServiceURL); authn.setProtocolBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"); //authn.setDestination(postAuthnReqTo); authn.setDestination(redirAuthnReqTo); DateTime dt = new DateTime(); String authMechanism = authParams.get("authCtxRef").getValues().get(0); byte[] idBytes = new byte[20]; random.nextBytes(idBytes); /*StringBuffer id = new StringBuffer(); for (byte b : idBytes) { id.append(Hex.encode(idBytes)); }*/ StringBuffer b = new StringBuffer(); b.append('f').append(Hex.encodeHexString(idBytes)); String id = b.toString(); authn.setIssueInstant(dt); //authn.setID(Long.toString(random.nextLong())); authn.setID(id.toString()); session.setAttribute("AUTOIDM_SAML2_REQUEST", authn.getID()); IssuerBuilder ib = new IssuerBuilder(); Issuer issuer = ib.buildObject(); issuer.setValue(assertionConsumerServiceURL); authn.setIssuer(issuer); //authn.setAssertionConsumerServiceIndex(0); //authn.setAttributeConsumingServiceIndex(0); NameIDPolicyBuilder nidbpb = new NameIDPolicyBuilder(); NameIDPolicy nidp = nidbpb.buildObject(); //nidp.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified"); nidp.setFormat("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"); nidp.setAllowCreate(true); nidp.setSPNameQualifier(assertionConsumerServiceURL); //authn.setNameIDPolicy(nidp); authn.setIsPassive(false); //authn.setProviderName("tremolosecurity.com"); if (!authMechanism.isEmpty() && !authMechanism.equalsIgnoreCase("none")) { AuthnContextClassRefBuilder accrb = new AuthnContextClassRefBuilder(); AuthnContextClassRef accr = accrb.buildObject(); accr.setAuthnContextClassRef(authMechanism); //accr.setAuthnContextClassRef("urn:federation:authentication:windows"); //accr.setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"); RequestedAuthnContextBuilder racb = new RequestedAuthnContextBuilder(); RequestedAuthnContext rac = racb.buildObject(); rac.getAuthnContextClassRefs().add(accr); rac.setComparison(AuthnContextComparisonTypeEnumeration.EXACT); authn.setRequestedAuthnContext(rac); } authn.setForceAuthn(false); try { // Get the Subject marshaller Marshaller marshaller = new AuthnRequestMarshaller(); // Marshall the Subject //Element assertionElement = marshaller.marshall(authn); String xml = OpenSAMLUtils.xml2str(authn); xml = xml.substring(xml.indexOf("?>") + 2); if (logger.isDebugEnabled()) { logger.debug("=======AuthnRequest============"); logger.debug(xml); logger.debug("=======AuthnRequest============"); } byte[] bxml = xml.getBytes("UTF-8"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DeflaterOutputStream compressor = new DeflaterOutputStream(baos, new Deflater(Deflater.BEST_COMPRESSION, true)); compressor.write(bxml); compressor.flush(); compressor.close(); String b64 = new String(Base64.encodeBase64(baos.toByteArray())); StringBuffer redirURL = new StringBuffer(); StringBuffer query = new StringBuffer(); idBytes = new byte[20]; random.nextBytes(idBytes); query.append("SAMLRequest=").append(URLEncoder.encode(b64, "UTF-8")).append("&RelayState=") .append(URLEncoder.encode(Hex.encodeHexString(idBytes), "UTF-8")); if (signAuthnReq) { String sigAlg = authParams.get("sigAlg") != null ? authParams.get("sigAlg").getValues().get(0) : "RSA-SHA1"; String xmlSigAlg = SAML2Auth.xmlDigSigAlgs.get(sigAlg); String javaSigAlg = SAML2Auth.javaDigSigAlgs.get(sigAlg); //sb.append("SAMLRequest=").append(xml).append("&SigAlg=").append(URLEncoder.encode("http://www.w3.org/2000/09/xmldsig#rsa-sha1", "UTF-8")); query.append("&SigAlg=").append(URLEncoder.encode(xmlSigAlg, "UTF-8")); java.security.Signature signer = java.security.Signature.getInstance(javaSigAlg); if (authParams.get("spSigKey") == null) { throw new ServletException("No signature certificate specified"); } String spSigKey = authParams.get("spSigKey").getValues().get(0); signer.initSign(cfgMgr.getPrivateKey(spSigKey)); signer.update(query.toString().getBytes("UTF-8")); String base64Sig = new String(Base64.encodeBase64(signer.sign())); query.append("&Signature=").append(URLEncoder.encode(base64Sig, "UTF-8")); } redirURL.append(redirAuthnReqTo).append("?").append(query.toString()); if (isJump) { if (logger.isDebugEnabled()) { logger.debug("Redirecting to Jump Page"); logger.debug("SAML2_JUMPPAGE='" + req.getAttribute("TREMOLO_AUTH_REDIR_URI")); } session.setAttribute("SAML2_JUMPPAGE", redirURL.toString()); resp.sendRedirect(jumpPage); } else { resp.sendRedirect(redirURL.toString()); } /*String b64 = new String( org.apache.directory.shared.ldap.util.Base64 .encode(bxml)); req.setAttribute("postaction", postAuthnReqTo); req.setAttribute("postdata", b64); req.getRequestDispatcher("/auth/fed/postauthnreq.jsp").forward( req, resp);*/ } catch (Exception e) { throw new ServletException("Error generating new authn request", e); } } }
From source file:com.tremolosecurity.idp.providers.OpenIDConnectIdP.java
private void postResponse(OpenIDConnectTransaction transaction, HttpServletRequest request, HttpServletResponse response, AuthInfo authInfo, UrlHolder holder) throws Exception { //first generate a lastmile token OpenIDConnectTrust trust = trusts.get(transaction.getClientID()); ConfigManager cfgMgr = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ); DateTime now = new DateTime(); DateTime notBefore = now.minus(trust.getCodeTokenTimeToLive()); DateTime notAfter = now.plus(trust.getCodeTokenTimeToLive()); com.tremolosecurity.lastmile.LastMile lmreq = new com.tremolosecurity.lastmile.LastMile( request.getRequestURI(), notBefore, notAfter, authInfo.getAuthLevel(), authInfo.getAuthMethod()); lmreq.getAttributes().add(new Attribute("dn", authInfo.getUserDN())); Attribute attr = new Attribute("scope"); attr.getValues().addAll(transaction.getScope()); lmreq.getAttributes().add(attr);/*from www.j a v a 2 s. c om*/ if (transaction.getNonce() != null) { lmreq.getAttributes().add(new Attribute("nonce", transaction.getNonce())); } SecretKey key = cfgMgr.getSecretKey(trust.getCodeLastmileKeyName()); String codeToken = lmreq.generateLastMileToken(key); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DeflaterOutputStream compressor = new DeflaterOutputStream(baos, new Deflater(Deflater.BEST_COMPRESSION, true)); compressor.write(org.bouncycastle.util.encoders.Base64.decode(codeToken.getBytes("UTF-8"))); compressor.flush(); compressor.close(); String b64 = new String(org.bouncycastle.util.encoders.Base64.encode(baos.toByteArray())); StringBuffer b = new StringBuffer(); b.append(transaction.getRedirectURI()).append("?").append("code=").append(URLEncoder.encode(b64, "UTF-8")) .append("&state=").append(URLEncoder.encode(transaction.getState(), "UTF-8")); response.sendRedirect(b.toString()); }
From source file:org.apache.flex.swf.io.SWFWriter.java
/** * This method does not close the {@code output} stream. *///from w w w . j a v a2 s . c o m @Override public void writeTo(OutputStream output) { assert output != null; writtenTags = new HashSet<ITag>(); // The SWF data after the first 8 bytes can be compressed. At this // moment, we only encode the "compressible" part. writeCompressibleHeader(); // FileAttributes must be the first tag. writeTag(SWF.getFileAttributes(swf)); // Raw Metadata String metadata = swf.getMetadata(); if (metadata != null) writeTag(new MetadataTag(metadata)); // SetBackgroundColor tag final RGB backgroundColor = swf.getBackgroundColor(); if (backgroundColor != null) writeTag(new SetBackgroundColorTag(backgroundColor)); // EnableDebugger2 tag if (enableDebug) writeTag(new EnableDebugger2Tag("NO-PASSWORD")); // ProductInfo tag for Flex compatibility ProductInfoTag productInfo = swf.getProductInfo(); if (productInfo != null) writeTag(productInfo); // ScriptLimits tag final ScriptLimitsTag scriptLimitsTag = swf.getScriptLimits(); if (scriptLimitsTag != null) writeTag(scriptLimitsTag); // Frames and enclosed tags. writeFrames(); // End of SWF writeTag(new EndTag()); writtenTags = null; // Compute the size of the SWF file. long length = outputBuffer.size() + 8; try { // write the first 8 bytes switch (useCompression) { case LZMA: output.write('Z'); break; case ZLIB: output.write('C'); break; case NONE: output.write('F'); break; default: assert false; } output.write('W'); output.write('S'); output.write(swf.getVersion()); writeInt(output, (int) length); // write the "compressible" part switch (useCompression) { case LZMA: { LZMACompressor compressor = new LZMACompressor(); compressor.compress(outputBuffer); // now write the compressed length final long compressedLength = compressor.getLengthOfCompressedPayload(); assert compressedLength <= 0xffffffffl; writeInt(output, (int) compressedLength); // now write the LZMA props compressor.writeLZMAProperties(output); // Normally LZMA (7zip) would write an 8 byte length here, but we don't, because the // SWF header already has this info // now write the n bytes of LZMA data, followed by the 6 byte EOF compressor.writeDataAndEnd(output); output.flush(); } break; case ZLIB: { int compressionLevel = enableDebug ? Deflater.BEST_SPEED : Deflater.BEST_COMPRESSION; Deflater deflater = new Deflater(compressionLevel); DeflaterOutputStream deflaterStream = new DeflaterOutputStream(output, deflater); deflaterStream.write(outputBuffer.getBytes(), 0, outputBuffer.size()); deflaterStream.finish(); deflater.end(); deflaterStream.flush(); break; } case NONE: { output.write(outputBuffer.getBytes(), 0, outputBuffer.size()); output.flush(); break; } default: assert false; } } catch (IOException e) { throw new RuntimeException(e); } }