List of usage examples for org.apache.commons.codec.binary Base64 encodeBase64String
public static String encodeBase64String(final byte[] binaryData)
From source file:com.twinsoft.convertigo.engine.AttachmentManager.java
public void addAttachment(final byte[] data, final String name, final String contentType, String referer, String url, Policy policy, String filename, Status status) { Element eAttachment = transaction.context.outputDocument.createElement("attachment"); eAttachment.setAttribute("type", "attachment"); eAttachment.setAttribute("name", name); eAttachment.setAttribute("content-type", contentType); if (referer != null) { eAttachment.setAttribute("referer", referer); }/*w w w . j a va 2 s .c om*/ if (url != null) { eAttachment.setAttribute("url", url); } eAttachment.setAttribute("content-length", "" + data.length); eAttachment.setAttribute("status", status.name()); if (status == Status.timeout) { policy = Policy.base64; } else if (policy == null) { policy = Policy.localfile_increment; } switch (policy) { case base64: eAttachment.setAttribute("encoding", "base64"); eAttachment.appendChild( transaction.context.outputDocument.createTextNode(Base64.encodeBase64String(data))); break; case localfile_override: case localfile_increment: default: if (filename == null || filename.length() == 0) { filename = ".//downloads/" + name; } String projectName = transaction.getProject().getName(); filename = Engine.theApp.filePropertyManager.getFilepathFromProperty(filename, projectName); File file = new File(filename); file.getParentFile().mkdirs(); if (policy == Policy.localfile_increment && file.exists()) { int cpt = 2; String leaf = file.getName(); while ((file = new File(file.getParentFile(), cpt + "_" + leaf)).exists()) { cpt++; } } synchronized (Engine.theApp.filePropertyManager.getMutex(file)) { try { FileOutputStream fileOut = new FileOutputStream(file); fileOut.write(data); fileOut.close(); } catch (IOException e) { Engine.logEngine.error("AttachmentComponent: cannot write attachment '" + name + "'", e); } finally { Engine.theApp.filePropertyManager.releaseMutex(file); } } String filepath = file.getAbsolutePath(); eAttachment.setAttribute("local-url", filepath); String projectPath = Engine.PROJECTS_PATH + File.separator + projectName + File.separator; if (filepath.startsWith(projectPath)) { eAttachment.setAttribute("relative-url", filepath.substring(projectPath.length()).replaceAll("\\\\", "/")); } break; } transaction.context.outputDocument.getDocumentElement().appendChild(eAttachment); }
From source file:com.github.jinahya.codec.PercentBinaryDecoderProxyTest.java
@Test(invocationCount = 128) public void testDecode() throws Exception { final BinaryDecoder decoder = (BinaryDecoder) PercentBinaryDecoderProxy.newInstance(); try {// w ww. jav a2 s . c om decoder.decode((Object) null); Assert.fail("passed: decode((Object) null)"); } catch (NullPointerException npe) { // ok } try { decoder.decode((byte[]) null); Assert.fail("passed: decode((byte[]) null)"); } catch (NullPointerException npe) { // ok } final Random random = ThreadLocalRandom.current(); final byte[] expected = new byte[random.nextInt(128)]; random.nextBytes(expected); System.out.println("original ----------------------------------------"); System.out.println(Base64.encodeBase64String(expected)); final byte[] encoded = PercentEncoder.encodeMultiple(expected); System.out.println("encoded -----------------------------------------"); System.out.println(new String(encoded, "US-ASCII")); final byte[] actual = decoder.decode(encoded); System.out.println("decoded -----------------------------------------"); System.out.println(Base64.encodeBase64String(actual)); Assert.assertEquals(actual, expected); }
From source file:com.gvmax.common.util.Enc.java
public String encrypt(String valueToEnc) { if (!enabled) { return valueToEnc; }/*w w w. j ava2 s.c om*/ if (valueToEnc == null) { return null; } try { c.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv)); byte[] encValue = c.doFinal(valueToEnc.getBytes("UTF-8")); return Base64.encodeBase64String(encValue); } catch (Exception e) { logger.warn("Unable to encrypt: " + valueToEnc, e); return null; } }
From source file:eu.europa.esig.dss.pades.DigestStabilityTest.java
@Test public void testTwiceGetDataToSignReturnsSameDigest() throws Exception { DSSDocument toBeSigned = new FileDocument(new File("src/test/resources/sample.pdf")); CertificateService certificateService = new CertificateService(); DSSPrivateKeyEntry privateKeyEntry = certificateService .generateCertificateChain(SignatureAlgorithm.RSA_SHA256); Date signingDate = new Date(); ToBeSigned dataToSign1 = getDataToSign(toBeSigned, privateKeyEntry, signingDate); ToBeSigned dataToSign2 = getDataToSign(toBeSigned, privateKeyEntry, signingDate); final MessageDigest messageDigest = MessageDigest.getInstance(DigestAlgorithm.SHA256.getOid()); byte[] digest1 = messageDigest.digest(dataToSign1.getBytes()); byte[] digest2 = messageDigest.digest(dataToSign2.getBytes()); assertEquals(Base64.encodeBase64String(digest1), Base64.encodeBase64String(digest2)); }
From source file:localca.certstore.MockCertificateStorage.java
@Override public void setCert(String commonName, X509Certificate certificate) throws CertificateStorageException { if (!map.containsKey(commonName)) { throw new CertificateStorageException(CertificateStorageExceptionType.NOT_FOUND, commonName); }/*from ww w . j a v a2 s . c o m*/ if (map.get(commonName).getEncoded() != null) { throw new CertificateStorageException(CertificateStorageExceptionType.ALREADY_SET, commonName); } try { map.put(commonName, new StoredCertificate(commonName, Base64.encodeBase64String(certificate.getEncoded()))); } catch (CertificateEncodingException e) { throw new CertificateStorageException(e, CertificateStorageExceptionType.ENCODING_ERROR, commonName); } }
From source file:io.warp10.script.processing.Pencode.java
@Override public Object apply(WarpScriptStack stack) throws WarpScriptException { Object top = stack.pop();//from ww w .j a v a 2s. c o m if (!(top instanceof processing.core.PGraphics)) { throw new WarpScriptException(getName() + " operates on a PGraphics instance."); } processing.core.PGraphics pg = (processing.core.PGraphics) top; pg.endDraw(); BufferedImage bimage = new BufferedImage(pg.pixelWidth, pg.pixelHeight, BufferedImage.TYPE_INT_ARGB); bimage.setRGB(0, 0, pg.pixelWidth, pg.pixelHeight, pg.pixels, 0, pg.pixelWidth); Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("png"); ImageWriter writer = null; if (iter.hasNext()) { writer = iter.next(); } ImageWriteParam param = writer.getDefaultWriteParam(); IIOMetadata metadata = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream output = new BufferedOutputStream(baos); try { writer.setOutput(ImageIO.createImageOutputStream(output)); writer.write(metadata, new IIOImage(bimage, null, metadata), param); } catch (IOException ioe) { throw new WarpScriptException(getName() + " error while encoding PGraphics.", ioe); } writer.dispose(); StringBuilder sb = new StringBuilder("data:image/png;base64,"); sb.append(Base64.encodeBase64String(baos.toByteArray())); stack.push(sb.toString()); // // Re-issue a 'beginDraw' so we can continue using the PGraphics instance // pg.beginDraw(); return stack; }
From source file:li.poi.services.docx.resource.MailMerge.java
@Path("/merge") @PUT//w ww. j a v a 2 s . c o m @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public MailMergeResponse merge(MailMergeRequest request) { MailMergeResponse response = new MailMergeResponse(); File template = null; File output = null; try { MailMergeController controller = new MailMergeController(); template = File.createTempFile("template", ".docx"); FileUtils.writeByteArrayToFile(template, Base64.decodeBase64(request.getTemplate())); output = controller.getMergedDocument(template, request.getValues()); response.setDocument(Base64.encodeBase64String(IOUtils.toByteArray(new FileInputStream(output)))); } catch (IOException e) { response.setError(e.getMessage()); } finally { // delete the files if (template != null) { boolean deleted = template.delete(); if (!deleted) { log.warn("file not deleted " + template.getAbsolutePath()); } } if (output != null) { boolean deleted = output.delete(); if (!deleted) { log.warn("file not deleted " + output.getAbsolutePath()); } } } return response; }
From source file:com.vmware.o11n.plugin.crypto.service.CryptoRSAService.java
/** * RSA Encryption//w ww . j a v a 2s. c o m * * @param pemKey RSA Key (Public or Private, Public will be derived from Private) * @param dataB64 Data encoded with Base64 to encrypt * @return Encrypted data Base64 encoded * @throws IOException * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws InvalidKeyException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public String encrypt(String pemKey, String dataB64) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { String encryptedB64 = null; PublicKey publicKey = null; Key key = null; try { key = CryptoUtil.getKey(pemKey); //can be private or public } catch (IOException e) { //try to fix key: key = CryptoUtil.getKey(CryptoUtil.fixPemString(pemKey)); } if (key instanceof RSAPublicKey) { publicKey = (RSAPublicKey) key; } else if (key instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) key; publicKey = CryptoUtil.getPublicFromPrivate(privateKey); } else { throw new IllegalArgumentException("Unknown key object type: " + key.getClass().getName()); } Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, publicKey); encryptedB64 = Base64.encodeBase64String(cipher.doFinal(Base64.decodeBase64(dataB64))); return encryptedB64; }
From source file:com.twosigma.beaker.NamespaceClient.java
private void setup(String session) { this.session = session; String account = "beaker:" + System.getenv("beaker_core_password"); this.auth = "Basic " + Base64.encodeBase64String(account.getBytes()); this.urlBase = "http://127.0.0.1:" + System.getenv("beaker_core_port") + "/rest/namespace"; this.ctrlUrlBase = "http://127.0.0.1:" + System.getenv("beaker_core_port") + "/rest/notebookctrl"; this.easyFormUrl = "http://127.0.0.1:" + System.getenv("beaker_core_port") + "/rest/easyform"; this.utilUrl = "http://127.0.0.1:" + System.getenv("beaker_core_port") + "/rest/util"; oclasses = new Class<?>[4]; oclasses[0] = Object.class; oclasses[1] = Boolean.class; oclasses[2] = Integer.class; oclasses[3] = String.class; }
From source file:miage.ecom.web.admin.service.ImgurImageManager.java
private String getBase64String(InputStream is) throws IOException { return Base64.encodeBase64String(inputStreamToByteArray(is)); }