List of usage examples for org.bouncycastle.openpgp PGPUtil getDecoderStream
public static InputStream getDecoderStream(InputStream in) throws IOException
From source file:SELSKeyGen.java
License:Open Source License
private static PGPPublicKey readPublicKey(InputStream in) throws IOException, PGPException { in = PGPUtil.getDecoderStream(in); PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in); //// w w w . j ava 2 s .co m // we just loop through the collection till we find a key suitable for encryption, in the real // world you would probably want to be a bit smarter about this. // PGPPublicKey key = null; // // iterate through the key rings. // Iterator rIt = pgpPub.getKeyRings(); while (key == null && rIt.hasNext()) { PGPPublicKeyRing kRing = (PGPPublicKeyRing) rIt.next(); Iterator kIt = kRing.getPublicKeys(); //boolean encryptionKeyFound = false; while (key == null && kIt.hasNext()) { PGPPublicKey k = (PGPPublicKey) kIt.next(); if (k.isEncryptionKey()) { key = k; } } } if (key == null) { throw new IllegalArgumentException("Can't find encryption key in key ring."); } return key; }
From source file:SELSKeyGen.java
License:Open Source License
/** * Load a secret key ring collection from keyIn and find the secret key corresponding to * keyID if it exists.// w w w . j a v a2s. c o m * * @param keyIn input stream representing a key ring collection. * @param keyID keyID we want. * @param pass passphrase to decrypt secret key with. * @return * @throws IOException * @throws PGPException * @throws NoSuchProviderException */ private static PGPPrivateKey findSecretKey(InputStream keyIn, long keyID, char[] pass) throws IOException, PGPException, NoSuchProviderException { PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn)); PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID); if (pgpSecKey == null) { return null; } return pgpSecKey.extractPrivateKey(pass, "BC"); }
From source file:alpha.offsync.security.OpenPGPSecurityUtility.java
License:Apache License
@Override public void decrypt(final OutputStream outputStream, final InputStream inputStream) { try {/*from w w w .j av a 2 s . c o 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:alpha.offsync.security.OpenPGPSecurityUtility.java
License:Apache License
@Override public void verify(OutputStream outputStream, final InputStream inputStream) { try {/*from w ww . j a va 2 s . c o 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:alpha.offsync.security.OpenPGPSecurityUtility.java
License:Apache License
@Override public void importCryptographyMetadata(final InputStream input) { OpenPGPSecurityUtility.LOGGER.info("Importing cryptography metadata"); try {/*from w w w . j av a 2 s. c o m*/ PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream(new FileInputStream(this.publicKeyRing))); final PGPPublicKeyRingCollection pgpPubIncoming = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream(input)); PGPPublicKeyRing ppKr; final Iterator<PGPPublicKeyRing> it = pgpPubIncoming.getKeyRings(); while (it.hasNext()) { ppKr = it.next(); if (!pgpPub.contains(ppKr.getPublicKey().getKeyID())) { pgpPub = PGPPublicKeyRingCollection.addPublicKeyRing(pgpPub, ppKr); } } pgpPub.encode(new FileOutputStream(new File(this.publicKeyRing.getAbsolutePath()))); } catch (final FileNotFoundException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } catch (final PGPException e) { e.printStackTrace(); } }
From source file:alpha.offsync.security.OpenPGPSecurityUtility.java
License:Apache License
/** * Gets the correct encryption key from local public keyring using the * supplied key information./*from w ww . j a v a2s . c o m*/ * * @param keyInfo * the supplied key information * @return the correct encryption key */ public PGPPublicKey getEncryptionKey(final String keyInfo) { PGPPublicKeyRingCollection pgpPub; try { pgpPub = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream(new FileInputStream(this.publicKeyRing))); final Iterator<PGPPublicKeyRing> keyRingIter = pgpPub.getKeyRings(); while (keyRingIter.hasNext()) { final PGPPublicKeyRing keyRing = keyRingIter.next(); final Iterator keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext()) { final PGPPublicKey key = (PGPPublicKey) keyIter.next(); final Iterator idIter = key.getUserIDs(); while (idIter.hasNext()) { final String userID = idIter.next().toString(); if (userID.contains(keyInfo) && key.isEncryptionKey()) return key; } } } } catch (final FileNotFoundException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } catch (final PGPException e) { e.printStackTrace(); } return null; }
From source file:alpha.offsync.security.OpenPGPSecurityUtility.java
License:Apache License
/** * Gets the correct signing key from local secret keyring using the supplied * key information.//from w w w.j av a 2s .c o m * * @param keyInfo * the supplied key information * @return the correct signing key * @throws IOException * Signals that an I/O exception has occurred. * @throws PGPException * thrown if an error is encountered */ public PGPSecretKey getSignKey(final String keyInfo) throws IOException, PGPException { final PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream(new FileInputStream(this.secretKeyRing))); final Iterator keyRingIter = pgpSec.getKeyRings(); while (keyRingIter.hasNext()) { final PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRingIter.next(); final Iterator keyIter = keyRing.getSecretKeys(); while (keyIter.hasNext()) { final PGPSecretKey key = (PGPSecretKey) keyIter.next(); final Iterator idIter = key.getUserIDs(); while (idIter.hasNext()) { final String userID = idIter.next().toString(); if (userID.contains(keyInfo) && key.isSigningKey()) return key; } } } return null; }
From source file:bisq.common.crypto.PGP.java
License:Open Source License
@Nullable public static PGPPublicKey getPubKeyFromPem(@Nullable String pem) { if (pem != null) { InputStream inputStream = new ByteArrayInputStream(pem.getBytes(Charsets.UTF_8)); try {/* w ww .ja v a2s . c o m*/ inputStream = PGPUtil.getDecoderStream(inputStream); try { JcaPGPPublicKeyRingCollection ringCollection = new JcaPGPPublicKeyRingCollection(inputStream); Iterator<PGPPublicKeyRing> keyRingsIterator = ringCollection.getKeyRings(); while (keyRingsIterator.hasNext()) { PGPPublicKeyRing pgpPublicKeyRing = keyRingsIterator.next(); Iterator<PGPPublicKey> pubKeysIterator = pgpPublicKeyRing.getPublicKeys(); while (pubKeysIterator.hasNext()) { final PGPPublicKey pgpPublicKey = pubKeysIterator.next(); if ((pgpPublicKey).isEncryptionKey()) { log.debug(pgpPublicKey.getClass().getName() + " KeyID: " + Long.toHexString(pgpPublicKey.getKeyID()) + " type: " + pgpPublicKey.getAlgorithm() + " fingerprint: " + new String(Hex.encode(pgpPublicKey.getFingerprint()))); BCPGKey bcKey = pgpPublicKey.getPublicKeyPacket().getKey(); log.debug(bcKey.getClass().getName()); if (bcKey instanceof RSAPublicBCPGKey) { RSAPublicBCPGKey bcRSA = (RSAPublicBCPGKey) bcKey; RSAPublicKeySpec specRSA = new RSAPublicKeySpec(bcRSA.getModulus(), bcRSA.getPublicExponent()); PublicKey jceKey = KeyFactory.getInstance("RSA").generatePublic(specRSA); // if you want to use the key in JCE, use jceKey // if you want to write "X.509" (SPKI) DER format to a file: //Files.write(new File(pubKeyAsString).toPath(), jceKey.getEncoded()); // if you want to write in PEM, bouncycastle can do that // or you can just do base64 and add BEGIN/END lines // return pubKeyAsString; // assume only one key; if need to handle multiple keys // or select other than the first, specify more clearly } return pgpPublicKey; } } } return null; } catch (PGPException | InvalidKeySpecException | NoSuchAlgorithmException e) { log.error("Error creating publicKey from pem. pem={}, error={}", pem, e); e.printStackTrace(); throw new KeyConversionException(e); } } catch (IOException e) { log.error("Error creating publicKey from pem. pem={}, error={}", pem, e); e.printStackTrace(); throw new KeyConversionException(e); } finally { try { inputStream.close(); } catch (IOException ignore) { } } } else { log.warn("Error creating publicKey from pem. pem=null"); return null; } }
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 w w w.ja va 2 s .com*/ 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
private PGPPublicKey readPublicKey(InputStream input, String keyId) throws IOException, PGPException { PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input), new BcKeyFingerprintCalculator()); Iterator keyRingIter = pgpPub.getKeyRings(); while (keyRingIter.hasNext()) { PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next(); Iterator keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext()) { PGPPublicKey key = (PGPPublicKey) keyIter.next(); if (Long.toHexString(key.getKeyID()).toUpperCase().endsWith(keyId)) { return key; }//from w ww .j a v a2 s. c o m } } throw new IllegalArgumentException("Can't find encryption key in key ring."); }