List of usage examples for org.bouncycastle.util.io Streams pipeAll
public static void pipeAll(InputStream inStr, OutputStream outStr) throws IOException
From source file:alpha.offsync.security.OpenPGPSecurityUtility.java
License:Apache License
@Override public void decrypt(final OutputStream outputStream, final InputStream inputStream) { try {/* w w w. j a v a 2 s. co m*/ final File keyFile = this.secretKeyRing; final char[] passwd = this.secretKeyRingPassword; final InputStream in = PGPUtil.getDecoderStream(inputStream); try { final PGPObjectFactory pgpF = new PGPObjectFactory(in); PGPEncryptedDataList enc; final Object o = pgpF.nextObject(); if (o instanceof PGPEncryptedDataList) { enc = (PGPEncryptedDataList) o; } else { enc = (PGPEncryptedDataList) pgpF.nextObject(); } final Iterator it = enc.getEncryptedDataObjects(); PGPPrivateKey sKey = null; PGPPublicKeyEncryptedData pbe = null; final PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream(new FileInputStream(keyFile))); while ((sKey == null) && it.hasNext()) { pbe = (PGPPublicKeyEncryptedData) it.next(); sKey = this.findSecretKey(pgpSec, pbe.getKeyID(), passwd); } if (sKey == null) throw new IllegalArgumentException("secret key for message not found."); final InputStream clear = pbe.getDataStream(new BcPublicKeyDataDecryptorFactory(sKey)); final PGPObjectFactory plainFact = new PGPObjectFactory(clear); final PGPCompressedData cData = (PGPCompressedData) plainFact.nextObject(); final InputStream compressedStream = new BufferedInputStream(cData.getDataStream()); final PGPObjectFactory pgpFact = new PGPObjectFactory(compressedStream); final Object message = pgpFact.nextObject(); if (message instanceof PGPLiteralData) { final PGPLiteralData ld = (PGPLiteralData) message; final InputStream unc = ld.getInputStream(); final OutputStream fOut = new BufferedOutputStream(outputStream); Streams.pipeAll(unc, fOut); fOut.close(); } else if (message instanceof PGPOnePassSignatureList) throw new PGPException("encrypted message contains a signed message - not literal data."); else throw new PGPException("message is not a simple encrypted file - type unknown."); } catch (final PGPException e) { System.err.println(e); if (e.getUnderlyingException() != null) { e.getUnderlyingException().printStackTrace(); } } } catch (final FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.goodvikings.cryptim.api.KeyRing.java
License:BEER-WARE LICENSE
public boolean decryptVerifyMessage(InputStream in, OutputStream out, String jid) throws IOException, PGPException, SignatureException { in = new ArmoredInputStream(in); PGPObjectFactory plainFact = new PGPObjectFactory( ((PGPPublicKeyEncryptedData) ((PGPEncryptedDataList) new PGPObjectFactory(in).nextObject()) .getEncryptedDataObjects().next()) .getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider(PROVIDER) .build(kp.getPrivateKey()))); PGPOnePassSignatureList onePassSignatureList = null; PGPSignatureList signatureList = null; PGPCompressedData compressedData = null; Object obj = plainFact.nextObject(); ByteArrayOutputStream actualOutput = new ByteArrayOutputStream(); while (obj != null) { if (obj instanceof PGPCompressedData) { compressedData = (PGPCompressedData) obj; plainFact = new PGPObjectFactory(compressedData.getDataStream()); obj = plainFact.nextObject(); }/*w w w . java 2s . co m*/ if (obj instanceof PGPLiteralData) { Streams.pipeAll(((PGPLiteralData) obj).getInputStream(), actualOutput); } else if (obj instanceof PGPOnePassSignatureList) { onePassSignatureList = (PGPOnePassSignatureList) obj; } else if (obj instanceof PGPSignatureList) { signatureList = (PGPSignatureList) obj; } else { throw new PGPException("message unknown message type."); } obj = plainFact.nextObject(); } actualOutput.close(); byte[] output = actualOutput.toByteArray(); PGPOnePassSignature ops = onePassSignatureList.get(0); ops.init(new JcaPGPContentVerifierBuilderProvider().setProvider(PROVIDER), keys.get(jid)); ops.update(output); out.write(output); out.flush(); out.close(); return ops.verify(signatureList.get(0)); }
From source file:com.netflix.priam.backup.AbstractRestore.java
License:Apache License
public void download(final AbstractBackupPath path, final OutputStream finalDestination, final File tempFile, final IFileCryptography fileCryptography, final char[] passPhrase, final ICompression compress) { if (config.getRestoreKeySpaces().size() != 0 && (!config.getRestoreKeySpaces().contains(path.keyspace) || path.keyspace.equals(SYSTEM_KEYSPACE))) return;/* ww w . jav a 2s. co m*/ count.incrementAndGet(); executor.submit(new RetryableCallable<Integer>() { @Override public Integer retriableCall() throws Exception { //== download object from source bucket try { logger.info("Downloading file from: " + path.getRemotePath() + " to: " + tempFile.getAbsolutePath()); fs.download(path, new FileOutputStream(tempFile), tempFile.getAbsolutePath()); tracker.adjustAndAdd(path); logger.info("Completed downloading file from: " + path.getRemotePath() + " to: " + tempFile.getAbsolutePath()); } catch (Exception ex) { //This behavior is retryable; therefore, lets get to a clean state before each retry. if (tempFile.exists()) { tempFile.createNewFile(); } throw new Exception("Exception downloading file from: " + path.getRemotePath() + " to: " + tempFile.getAbsolutePath(), ex); } //== object downloaded successfully from source, decrypt it. OutputStream fOut = null; //destination file after decryption File decryptedFile = new File(tempFile.getAbsolutePath() + ".decrypted"); try { InputStream in = new BufferedInputStream(new FileInputStream(tempFile.getAbsolutePath())); InputStream encryptedDataInputStream = fileCryptography.decryptStream(in, passPhrase, tempFile.getAbsolutePath()); fOut = new BufferedOutputStream(new FileOutputStream(decryptedFile)); Streams.pipeAll(encryptedDataInputStream, fOut); logger.info("completed decrypting file: " + tempFile.getAbsolutePath() + "to final file dest: " + decryptedFile.getAbsolutePath()); } catch (Exception ex) { //This behavior is retryable; therefore, lets get to a clean state before each retry. if (tempFile.exists()) { tempFile.createNewFile(); } if (decryptedFile.exists()) { decryptedFile.createNewFile(); } throw new Exception("Exception during decryption file: " + decryptedFile.getAbsolutePath(), ex); } finally { if (fOut != null) { fOut.close(); } } //== object downloaded and decrypted successfully, now uncompress it logger.info("Start uncompressing file: " + decryptedFile.getAbsolutePath() + " to the FINAL destination stream"); FileInputStream fileIs = null; InputStream is = null; try { fileIs = new FileInputStream(decryptedFile); is = new BufferedInputStream(fileIs); compress.decompressAndClose(is, finalDestination); } catch (Exception ex) { IOUtils.closeQuietly(is); throw new Exception("Exception uncompressing file: " + decryptedFile.getAbsolutePath() + " to the FINAL destination stream"); } logger.info("Completed uncompressing file: " + decryptedFile.getAbsolutePath() + " to the FINAL destination stream " + " current worker: " + Thread.currentThread().getName()); //if here, everything was successful for this object, lets remove unneeded file(s) if (tempFile.exists()) tempFile.delete(); if (decryptedFile.exists()) { decryptedFile.delete(); } //Note: removal of the tempFile is responsbility of the caller as this behavior did not create it. return count.decrementAndGet(); } }); }
From source file:com.simple.sftpfetch.decrypt.PGPFileDecrypter.java
License:Apache License
private void decryptFile(InputStream in, OutputStream outputStream) throws IOException, NoSuchProviderException { in = PGPUtil.getDecoderStream(in);/*www. j a va2s. c om*/ try { PGPEncryptedDataList enc = getEncryptedDataList(in); Iterator it = enc.getEncryptedDataObjects(); PGPPrivateKey sKey = null; PGPPublicKeyEncryptedData pbe = null; while (sKey == null && it.hasNext()) { pbe = (PGPPublicKeyEncryptedData) it.next(); sKey = getPrivateKey(sKey, pbe); } if (sKey == null) { throw new IllegalArgumentException("secret key for message not found."); } InputStream clear = pbe.getDataStream(sKey, "BC"); Object message = new PGPObjectFactory(clear).nextObject(); if (message instanceof PGPCompressedData) { PGPCompressedData cData = (PGPCompressedData) message; PGPObjectFactory pgpFact = new PGPObjectFactory(cData.getDataStream()); message = pgpFact.nextObject(); } if (message instanceof PGPLiteralData) { PGPLiteralData ld = (PGPLiteralData) message; Streams.pipeAll(ld.getInputStream(), outputStream); } else if (message instanceof PGPOnePassSignatureList) { throw new PGPException("encrypted message contains a signed message - not literal data."); } else { throw new PGPException("message is not a simple encrypted file - type unknown."); } if (pbe.isIntegrityProtected() && !pbe.verify()) { throw new PGPException("message failed integrity check"); } } catch (PGPException e) { System.err.println(e); if (e.getUnderlyingException() != null) { e.getUnderlyingException().printStackTrace(); } } }
From source file:gr.abiss.calipso.util.PgpUtils.java
License:Open Source License
/** * decrypt the passed in message stream// w w w .j a v a2 s .co m */ private static void decryptFile(InputStream in, InputStream keyIn, char[] passwd, String defaultFileName) throws IOException, NoSuchProviderException { in = PGPUtil.getDecoderStream(in); try { PGPObjectFactory pgpF = new PGPObjectFactory(in); PGPEncryptedDataList enc; Object o = pgpF.nextObject(); // // the first object might be a PGP marker packet. // if (o instanceof PGPEncryptedDataList) { enc = (PGPEncryptedDataList) o; } else { enc = (PGPEncryptedDataList) pgpF.nextObject(); } // // find the secret key // Iterator it = enc.getEncryptedDataObjects(); PGPPrivateKey sKey = null; PGPPublicKeyEncryptedData pbe = null; PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn)); while (sKey == null && it.hasNext()) { pbe = (PGPPublicKeyEncryptedData) it.next(); sKey = findSecretKey(pgpSec, pbe.getKeyID(), passwd); } if (sKey == null) { throw new IllegalArgumentException("secret key for message not found."); } InputStream clear = pbe.getDataStream(sKey, "BC"); PGPObjectFactory plainFact = new PGPObjectFactory(clear); Object message = plainFact.nextObject(); if (message instanceof PGPCompressedData) { PGPCompressedData cData = (PGPCompressedData) message; PGPObjectFactory pgpFact = new PGPObjectFactory(cData.getDataStream()); message = pgpFact.nextObject(); } if (message instanceof PGPLiteralData) { PGPLiteralData ld = (PGPLiteralData) message; String outFileName = ld.getFileName(); if (outFileName.length() == 0) { outFileName = defaultFileName; } InputStream unc = ld.getInputStream(); OutputStream fOut = new BufferedOutputStream(new FileOutputStream(outFileName)); Streams.pipeAll(unc, fOut); fOut.close(); } else if (message instanceof PGPOnePassSignatureList) { throw new PGPException("encrypted message contains a signed message - not literal data."); } else { throw new PGPException("message is not a simple encrypted file - type unknown."); } if (pbe.isIntegrityProtected()) { if (!pbe.verify()) { System.err.println("message failed integrity check"); } else { System.err.println("message integrity check passed"); } } else { System.err.println("no message integrity check"); } } catch (PGPException e) { System.err.println(e); if (e.getUnderlyingException() != null) { e.getUnderlyingException().printStackTrace(); } } }
From source file:hh.learnj.test.license.test.lincense3j.KeyBasedFileProcessor.java
/** * decrypt the passed in message stream// w ww . j a v a 2 s. c om */ private static void decryptFile(InputStream in, InputStream keyIn, char[] passwd, String defaultFileName) throws IOException, NoSuchProviderException { in = PGPUtil.getDecoderStream(in); try { JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(in); PGPEncryptedDataList enc; Object o = pgpF.nextObject(); // // the first object might be a PGP marker packet. // if (o instanceof PGPEncryptedDataList) { enc = (PGPEncryptedDataList) o; } else { enc = (PGPEncryptedDataList) pgpF.nextObject(); } // // find the secret key // Iterator it = enc.getEncryptedDataObjects(); PGPPrivateKey sKey = null; PGPPublicKeyEncryptedData pbe = null; PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn), new JcaKeyFingerprintCalculator()); while (sKey == null && it.hasNext()) { pbe = (PGPPublicKeyEncryptedData) it.next(); sKey = MyPGPUtil.findSecretKey(pgpSec, pbe.getKeyID(), passwd); } if (sKey == null) { throw new IllegalArgumentException("secret key for message not found."); } InputStream clear = pbe .getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(sKey)); JcaPGPObjectFactory plainFact = new JcaPGPObjectFactory(clear); Object message = plainFact.nextObject(); if (message instanceof PGPCompressedData) { PGPCompressedData cData = (PGPCompressedData) message; JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(cData.getDataStream()); message = pgpFact.nextObject(); } if (message instanceof PGPLiteralData) { PGPLiteralData ld = (PGPLiteralData) message; String outFileName = ld.getFileName(); if (outFileName.length() == 0) { outFileName = defaultFileName; } else { /** * modify 20160520 set fileName ???????? */ String separator = ""; if (outFileName.contains("/")) { separator = "/"; } else if (outFileName.contains("\\")) { separator = "\\"; } String fileName = outFileName.substring(outFileName.lastIndexOf(separator) + 1); // String defseparator = ""; if (defaultFileName.contains("/")) { defseparator = "/"; } else if (defaultFileName.contains("\\")) { defseparator = "\\"; } defaultFileName = defaultFileName.substring(0, defaultFileName.lastIndexOf(defseparator)); outFileName = defaultFileName + File.separator + fileName; } InputStream unc = ld.getInputStream(); OutputStream fOut = new BufferedOutputStream(new FileOutputStream(outFileName)); Streams.pipeAll(unc, fOut); fOut.close(); } else if (message instanceof PGPOnePassSignatureList) { throw new PGPException("encrypted message contains a signed message - not literal data."); } else { throw new PGPException("message is not a simple encrypted file - type unknown."); } if (pbe.isIntegrityProtected()) { if (!pbe.verify()) { System.err.println("message failed integrity check"); } else { System.err.println("message integrity check passed"); } } else { System.err.println("no message integrity check"); } } catch (PGPException e) { System.err.println(e); if (e.getUnderlyingException() != null) { e.getUnderlyingException().printStackTrace(); } } }
From source file:it.trento.comune.j4sign.examples.TsdTest.java
License:Open Source License
public boolean validate(String outPath) { boolean timestampValid = false; DigestCalculatorProvider digestCalculatorProvider = new BcDigestCalculatorProvider(); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); System.out.println("Validating TSD ..."); try {/*from www. jav a 2s. c o m*/ Streams.pipeAll(cmsTimeStampedData.getContent(), bOut); DigestCalculator imprintCalculator = cmsTimeStampedData .getMessageImprintDigestCalculator(digestCalculatorProvider); Streams.pipeAll(new ByteArrayInputStream(bOut.toByteArray()), imprintCalculator.getOutputStream()); cmsTimeStampedData.validate(digestCalculatorProvider, imprintCalculator.getDigest()); timestampValid = true; System.out.println("Timestamp validated."); System.out.println("Writing extracted data to file: " + outPath); FileOutputStream fos = new FileOutputStream(outPath); fos.write(bOut.toByteArray()); } catch (IOException e) { System.out.println("IOException: " + e.getMessage()); } catch (OperatorCreationException e) { System.out.println("OperatorCreationException: " + e.getMessage()); } catch (ImprintDigestInvalidException e) { System.out.println("ImprintDigestInvalidException: " + e.getMessage()); } catch (CMSException e) { System.out.println("CMSException: " + e.getMessage()); } return timestampValid; }
From source file:org.cryptacular.io.DecodingInputStreamTest.java
License:Open Source License
@Test(dataProvider = "plaintext-files") public void testDecode(final String path) throws Exception { final String expected = StreamUtil.readAll(StreamUtil.makeReader(new File(path))); final File file = new File(path + ".b64"); final DecodingInputStream input = DecodingInputStream.base64(StreamUtil.makeStream(file)); final ByteArrayOutputStream output = new ByteArrayOutputStream(expected.length()); try {/* www .j a va 2 s. c o m*/ Streams.pipeAll(input, output); } finally { StreamUtil.closeStream(input); StreamUtil.closeStream(output); } assertEquals(ByteUtil.toString(output.toByteArray()), expected); }
From source file:org.cryptacular.io.EncodingOutputStreamTest.java
License:Open Source License
@Test(dataProvider = "plaintext-files") public void testEncode(final String path) throws Exception { final File file = new File(path); String expectedPath = path + ".b64"; if ("\r\n".equals(System.lineSeparator())) { expectedPath += ".crlf"; }/*from w w w . j a v a 2s.c om*/ final String expected = new String(StreamUtil.readAll(expectedPath)); final ByteArrayOutputStream bufOut = new ByteArrayOutputStream((int) file.length() * 4 / 3); final EncodingOutputStream output = EncodingOutputStream.base64(bufOut, 64); try { Streams.pipeAll(StreamUtil.makeStream(file), output); } finally { StreamUtil.closeStream(output); } assertEquals(ByteUtil.toString(bufOut.toByteArray()), expected); }
From source file:org.cryptacular.pbe.AbstractEncryptionScheme.java
License:Open Source License
@Override public void encrypt(final InputStream in, final OutputStream out) throws IOException { cipher.init(true, parameters);/*from w w w .ja v a 2s .c om*/ Streams.pipeAll(in, new CipherOutputStream(out, cipher)); }