Java Code Examples for org.bouncycastle.openpgp.PGPUtil#getDecoderStream()
The following examples show how to use
org.bouncycastle.openpgp.PGPUtil#getDecoderStream() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KeyFilesOperationsPgpImpl.java From pgptool with GNU General Public License v3.0 | 7 votes |
@SuppressWarnings("rawtypes") private static void readKeyFromStream(KeyDataPgp data, InputStream stream) throws IOException { PGPObjectFactory factory = new PGPObjectFactory(PGPUtil.getDecoderStream(stream), fingerprintCalculator); for (Iterator iter = factory.iterator(); iter.hasNext();) { Object section = iter.next(); log.debug("Section found: " + section); if (section instanceof PGPSecretKeyRing) { data.setSecretKeyRing((PGPSecretKeyRing) section); } else if (section instanceof PGPPublicKeyRing) { data.setPublicKeyRing((PGPPublicKeyRing) section); } else { log.error("Unknown section enountered in a key file: " + section); } } }
Example 2
Source File: AptSigningFacet.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
private PGPSecretKey readSecretKey() throws IOException { try { PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream(new ByteArrayInputStream(config.keypair.getBytes(Charsets.UTF_8))), new JcaKeyFingerprintCalculator()); Iterator<PGPSecretKeyRing> keyRings = pgpSec.getKeyRings(); while (keyRings.hasNext()) { PGPSecretKeyRing keyRing = keyRings.next(); Iterator<PGPSecretKey> keys = keyRing.getSecretKeys(); while (keys.hasNext()) { PGPSecretKey key = keys.next(); if (key.isSigningKey()) { return key; } } } } catch (PGPException ex) { throw new RuntimeException(ex); } throw new IllegalStateException("Can't find signing key in key ring."); }
Example 3
Source File: AptSigningFacet.java From nexus-repository-apt with Eclipse Public License 1.0 | 6 votes |
private PGPSecretKey readSecretKey() throws IOException, PGPException { PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream(new ByteArrayInputStream(config.keypair.getBytes())), new JcaKeyFingerprintCalculator()); Iterator<PGPSecretKeyRing> keyRings = pgpSec.getKeyRings(); while (keyRings.hasNext()) { PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRings.next(); Iterator<PGPSecretKey> keys = keyRing.getSecretKeys(); while (keys.hasNext()) { PGPSecretKey key = (PGPSecretKey) keys.next(); if (key.isSigningKey()) { return key; } } } throw new IllegalStateException("Can't find signing key in key ring."); }
Example 4
Source File: BcGpgDoer.java From jeka with Apache License 2.0 | 6 votes |
private static List<PGPSecretKeyRing> extractSecrectKeyRings(InputStream inputStream) { InputStream decodedInput; try { decodedInput = PGPUtil.getDecoderStream(inputStream); } catch (final IOException e) { throw JkUtilsThrowable.unchecked(e); } final KeyFingerPrintCalculator fingerPrintCalculator = new JcaKeyFingerprintCalculator(); final InnerPGPObjectFactory pgpFact = new InnerPGPObjectFactory(decodedInput, fingerPrintCalculator); PGPSecretKeyRing secKeyRing; final List<PGPSecretKeyRing> result = new LinkedList<>(); while ((secKeyRing = pgpFact.nextSecretKey()) != null) { result.add(secKeyRing); } return result; }
Example 5
Source File: EncryptionServicePgpImpl.java From pgptool with GNU General Public License v3.0 | 5 votes |
@SuppressWarnings("rawtypes") private PGPPublicKeyEncryptedData getPublicKeyEncryptedDataByKeyId(InputStream in, PGPSecretKey secretKey) { try { PGPObjectFactory factory = new PGPObjectFactory(PGPUtil.getDecoderStream(in), KeyFilesOperationsPgpImpl.fingerprintCalculator); for (Iterator iter = factory.iterator(); iter.hasNext();) { Object section = iter.next(); if (section instanceof PGPEncryptedDataList) { PGPEncryptedDataList d = (PGPEncryptedDataList) section; for (Iterator dataIter = d.getEncryptedDataObjects(); dataIter.hasNext();) { PGPPublicKeyEncryptedData data = (PGPPublicKeyEncryptedData) dataIter.next(); if (data.getKeyID() == secretKey.getKeyID()) { return data; } } } } // NOTE: That is actually should NEVER happen since secret key we're // supposed to use here was taken exactly same way as we're looking // for PGPPublicKeyEncryptedData now throw new RuntimeException("Encryption data matching given key " + KeyDataPgp.buildKeyIdStr(secretKey.getKeyID()) + " wasn't found"); } catch (Throwable t) { throw new RuntimeException("Failed to find Encryption data section in encrypted file", t); } }
Example 6
Source File: BcGpgDoer.java From jeka with Apache License 2.0 | 5 votes |
static boolean verify(InputStream streamToVerify, InputStream signatureStream, InputStream keyInputStream) throws IOException, PGPException { final InputStream sigInputStream = PGPUtil.getDecoderStream(new BufferedInputStream( signatureStream)); final KeyFingerPrintCalculator fingerPrintCalculator = new JcaKeyFingerprintCalculator(); final PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(sigInputStream, fingerPrintCalculator); final PGPSignatureList signatureList; final Object gpgObject = pgpObjectFactory.nextObject(); if (gpgObject == null) { throw new IllegalArgumentException("no PGP signature found in " + sigInputStream); } if (gpgObject instanceof PGPCompressedData) { final PGPCompressedData compressedData = (PGPCompressedData) gpgObject; final PGPObjectFactory compressedPgpObjectFactory = new PGPObjectFactory( compressedData.getDataStream(), fingerPrintCalculator); signatureList = (PGPSignatureList) compressedPgpObjectFactory.nextObject(); } else { signatureList = (PGPSignatureList) gpgObject; } final PGPPublicKeyRingCollection pgpPubRingCollection = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream(keyInputStream), fingerPrintCalculator); final InputStream bufferedStream = new BufferedInputStream(streamToVerify); final PGPSignature signature = signatureList.get(0); final PGPPublicKey publicKey = pgpPubRingCollection.getPublicKey(signature.getKeyID()); final PGPContentVerifierBuilderProvider builderProvider = new BcPGPContentVerifierBuilderProvider(); signature.init(builderProvider, publicKey); int character; while ((character = bufferedStream.read()) >= 0) { signature.update((byte) character); } return signature.verify(); }
Example 7
Source File: PgpHelper.java From packagedrone with Eclipse Public License 1.0 | 5 votes |
public static PGPSecretKey loadSecretKey ( final InputStream input, final String keyId ) throws IOException, PGPException { final long keyIdNum = Long.parseUnsignedLong ( keyId, 16 ); final BcPGPSecretKeyRingCollection keyrings = new BcPGPSecretKeyRingCollection ( PGPUtil.getDecoderStream ( input ) ); final Iterator<?> keyRingIter = keyrings.getKeyRings (); while ( keyRingIter.hasNext () ) { final PGPSecretKeyRing secretKeyRing = (PGPSecretKeyRing)keyRingIter.next (); final Iterator<?> secretKeyIterator = secretKeyRing.getSecretKeys (); while ( secretKeyIterator.hasNext () ) { final PGPSecretKey key = (PGPSecretKey)secretKeyIterator.next (); if ( !key.isSigningKey () ) { continue; } final long shortId = key.getKeyID () & 0xFFFFFFFFL; if ( key.getKeyID () != keyIdNum && shortId != keyIdNum ) { continue; } return key; } } return null; }
Example 8
Source File: DummyKeyringModule.java From nomulus with Apache License 2.0 | 5 votes |
/** Always returns a {@link InMemoryKeyring} instance. */ @Provides @Named("DummyKeyring") static InMemoryKeyring provideDummyKeyring() { PGPKeyPair dummyKey; try (InputStream publicInput = PGP_PUBLIC_KEYRING.openStream(); InputStream privateInput = PGP_PRIVATE_KEYRING.openStream()) { PGPPublicKeyRingCollection publicKeys = new BcPGPPublicKeyRingCollection(PGPUtil.getDecoderStream(publicInput)); PGPSecretKeyRingCollection privateKeys = new BcPGPSecretKeyRingCollection(PGPUtil.getDecoderStream(privateInput)); dummyKey = lookupKeyPair(publicKeys, privateKeys, EMAIL_ADDRESS, ENCRYPT_SIGN); } catch (PGPException | IOException e) { throw new VerifyException("Failed to load PGP keys from jar", e); } // Use the same dummy PGP keypair for all required PGP keys -- a real production system would // have different values for these keys. Pass dummy values for all Strings. return new InMemoryKeyring( dummyKey, dummyKey, dummyKey.getPublicKey(), dummyKey, dummyKey.getPublicKey(), "not a real key", "not a real key", "not a real password", "not a real API key", "not a real login", "not a real password", "not a real login", "not a real credential", "not a real password", "not a real password"); }
Example 9
Source File: PGPEncryptionUtilTest.java From peer-os with Apache License 2.0 | 5 votes |
private void signKeyAndPrintIds( KeyPair first, KeyPair second, String password ) throws IOException, PGPException { InputStream firstPublicStream = new ByteArrayInputStream( first.getPubKeyring() ); InputStream secondPublicStream = new ByteArrayInputStream( second.getPubKeyring() ); InputStream secondSecretStream = new ByteArrayInputStream( second.getSecKeyring() ); PGPPublicKeyRingCollection keyrings = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream( firstPublicStream ), new JcaKeyFingerprintCalculator() ); PGPPublicKeyRing firstPublicKeyRing = null; if ( keyrings.getKeyRings().hasNext() ) { firstPublicKeyRing = keyrings.getKeyRings().next(); PGPSecretKey secondSecretKey = PGPEncryptionUtil.findSecretKeyById( secondSecretStream, second.getPrimaryKeyId() ); PGPPublicKey secondPublicKey = PGPEncryptionUtil.findPublicKeyById( secondPublicStream, second.getPrimaryKeyId() ); if ( secondSecretKey != null ) { String keyId = Long.toHexString( secondSecretKey.getKeyID() ); PGPPublicKeyRing firstSignedPublicKeyRing = PGPEncryptionUtil.signPublicKey( firstPublicKeyRing, keyId, secondSecretKey, password ); printPublicKeySignatures( firstSignedPublicKeyRing.getPublicKey(), secondPublicKey ); first.setPubKeyring( firstSignedPublicKeyRing.getEncoded() ); } } }
Example 10
Source File: TmchData.java From nomulus with Apache License 2.0 | 5 votes |
static PGPPublicKey loadPublicKey(ByteSource pgpPublicKeyFile) { try (InputStream input = pgpPublicKeyFile.openStream(); InputStream decoder = PGPUtil.getDecoderStream(input)) { return new BcPGPPublicKeyRing(decoder).getPublicKey(); } catch (IOException e) { throw new RuntimeException(e); } }
Example 11
Source File: PGPEncryptionUtilTest.java From peer-os with Apache License 2.0 | 5 votes |
@Test public void testVerifyClearSign() throws Exception { InputStream secondPublicStream = findFile( PLUGIN_PUBLIC_KEY ); PGPPublicKeyRingCollection secondPublicKeyRingCollection = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream( secondPublicStream ), new JcaKeyFingerprintCalculator() ); PGPPublicKeyRing pgpKeyring = secondPublicKeyRingCollection .getPublicKeyRing( secondPublicKeyRingCollection.iterator().next().getPublicKey().getKeyID() ); String signedMessage = IOUtils.toString( findFile( "signedMessage.txt" ) ); logger.info( "\n" + signedMessage ); boolean result = PGPEncryptionUtil.verifyClearSign( signedMessage.getBytes(), pgpKeyring ); if ( result ) { logger.info( "signature verified." ); } else { logger.info( "signature verification failed." ); } assertEquals( true, result ); }
Example 12
Source File: GPGFileEncryptor.java From incubator-gobblin with Apache License 2.0 | 5 votes |
/** * Taking in an input {@link OutputStream}, keyring inputstream and a passPhrase, generate an encrypted {@link OutputStream}. * @param outputStream {@link OutputStream} that will receive the encrypted content * @param keyIn keyring inputstream. This InputStream is owned by the caller. * @param keyId key identifier * @param cipher the symmetric cipher to use for encryption. If null or empty then a default cipher is used. * @return an {@link OutputStream} to write content to for encryption * @throws IOException */ public OutputStream encryptFile(OutputStream outputStream, InputStream keyIn, long keyId, String cipher) throws IOException { try { if (Security.getProvider(PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastleProvider()); } PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator( new JcePGPDataEncryptorBuilder(symmetricKeyAlgorithmNameToTag(cipher)) .setSecureRandom(new SecureRandom()) .setProvider(PROVIDER_NAME)); PGPPublicKey publicKey; PGPPublicKeyRingCollection keyRings = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(keyIn), new BcKeyFingerprintCalculator()); publicKey = keyRings.getPublicKey(keyId); if (publicKey == null) { throw new IllegalArgumentException("public key for encryption not found"); } cPk.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(publicKey).setProvider(PROVIDER_NAME)); OutputStream cOut = cPk.open(outputStream, new byte[BUFFER_SIZE]); PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator(); OutputStream _literalOut = literalGen.open(cOut, PGPLiteralDataGenerator.BINARY, PAYLOAD_NAME, new Date(), new byte[BUFFER_SIZE]); return new ClosingWrapperOutputStream(_literalOut, cOut, outputStream); } catch (PGPException e) { throw new IOException(e); } }
Example 13
Source File: Marksdb.java From nomulus with Apache License 2.0 | 5 votes |
/** * Extracts a {@link PGPSignature} object from a blob of {@code .sig} data. * * @throws SignatureException if a signature object couldn't be extracted for any reason. */ private static PGPSignature pgpExtractSignature(@Tainted byte[] signature) throws SignatureException { try { ByteArrayInputStream input = new ByteArrayInputStream(signature); PGPObjectFactory decoder = new BcPGPObjectFactory(PGPUtil.getDecoderStream(input)); Object object = decoder.nextObject(); if (object == null) { throw new SignatureException(String.format( "No OpenPGP packets found in signature.\n%s", dumpHex(signature))); } if (!(object instanceof PGPSignatureList)) { throw new SignatureException(String.format( "Expected PGPSignatureList packet but got %s\n%s", object.getClass().getSimpleName(), dumpHex(signature))); } PGPSignatureList sigs = (PGPSignatureList) object; if (sigs.isEmpty()) { throw new SignatureException(String.format( "PGPSignatureList doesn't have a PGPSignature.\n%s", dumpHex(signature))); } return sigs.get(0); } catch (IOException e) { throw new SignatureException(String.format( "Failed to extract PGPSignature object from .sig blob.\n%s", dumpHex(signature)), e); } }
Example 14
Source File: AptITSupport.java From nexus-public with Eclipse Public License 1.0 | 4 votes |
public boolean verifyInReleaseFilePgpSignature(final InputStream fileContent, final InputStream publicKeyString) throws Exception { PGPPublicKeyRingCollection pgpRings = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(publicKeyString), new JcaKeyFingerprintCalculator()); ArmoredInputStream aIn = new ArmoredInputStream(fileContent); ByteArrayOutputStream releaseContent = new ByteArrayOutputStream(); ByteArrayOutputStream lineOut = new ByteArrayOutputStream(); int fromPositon = -1; if (aIn.isClearText()) { do { fromPositon = readStreamLine(lineOut, fromPositon, aIn); releaseContent.write(lineOut.toByteArray()); } while (fromPositon != -1 && aIn.isClearText()); } PGPObjectFactory pgpFact = new PGPObjectFactory(aIn, new JcaKeyFingerprintCalculator()); PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject(); PGPSignature sig = p3.get(0); PGPPublicKey publicKey = pgpRings.getPublicKey(sig.getKeyID()); sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), publicKey); InputStream sigIn = new ByteArrayInputStream(releaseContent.toByteArray()); fromPositon = -1; do { int length; if (fromPositon != -1) { sig.update((byte) '\r'); sig.update((byte) '\n'); } fromPositon = readStreamLine(lineOut, fromPositon, sigIn); length = lineOut.toString(StandardCharsets.UTF_8.name()).replaceAll("\\s*$", "").length(); if (length > 0) { sig.update(lineOut.toByteArray(), 0, length); } } while (fromPositon != -1); return sig.verify(); }
Example 15
Source File: KmsTestHelper.java From nomulus with Apache License 2.0 | 4 votes |
private static BcPGPSecretKeyRing getPrivateKeyring() throws Exception { return new BcPGPSecretKeyRing(PGPUtil.getDecoderStream(PGP_PRIVATE_KEYRING.openStream())); }
Example 16
Source File: PGPEncryptionUtilTest.java From peer-os with Apache License 2.0 | 4 votes |
@Test public void testClearSign() throws Exception { InputStream secondSecretStream = findFile( PLUGIN_PRIVATE_KEY ); InputStream secondPublicStream = findFile( PLUGIN_PUBLIC_KEY ); PGPSecretKeyRingCollection secretKeyRingCollection = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream( secondSecretStream ), new JcaKeyFingerprintCalculator() ); PGPSecretKeyRing secretKeyRing = secretKeyRingCollection .getSecretKeyRing( secretKeyRingCollection.iterator().next().getPublicKey().getKeyID() ); PGPSecretKey secondSecretKey = secretKeyRing.getSecretKey(); PGPPublicKeyRingCollection secondPublicKeyRingCollection = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream( secondPublicStream ), new JcaKeyFingerprintCalculator() ); PGPPublicKeyRing pgpKeyring = secondPublicKeyRingCollection .getPublicKeyRing( secondPublicKeyRingCollection.iterator().next().getPublicKey().getKeyID() ); byte[] signedMessageArmor = PGPEncryptionUtil .clearSign( IOUtils.toString( findFile( "message.txt" ) ).getBytes(), secondSecretKey, "123".toCharArray(), "" ); String signedMessage = new String( signedMessageArmor, StandardCharsets.UTF_8 ); logger.info( "\n" + signedMessage ); boolean result = PGPEncryptionUtil.verifyClearSign( signedMessage.getBytes(), pgpKeyring ); if ( result ) { logger.info( "signature verified." ); } else { logger.info( "signature verification failed." ); } assertEquals( true, result ); }
Example 17
Source File: PublicKeyUtils.java From pgpverify-maven-plugin with Apache License 2.0 | 3 votes |
/** * Load Public Keys ring from stream for given keyId. * * @param keyStream * input stream with public keys * @param keyId * key ID for find proper key ring * * @return key ring with given key id * * @throws IOException * if problem with comunication * @throws PGPException * if problem with PGP data */ public static Optional<PGPPublicKeyRing> loadPublicKeyRing(InputStream keyStream, PGPKeyId keyId) throws IOException, PGPException { InputStream keyIn = PGPUtil.getDecoderStream(keyStream); PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection(keyIn, new BcKeyFingerprintCalculator()); Optional<PGPPublicKeyRing> publicKeyRing = Optional.ofNullable(keyId.getKeyRingFromRingCollection(pgpRing)); publicKeyRing.ifPresent(PublicKeyUtils::verifyPublicKeyRing); return publicKeyRing; }
Example 18
Source File: BouncyCastleTest.java From nomulus with Apache License 2.0 | 3 votes |
@Test public void testEncryptDecrypt_KeyRingStyle() throws Exception { int bufferSize = 64 * 1024; // Alice loads Bob's "publicKey" into memory from her public key ring. PGPPublicKeyRingCollection publicKeyRings = new BcPGPPublicKeyRingCollection( PGPUtil.getDecoderStream(new ByteArrayInputStream(PUBLIC_KEY))); PGPPublicKeyRing publicKeyRing = publicKeyRings.getKeyRings("[email protected]", true, true).next(); PGPPublicKey publicKey = publicKeyRing.getPublicKey(); // Alice encrypts the secret message for Bob using his "publicKey". PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator( new BcPGPDataEncryptorBuilder(AES_128)); encryptor.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey)); byte[] encryptedData; try (ByteArrayOutputStream output = new ByteArrayOutputStream()) { try (OutputStream output2 = encryptor.open(output, new byte[bufferSize])) { output2.write(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8)); } encryptedData = output.toByteArray(); } logger.atInfo().log("Encrypted data: %s", dumpHex(encryptedData)); // Bob loads his chain of private keys into memory. PGPSecretKeyRingCollection privateKeyRings = new BcPGPSecretKeyRingCollection( PGPUtil.getDecoderStream(new ByteArrayInputStream(PRIVATE_KEY))); // Bob decrypt's the OpenPGP message (w/ ciphertext) using his "privateKey". try (ByteArrayInputStream input = new ByteArrayInputStream(encryptedData)) { PGPObjectFactory pgpFact = new BcPGPObjectFactory(input); PGPEncryptedDataList encDataList = (PGPEncryptedDataList) pgpFact.nextObject(); assertThat(encDataList.size()).isEqualTo(1); PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encDataList.get(0); // Bob loads the private key to which the message is addressed. PGPPrivateKey privateKey = extractPrivateKey(privateKeyRings.getSecretKey(encData.getKeyID())); try (InputStream original = encData.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey))) { assertThat(CharStreams.toString(new InputStreamReader(original, UTF_8))) .isEqualTo(FALL_OF_HYPERION_A_DREAM); } } }
Example 19
Source File: PGPVerify.java From peer-os with Apache License 2.0 | 3 votes |
private static JcaPGPObjectFactory getObjectFactory( byte signedData[] ) throws IOException, PGPException { InputStream in = PGPUtil.getDecoderStream( new ByteArrayInputStream( signedData ) ); JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory( in ); PGPCompressedData compressedData = ( PGPCompressedData ) pgpFact.nextObject(); return new JcaPGPObjectFactory( compressedData.getDataStream() ); }
Example 20
Source File: PgpHelper.java From packagedrone with Eclipse Public License 1.0 | 3 votes |
public static Stream<PGPKeyRing> streamKeyring ( final InputStream input ) throws IOException, PGPException { final BcPGPSecretKeyRingCollection keyrings = new BcPGPSecretKeyRingCollection ( PGPUtil.getDecoderStream ( input ) ); final Iterator<?> keyRingIter = keyrings.getKeyRings (); final Stream<?> s = StreamSupport.stream ( Spliterators.spliteratorUnknownSize ( keyRingIter, Spliterator.ORDERED ), false ); return s.map ( o -> (PGPKeyRing)o ); }