List of usage examples for org.bouncycastle.openpgp PGPObjectFactory nextObject
public Object nextObject() throws IOException
null if the end of stream is reached. From source file:alpha.offsync.security.OpenPGPSecurityUtility.java
License:Apache License
@Override public void decrypt(final OutputStream outputStream, final InputStream inputStream) { try {/* ww w .j av a 2 s. c om*/ 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:alpha.offsync.security.OpenPGPSecurityUtility.java
License:Apache License
@Override public void verify(OutputStream outputStream, final InputStream inputStream) { try {//from w w w . j av a2s .co m final File keyFile = this.publicKeyRing; final InputStream in = PGPUtil.getDecoderStream(inputStream); PGPObjectFactory pgpFact = new PGPObjectFactory(in); final PGPCompressedData c1 = (PGPCompressedData) pgpFact.nextObject(); pgpFact = new PGPObjectFactory(c1.getDataStream()); final PGPOnePassSignatureList p1 = (PGPOnePassSignatureList) pgpFact.nextObject(); final PGPOnePassSignature ops = p1.get(0); final PGPLiteralData p2 = (PGPLiteralData) pgpFact.nextObject(); final InputStream dIn = p2.getInputStream(); int ch; final PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream(new FileInputStream(keyFile))); final PGPPublicKey key = pgpRing.getPublicKey(ops.getKeyID()); ops.init(new BcPGPContentVerifierBuilderProvider(), key); while ((ch = dIn.read()) >= 0) { ops.update((byte) ch); outputStream.write(ch); } outputStream.close(); final PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject(); if (!ops.verify(p3.get(0))) { outputStream = null; } } catch (final FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final SignatureException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final PGPException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:bisq.desktop.main.overlays.windows.downloadupdate.BisqInstaller.java
License:Open Source License
/** * Verifies detached PGP signatures against GPG/openPGP RSA public keys. Does currently not work with openssl or JCA/JCE keys. * * @param pubKeyFile Path to file providing the public key to use * @param sigFile Path to detached signature file * @param dataFile Path to signed data file * @return {@code true} if signature is valid, {@code false} if signature is not valid * @throws Exception throws various exceptions in case something went wrong. Main reason should be that key or * signature could be extracted from the provided files due to a "bad" format.<br> * <code>FileNotFoundException, IOException, SignatureException, PGPException</code> *///from www . j a v a2 s . c om public static VerifyStatusEnum verifySignature(File pubKeyFile, File sigFile, File dataFile) throws Exception { InputStream inputStream; int bytesRead; PGPPublicKey publicKey; PGPSignature pgpSignature; boolean result; // Read keys from file inputStream = PGPUtil.getDecoderStream(new FileInputStream(pubKeyFile)); PGPPublicKeyRingCollection publicKeyRingCollection = new PGPPublicKeyRingCollection(inputStream, new JcaKeyFingerprintCalculator()); inputStream.close(); Iterator<PGPPublicKeyRing> iterator = publicKeyRingCollection.getKeyRings(); PGPPublicKeyRing pgpPublicKeyRing; if (iterator.hasNext()) { pgpPublicKeyRing = iterator.next(); } else { throw new PGPException("Could not find public keyring in provided key file"); } // Would be the solution for multiple keys in one file // Iterator<PGPPublicKey> kIt; // kIt = pgpPublicKeyRing.getPublicKeys(); // publicKey = pgpPublicKeyRing.getPublicKey(0xF5B84436F379A1C6L); // Read signature from file inputStream = PGPUtil.getDecoderStream(new FileInputStream(sigFile)); PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(inputStream, new JcaKeyFingerprintCalculator()); Object o = pgpObjectFactory.nextObject(); if (o instanceof PGPSignatureList) { PGPSignatureList signatureList = (PGPSignatureList) o; checkArgument(!signatureList.isEmpty(), "signatureList must not be empty"); pgpSignature = signatureList.get(0); } else if (o instanceof PGPSignature) { pgpSignature = (PGPSignature) o; } else { throw new SignatureException("Could not find signature in provided signature file"); } inputStream.close(); log.debug("KeyID used in signature: %X\n", pgpSignature.getKeyID()); publicKey = pgpPublicKeyRing.getPublicKey(pgpSignature.getKeyID()); // If signature is not matching the key used for signing we fail if (publicKey == null) return VerifyStatusEnum.FAIL; log.debug("The ID of the selected key is %X\n", publicKey.getKeyID()); pgpSignature.init(new BcPGPContentVerifierBuilderProvider(), publicKey); // Read file to verify byte[] data = new byte[1024]; inputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile))); while (true) { bytesRead = inputStream.read(data, 0, 1024); if (bytesRead == -1) break; pgpSignature.update(data, 0, bytesRead); } inputStream.close(); // Verify the signature result = pgpSignature.verify(); return result ? VerifyStatusEnum.OK : VerifyStatusEnum.FAIL; }
From source file:cc.arduino.contributions.GPGDetachedSignatureVerifier.java
License:Open Source License
protected boolean verify(File signedFile, File signature, File publicKey) throws IOException { FileInputStream signatureInputStream = null; FileInputStream signedFileInputStream = null; try {/*from w ww .j a v a2s .com*/ signatureInputStream = new FileInputStream(signature); PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(signatureInputStream, new BcKeyFingerprintCalculator()); Object nextObject; try { nextObject = pgpObjectFactory.nextObject(); if (!(nextObject instanceof PGPSignatureList)) { return false; } } catch (IOException e) { return false; } PGPSignatureList pgpSignatureList = (PGPSignatureList) nextObject; assert pgpSignatureList.size() == 1; PGPSignature pgpSignature = pgpSignatureList.get(0); PGPPublicKey pgpPublicKey = readPublicKey(publicKey, keyId); pgpSignature.init(new BcPGPContentVerifierBuilderProvider(), pgpPublicKey); signedFileInputStream = new FileInputStream(signedFile); pgpSignature.update(IOUtils.toByteArray(signedFileInputStream)); return pgpSignature.verify(); } catch (PGPException e) { throw new IOException(e); } finally { IOUtils.closeQuietly(signatureInputStream); IOUtils.closeQuietly(signedFileInputStream); } }
From source file:cc.arduino.packages.security.ClearSignedVerifier.java
License:Open Source License
/** * Verify a PGP clearText-signature.//from w ww.j a v a2 s . c om * * @param signedTextFile A File containing the clearText signature * @param pubKeyRing A public key-ring containing the public key needed for the * signature verification * @return A VerifyResult class with the clearText and the signature * verification status * @throws FileNotFoundException */ public static VerifyResult verify(File signedTextFile, PGPPublicKeyRingCollection pubKeyRing) { // Create the result object VerifyResult result = new VerifyResult(); result.clearText = null; result.verified = false; result.error = null; ArmoredInputStream in = null; try { // Extract clear text. // Dash-encoding is removed by ArmoredInputStream. in = new ArmoredInputStream(new FileInputStream(signedTextFile)); ByteArrayOutputStream temp = new ByteArrayOutputStream(in.available()); while (true) { int c = in.read(); if (c == -1) throw new IOException("Unexpected end of file"); if (!in.isClearText()) break; temp.write(c); } byte clearText[] = temp.toByteArray(); result.clearText = clearText; // Extract signature from clear-signed text PGPObjectFactory pgpFact = new PGPObjectFactory(in); PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject(); PGPSignature sig = p3.get(0); // Decode public key PGPPublicKey publicKey = pubKeyRing.getPublicKey(sig.getKeyID()); // Verify signature Security.addProvider(new BouncyCastleProvider()); sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), publicKey); // RFC 4880, section 7: http://tools.ietf.org/html/rfc4880#section-7 // The signature must be validated using clear text: // - without trailing white spaces on every line // - using CR LF line endings, no matter what the original line ending is // - without the latest line ending BufferedReader textIn = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(clearText))); while (true) { // remove trailing whitespace and line endings String line = StringUtils.rtrim(textIn.readLine()); sig.update(line.getBytes()); if (!textIn.ready()) // skip latest line ending break; // always use CR LF sig.update((byte) '\r'); sig.update((byte) '\n'); } // Prepare the result result.verified = sig.verify(); } catch (Exception e) { result.error = e; } finally { if (in != null) try { in.close(); } catch (IOException e) { // ignored } } return result; }
From source file:com.bekwam.resignator.util.CryptUtils.java
License:Apache License
private byte[] decrypt(byte[] encrypted, char[] passPhrase) throws IOException, PGPException, NoSuchProviderException { try (InputStream in = new ByteArrayInputStream(encrypted)) { InputStream decoderIn = PGPUtil.getDecoderStream(in); PGPObjectFactory pgpF = new PGPObjectFactory(decoderIn, new BcKeyFingerprintCalculator()); PGPEncryptedDataList enc;/*w w w . j a v a 2 s .c om*/ Object o = pgpF.nextObject(); if (o == null) { // decryption failed; there is no next object // // This could arise if there is a problem with the underlying file. // if (logger.isWarnEnabled()) { logger.warn( "Field could not be decrypted. (Config file modified outside of app?) Returning input bytes as encrypted bytes."); } return encrypted; } // // the first object might be a PGP marker packet. // if (o instanceof PGPEncryptedDataList) { enc = (PGPEncryptedDataList) o; } else { enc = (PGPEncryptedDataList) pgpF.nextObject(); // i don't think this will be used } PGPPBEEncryptedData pbe = (PGPPBEEncryptedData) enc.get(0); InputStream clear = pbe.getDataStream(new JcePBEDataDecryptorFactoryBuilder( new JcaPGPDigestCalculatorProviderBuilder().setProvider("BC").build()).setProvider("BC") .build(passPhrase)); return Streams.readAll(clear); } }
From source file:com.geekcommune.identity.EncryptionUtil.java
License:Open Source License
/** * Decrypt the specified (PKE) input file. * /*from w w w .ja v a 2 s . co m*/ * Either pubRing and secRing should be null, or pgpSecKey should be null, but not both. * * @param out * @param inFile * @param pubRing * @param secRing * @param pgpSecKey * @param encKey * @param passwd * @param mdcRequired * @throws PGPException */ private void decryptKeyBasedFile(OutputStream out, InputStream inFile, PGPPublicKeyRingCollection pubRing, PGPSecretKeyRingCollection secRing, PGPSecretKey pgpSecKey, char[] passwd, boolean mdcRequired) throws PGPException { try { InputStream fileToDecrypt = PGPUtil.getDecoderStream(inFile); PGPObjectFactory pgpFact = new PGPObjectFactory(fileToDecrypt); Object message = pgpFact.nextObject(); PGPPublicKeyEncryptedData pked = null; // PGPCompressedData cData; // Check for signed only if (!(message instanceof PGPCompressedData)) { // // Encrypted - the first object might be a PGP marker packet. // if (!(message instanceof PGPEncryptedDataList)) { message = pgpFact.nextObject(); if (!(message instanceof PGPEncryptedDataList)) { throw new PGPException("Unrecognised PGP message type: " + message.getClass()); } } PGPEncryptedDataList enc = (PGPEncryptedDataList) message; int count = 0; // find the secret key that is needed while (count != enc.size()) { if (enc.get(count) instanceof PGPPublicKeyEncryptedData) { pked = (PGPPublicKeyEncryptedData) enc.get(count); if (pgpSecKey == null) { pgpSecKey = secRing.getSecretKey(pked.getKeyID()); if (pgpSecKey != null) { break; } } else { if (pgpSecKey.getKeyID() == pked.getKeyID()) { break; } } } count++; } if (pgpSecKey == null) { throw new PGPException("Corresponding secret key not found"); } // Check for revoked key PGPPublicKey encKey = pgpSecKey.getPublicKey(); if (encKey == null) { encKey = findPublicKey(pubRing, pgpSecKey.getKeyID(), true); } if (encKey.isRevoked()) { String keyId = Long.toHexString(encKey.getKeyID()).substring(8); System.out.println("Warning: Encryption key (0x" + keyId + ") has been revoked"); // throw new PGPException("Encryption key (0x"+keyId+") has been revoked"); } InputStream clear = pked.getDataStream(pgpSecKey.extractPrivateKey(passwd, "BC"), "BC"); PGPObjectFactory pgpClearFact = new PGPObjectFactory(clear); message = pgpClearFact.nextObject(); if (message == null) { message = pgpFact.nextObject(); } // // cData = (PGPCompressedData) pgpFact.nextObject(); // } // else { // cData = (PGPCompressedData) message; } if (message instanceof PGPCompressedData) { PGPCompressedData compressedData = (PGPCompressedData) message; pgpFact = new PGPObjectFactory(compressedData.getDataStream()); message = pgpFact.nextObject(); } // Plain file if (message instanceof PGPLiteralData) { PGPLiteralData ld = (PGPLiteralData) message; InputStream dataIn = ld.getInputStream(); int ch; while ((ch = dataIn.read()) >= 0) { out.write(ch); } out.close(); } else if (message instanceof PGPOnePassSignatureList) { // One-pass signature if (!checkOnePassSignature(out, (PGPOnePassSignatureList) message, pgpFact, pubRing)) { throw new PGPException("Signature verification failed"); } System.out.println("Signature verified"); } else if (message instanceof PGPSignatureList) { // Signature list if (!checkSignature(out, (PGPSignatureList) message, pgpFact, pubRing)) { throw new PGPException("Signature verification failed"); } System.out.println("Signature verified"); } else { // what? // System.out.println("Unrecognised message type"); throw new PGPException("Unrecognised PGP message type: " + message.getClass()); } if (pked != null) { if (pked.isIntegrityProtected()) { if (!pked.verify()) { throw new PGPException("Message failed integrity check"); } if (_verbose) { System.out.println("Message integrity check passed"); } } else { if (_verbose) { System.out.println("No message integrity check"); } if (mdcRequired) { throw new PGPException("Missing required message integrity check"); } } } } catch (PGPException e) { throw e; } catch (Exception e) { throw new PGPException("Error in decryption", e); } }
From source file:com.geekcommune.identity.EncryptionUtil.java
License:Open Source License
/** * Decrypt the specified (PBE) input file *//*w w w . j a v a 2 s. co m*/ public void decryptPBEBasedFile(String outputFilename, InputStream in, char[] passPhrase, boolean mdcRequired) throws PGPException { try { // // we need to be able to reset the stream if we try a // wrong passphrase, we'll assume that all the mechanisms // appear in the first 10k for the moment... // int READ_LIMIT = 10 * 1024; in.mark(READ_LIMIT); PGPPBEEncryptedData pbe; InputStream clear; int count = 0; for (;;) { InputStream dIn = PGPUtil.getDecoderStream(in); PGPObjectFactory pgpF = new PGPObjectFactory(dIn); 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(); } while (count < enc.size()) { if (enc.get(count) instanceof PGPPBEEncryptedData) { break; } count++; } if (count >= enc.size()) { throw new PGPException("Passphrase invalid"); } pbe = (PGPPBEEncryptedData) enc.get(count); try { clear = pbe.getDataStream(passPhrase, "BC"); } catch (PGPKeyValidationException e) { in.reset(); continue; } break; } PGPObjectFactory pgpFact = new PGPObjectFactory(clear); PGPCompressedData cData = (PGPCompressedData) pgpFact.nextObject(); pgpFact = new PGPObjectFactory(cData.getDataStream()); PGPLiteralData ld = (PGPLiteralData) pgpFact.nextObject(); if (outputFilename == null) { outputFilename = ld.getFileName(); } FileOutputStream fOut = new FileOutputStream(outputFilename); InputStream unc = ld.getInputStream(); int ch; while ((ch = unc.read()) >= 0) { fOut.write(ch); } if (pbe.isIntegrityProtected()) { if (!pbe.verify()) { throw new PGPException("Message failed integrity check"); } if (_verbose) { System.out.println("Message integrity check passed"); } } else { if (_verbose) { System.out.println("No message integrity check"); } if (mdcRequired) { throw new PGPException("Missing required message integrity check"); } } } catch (PGPException e) { throw e; } catch (Exception e) { throw new PGPException("Error in decryption", e); } }
From source file:com.geekcommune.identity.EncryptionUtil.java
License:Open Source License
/** * Verify the passed in file as being correctly signed. *///from www.ja va2 s. c o m public void verifyFile(OutputStream out, InputStream inFile, InputStream publicRing) throws PGPException { try { // Get the public keyring PGPPublicKeyRingCollection pubRing = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream(publicRing)); InputStream in = PGPUtil.getDecoderStream(inFile); // // a clear signed file // if (in instanceof ArmoredInputStream && ((ArmoredInputStream) in).isClearText()) { if (!checkClearsign(in, pubRing)) { throw new PGPException("Signature verification failed."); } if (_verbose) { System.out.println("Signature verified."); } } else { PGPObjectFactory pgpFact = new PGPObjectFactory(in); PGPCompressedData c1 = (PGPCompressedData) pgpFact.nextObject(); pgpFact = new PGPObjectFactory(c1.getDataStream()); Object message = pgpFact.nextObject(); if (message instanceof PGPOnePassSignatureList) { // One-pass signature list if (!checkOnePassSignature(out, (PGPOnePassSignatureList) message, pgpFact, pubRing)) { throw new PGPException("Signature verification failed."); } } else if (message instanceof PGPSignatureList) { // Signature list if (!checkSignature(out, (PGPSignatureList) message, pgpFact, pubRing)) { throw new PGPException("Signature verification failed."); } } else { // what? throw new PGPException("Unrecognised PGP message type"); } } if (_verbose) { System.out.println("Signature verified."); } } catch (Exception e) { throw new PGPException("Error in verification", e); } }
From source file:com.geekcommune.identity.EncryptionUtil.java
License:Open Source License
/** * Check the signature in clear-signed data *///from w ww . j a va2 s. c om private boolean checkClearsign(InputStream in, PGPPublicKeyRingCollection pgpRings) throws PGPException { try { // // read the input, making sure we ingore the last newline. // ArmoredInputStream aIn = (ArmoredInputStream) in; boolean newLine = false; ByteArrayOutputStream bOut = new ByteArrayOutputStream(); int ch; while ((ch = aIn.read()) >= 0 && aIn.isClearText()) { if (newLine) { bOut.write((byte) '\n'); newLine = false; } if (ch == '\n') { newLine = true; continue; } bOut.write((byte) ch); } PGPObjectFactory pgpFact = new PGPObjectFactory(aIn); PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject(); PGPSignature sig = null; PGPPublicKey key = null; int count = 0; while (count < p3.size()) { sig = (PGPSignature) p3.get(count); key = pgpRings.getPublicKey(sig.getKeyID()); if (key != null) { break; } count++; } if (key == null) { throw new PGPException("Corresponding public key not found"); } if (key.isRevoked()) { String keyId = Long.toHexString(key.getKeyID()).substring(8); System.out.println("Warning: Signing key (0x" + keyId + ") has been revoked"); // throw new PGPException("Signing key (0x"+keyId+") has been revoked"); } sig.initVerify(key, "BC"); sig.update(bOut.toByteArray()); return sig.verify(); } catch (PGPException e) { throw e; } catch (Exception e) { throw new PGPException("Error in verification", e); } }