public static PGPPublicKey readPublicKey(InputStream in) throws IOException, PGPException { in = PGPUtil.getDecoderStream(in); PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in, new JcaKeyFingerprintCalculator() ); Iterator rIt = pgpPub.getKeyRings(); while (rIt.hasNext()) { PGPPublicKeyRing kRing = (PGPPublicKeyRing) rIt.next(); Iterator kIt = kRing.getPublicKeys(); while (kIt.hasNext()) { PGPPublicKey k = (PGPPublicKey) kIt.next(); if (k.isEncryptionKey()) { return k; } } } throw new IllegalArgumentException( "Can't find encryption key in key ring."); }
static PGPSecretKey getSecretKey(String privateKeyData) throws IOException, PGPException { PGPPrivateKey privKey = null; try (InputStream privStream = new ArmoredInputStream(new ByteArrayInputStream(privateKeyData.getBytes("UTF-8")))) { PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(privStream), new JcaKeyFingerprintCalculator()); Iterator keyRingIter = pgpSec.getKeyRings(); while (keyRingIter.hasNext()) { PGPSecretKeyRing keyRing = (PGPSecretKeyRing)keyRingIter.next(); Iterator keyIter = keyRing.getSecretKeys(); while (keyIter.hasNext()) { PGPSecretKey key = (PGPSecretKey)keyIter.next(); if (key.isSigningKey()) { return key; } } } } throw new IllegalArgumentException("Can't find signing key in key ring."); }
static String signArmoredAscii(PGPPrivateKey privateKey, String data, int signatureAlgo) throws IOException, PGPException { String signature = null; final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(privateKey.getPublicKeyPacket().getAlgorithm(), signatureAlgo)); signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, privateKey); ByteArrayOutputStream signatureOutput = new ByteArrayOutputStream(); try( BCPGOutputStream outputStream = new BCPGOutputStream( new ArmoredOutputStream(signatureOutput)) ) { Utils.processStringAsStream(data, new StreamHandler() { @Override public void handleStreamBuffer(byte[] buffer, int offset, int length) throws IOException { signatureGenerator.update(buffer, offset, length); } }); signatureGenerator.generate().encode(outputStream); } signature = new String(signatureOutput.toByteArray(), "UTF-8"); return signature; }
static String signArmoredAscii(PGPPrivateKey privateKey, byte[] data, int signatureAlgo) throws IOException, PGPException { String signature = null; final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(privateKey.getPublicKeyPacket().getAlgorithm(), signatureAlgo)); signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, privateKey); ByteArrayOutputStream signatureOutput = new ByteArrayOutputStream(); try( BCPGOutputStream outputStream = new BCPGOutputStream( new ArmoredOutputStream(signatureOutput)) ) { Utils.processByteArrayAsStream(data, new StreamHandler() { @Override public void handleStreamBuffer(byte[] buffer, int offset, int length) throws IOException { signatureGenerator.update(buffer, offset, length); } }); signatureGenerator.generate().encode(outputStream); } signature = new String(signatureOutput.toByteArray(), "UTF-8"); return signature; }
/** * Determines a public key from the keyring collection which has a certain * key ID and which has a User ID which contains at least one of the User ID * parts. * * @param keyId * key ID * @param userIdParts * user ID parts, can be empty, than no filter on the User ID is * executed * @param publicKeyringCollection * keyring collection * @return public key or <code>null</code> if no fitting key is found * @throws PGPException */ @SuppressWarnings("unchecked") public static PGPPublicKey getPublicKeyWithKeyIdAndUserID(long keyId, List<String> userIdParts, PGPPublicKeyRingCollection publicKeyringCollection) throws PGPException { PGPPublicKeyRing publicKeyring = publicKeyringCollection.getPublicKeyRing(keyId); if (publicKeyring == null) { LOG.debug("No public key found for key ID {}.", Long.toString(keyId)); return null; } // publicKey can be a subkey the user IDs must therefore be provided by the primary/master key if (isAllowedKey(userIdParts, publicKeyring.getPublicKey().getUserIDs())) { return publicKeyring.getPublicKey(keyId); } else { return null; } }
/** * Wraps with stream that outputs encrypted data packet. */ protected OutputStream encrypt(OutputStream out, FileMetadata meta) throws IOException, PGPException { if (log.isLoggable(Level.FINEST)) log.finest("using encryption algorithm " + encryptionAlgorithm); if (encryptionAlgorithm == EncryptionAlgorithm.Unencrypted) return null; List<Key> keys = ring.getEncryptionKeys(); if (Util.isEmpty(keys) && Util.isEmpty(symmetricPassphrase)) throw new PGPException("no suitable encryption key found"); PGPEncryptedDataGenerator generator = buildEncryptor(); for (Key key : keys) generator.addMethod(buildPublicKeyEncryptor(key)); if (!Util.isEmpty(symmetricPassphrase)) generator.addMethod(buildSymmetricKeyEncryptor()); return generator.open(out, getEncryptionBuffer(meta)); }
/** * Wraps with stream that outputs compressed data packet. */ protected OutputStream compress(OutputStream out, FileMetadata meta) throws IOException, PGPException { if (log.isLoggable(Level.FINEST)) log.finest("using compression algorithm " + compressionAlgorithm + " -" + compressionLevel); if (compressionAlgorithm == CompressionAlgorithm.Uncompressed || compressionLevel < 1 || compressionLevel > 9) return null; int algo = compressionAlgorithm.ordinal(); int level = compressionLevel; byte[] buf = getCompressionBuffer(meta); return new PGPCompressedDataGenerator(algo, level).open(out, buf); }
public static byte[] decrypt( byte encData[], PGPPrivateKey privateKey ) throws PGPException, IOException { PGPPublicKeyEncryptedData pgpEncData = getPGPEncryptedData( encData ); InputStream is = getInputStream( privateKey, pgpEncData ); // IMPORTANT: pipe() should be before verify(). Otherwise we get "java.io.EOFException: Unexpected end of ZIP // input stream". byte data[] = pipe( is ); if ( !pgpEncData.verify() ) { throw new PGPDataValidationException( "Data integrity check failed" ); } return data; }
/** * Opens a new {@link Decryptor} (Reading Step 1/3) * * <p>This is the first step in opening a ghostryde file. After this method, you'll want to * call {@link #openDecompressor(Decryptor)}. * * @param input is an {@link InputStream} of the ghostryde file data. * @param privateKey is the private encryption key of the recipient (which is us!) * @throws IOException * @throws PGPException */ @CheckReturnValue public Decryptor openDecryptor(@WillNotClose InputStream input, PGPPrivateKey privateKey) throws IOException, PGPException { checkNotNull(privateKey, "privateKey"); PGPObjectFactory fact = new BcPGPObjectFactory(checkNotNull(input, "input")); PGPEncryptedDataList crypts = pgpCast(fact.nextObject(), PGPEncryptedDataList.class); checkState(crypts.size() > 0); if (crypts.size() > 1) { logger.warningfmt("crypts.size() is %d (should be 1)", crypts.size()); } PGPPublicKeyEncryptedData crypt = pgpCast(crypts.get(0), PGPPublicKeyEncryptedData.class); if (crypt.getKeyID() != privateKey.getKeyID()) { throw new PGPException(String.format( "Message was encrypted for keyid %x but ours is %x", crypt.getKeyID(), privateKey.getKeyID())); } return new Decryptor( crypt.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey)), crypt); }
public byte[] signExternal(String input) throws IOException, PGPException { PGPSecretKey signKey = readSecretKey(); PGPPrivateKey privKey = signKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(config.passphrase.toCharArray())); PGPSignatureGenerator sigGenerator = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder(signKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256).setProvider("BC")); sigGenerator.init(PGPSignature.BINARY_DOCUMENT, privKey); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) { BCPGOutputStream bOut = new BCPGOutputStream(aOut); sigGenerator.update(input.getBytes(Charsets.UTF_8)); sigGenerator.generate().encode(bOut); } return buffer.toByteArray(); }
@Override public String getRelationChallenge( final long ttl ) throws RelationVerificationException { RelationChallengeImpl relationToken = new RelationChallengeImpl( ttl ); relationDataService.save( relationToken ); String content = JsonUtil.toJson( relationToken ); securityManager.getKeyManager().getPublicKey( null ); try { KeyManager keyManager = securityManager.getKeyManager(); byte[] encBytes = PGPEncryptionUtil.encrypt( content.getBytes(), keyManager.getPublicKey( null ), true ); return "\n" + new String( encBytes, "UTF-8" ); } catch ( UnsupportedEncodingException | PGPException e ) { logger.error( "Error encrypting message for relation challenge", e ); throw new RelationVerificationException( "Error encrypting message for relation challenge", e ); } }
@Override public void addPeerEnvironmentPubKey( final String keyId, final PGPPublicKeyRing pek ) throws PeerException { Preconditions.checkNotNull( keyId, "Invalid key ID" ); Preconditions.checkNotNull( pek, "Public key ring is null" ); try { String exportedPubKeyRing = securityManager.getEncryptionTool().armorByteArrayToString( pek.getEncoded() ); peerWebClient.addPeerEnvironmentPubKey( keyId, exportedPubKeyRing ); } catch ( IOException | PGPException e ) { throw new PeerException( e.getMessage() ); } }
/** * Search for public key on keyring based on a substring (like an email address). * * @throws VerifyException if the key couldn't be found. * @see #lookupKeyPair */ public static PGPPublicKey lookupPublicKey( PGPPublicKeyRingCollection keyring, String query, KeyRequirement want) { try { // Safe by specification. @SuppressWarnings("unchecked") Iterator<PGPPublicKeyRing> results = keyring.getKeyRings(checkNotNull(query, "query"), true, true); verify(results.hasNext(), "No public key found matching substring: %s", query); while (results.hasNext()) { Optional<PGPPublicKey> result = lookupPublicSubkey(results.next(), want); if (result.isPresent()) { return result.get(); } } throw new VerifyException(String.format( "No public key (%s) found matching substring: %s", want, query)); } catch (PGPException e) { throw new VerifyException(String.format( "Public key lookup with query %s failed: %s", query, e.getMessage())); } }
public List<PGPSecretKeyAndPrivateKeyAndUserId> determineSecretKeysWithPrivateKeyAndUserId(Exchange exchange, String sigKeyFileName, List<String> sigKeyUserids, String sigKeyPassword, byte[] sigKeyRing) throws IOException, PGPException, NoSuchProviderException { Map<String, String> sigKeyUserId2Password = determineSignatureKeyUserId2Password(sigKeyUserids, sigKeyPassword); List<PGPSecretKeyAndPrivateKeyAndUserId> sigSecretKeysWithPrivateKeyAndUserId = PGPDataFormatUtil .findSecretKeysWithPrivateKeyAndUserId(exchange.getContext(), sigKeyFileName, sigKeyRing, sigKeyUserId2Password, getProvider()); if (sigSecretKeysWithPrivateKeyAndUserId.isEmpty()) { throw new IllegalArgumentException( String.format( "Cannot PGP sign message. No secret key found for User IDs %s. Either add keys with this User IDs to the secret keyring or change the configured User IDs.", sigKeyUserids)); } return sigSecretKeysWithPrivateKeyAndUserId; }
public void setSig(PGPSignature s) throws PGPException { sig = s; if (sig1 != null) return; key = getRing().findById(s.getKeyID()); if (key == null) { if (Decryptor.this.log.isLoggable(Level.INFO)) Decryptor.this.log.info("not found verification key " + Util.formatKeyId(s.getKeyID())); return; } Subkey subkey = key.findById(s.getKeyID()); if (subkey == null || !subkey.isForVerification()) key = null; else s.init(getVerifierProvider(), subkey.getPublicKey()); if (Decryptor.this.log.isLoggable(Level.INFO)) Decryptor.this.log.info((key == null ? "not " : "") + "using verification key " + subkey); }
void createEncryptedNonCompressedData(ByteArrayOutputStream bos, String keyringPath) throws Exception, IOException, PGPException, UnsupportedEncodingException { PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5) .setSecureRandom(new SecureRandom()).setProvider(getProvider())); encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(readPublicKey(keyringPath))); OutputStream encOut = encGen.open(bos, new byte[512]); PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator(); OutputStream litOut = litData.open(encOut, PGPLiteralData.BINARY, PGPLiteralData.CONSOLE, new Date(), new byte[512]); try { litOut.write("Test Message Without Compression".getBytes("UTF-8")); litOut.flush(); } finally { IOHelper.close(litOut); IOHelper.close(encOut, bos); } }
public static PGPSecretKey readSecretKey( PGPSecretKeyRing keyRing ) throws PGPException { try { Iterator keyIter = keyRing.getSecretKeys(); while ( keyIter.hasNext() ) { PGPSecretKey key = ( PGPSecretKey ) keyIter.next(); if ( key.isSigningKey() ) { return key; } } } catch ( Exception e ) { LOG.error( e.getMessage() ); } return null; }
public static PGPPublicKeyRing removeSignature( PGPPublicKeyRing keyToRemoveFrom, String id ) throws PGPException { try { PGPPublicKey oldKey = keyToRemoveFrom.getPublicKey(); PGPPublicKey newKey = PGPPublicKey.removeCertification( oldKey, id ); PGPPublicKeyRing newPublicKeyRing = PGPPublicKeyRing.removePublicKey( keyToRemoveFrom, oldKey ); return PGPPublicKeyRing.insertPublicKey( newPublicKeyRing, newKey ); } catch ( Exception e ) { //throw custom exception throw new PGPException( "Error removing signature", e ); } }
/** * Deciphers a ghostryde file from an in-memory byte array. * * @throws PGPException * @throws IOException */ public static DecodeResult decode(byte[] data, PGPPrivateKey key) throws IOException, PGPException { checkNotNull(data, "data"); Ghostryde ghost = new Ghostryde(1024 * 64); ByteArrayInputStream dataStream = new ByteArrayInputStream(data); ByteArrayOutputStream output = new ByteArrayOutputStream(); String name; DateTime modified; try (Decryptor decryptor = ghost.openDecryptor(dataStream, key); Decompressor decompressor = ghost.openDecompressor(decryptor); Input input = ghost.openInput(decompressor)) { name = input.getName(); modified = input.getModified(); ByteStreams.copy(input, output); } return new DecodeResult(output.toByteArray(), name, modified); }
@Deprecated public static PGPPublicKey findPublicKey(CamelContext context, String filename, byte[] keyRing, String userid, boolean forEncryption) throws IOException, PGPException, NoSuchProviderException { InputStream is = determineKeyRingInputStream(context, filename, keyRing, forEncryption); try { List<PGPPublicKey> result = findPublicKeys(is, Collections.singletonList(userid), forEncryption); if (result.isEmpty()) { return null; } else { return result.get(0); } } finally { IOHelper.close(is); } }
/** * Same as {@link #lookupPublicKey} but also retrieves the associated private key. * * @throws VerifyException if either keys couldn't be found. * @see #lookupPublicKey */ @SuppressWarnings("deprecation") public static PGPKeyPair lookupKeyPair( PGPPublicKeyRingCollection publics, PGPSecretKeyRingCollection privates, String query, KeyRequirement want) { PGPPublicKey publicKey = lookupPublicKey(publics, query, want); PGPPrivateKey privateKey; try { PGPSecretKey secret = verifyNotNull(privates.getSecretKey(publicKey.getKeyID()), "Keyring missing private key associated with public key id: %x (query '%s')", publicKey.getKeyID(), query); // We do not support putting a password on the private key so we're just going to // put char[0] here. privateKey = secret.extractPrivateKey( new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()) .build(new char[0])); } catch (PGPException e) { throw new VerifyException(e.getMessage()); } return new PGPKeyPair(publicKey, privateKey); }
public PGPSignatureGenerator createSignatureGenerator() { try { PGPSignatureGenerator generator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1)); generator.init(PGPSignature.BINARY_DOCUMENT, privateKey); return generator; } catch (PGPException e) { throw new UncheckedException(e); } }
private PGPPrivateKey createPrivateKey(PGPSecretKey secretKey, String password) { try { PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(password.toCharArray()); return secretKey.extractPrivateKey(decryptor); } catch (PGPException e) { throw new UncheckedException(e); } }
public static PGPSecretKey readSecretKey(InputStream in) throws IOException, PGPException { in = PGPUtil.getDecoderStream(in); PGPSecretKeyRingCollection keyRingCollection = new PGPSecretKeyRingCollection(in, new JcaKeyFingerprintCalculator()); // // We just loop through the collection till we find a key suitable for signing. // In the real world you would probably want to be a bit smarter about this. // PGPSecretKey secretKey = null; Iterator<PGPSecretKeyRing> rIt = keyRingCollection.getKeyRings(); while (secretKey == null && rIt.hasNext()) { PGPSecretKeyRing keyRing = rIt.next(); Iterator<PGPSecretKey> kIt = keyRing.getSecretKeys(); while (secretKey == null && kIt.hasNext()) { PGPSecretKey key = kIt.next(); if (key.isSigningKey()) { secretKey = key; } } } // Validate secret key if (secretKey == null) { throw new IllegalArgumentException("Can't find private key in the key ring."); } if (!secretKey.isSigningKey()) { throw new IllegalArgumentException("Private key does not allow signing."); } if (secretKey.getPublicKey().isRevoked()) { throw new IllegalArgumentException("Private key has been revoked."); } return secretKey; }
/** * A simple routine that opens a key ring file and loads the first available * key suitable for encryption. * * @param input * data stream containing the public key data * @return the first public key found. * @throws IOException * @throws PGPException */ static PGPPublicKey readPublicKey(InputStream input) throws IOException, PGPException { PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input), new JcaKeyFingerprintCalculator()); // // 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. // 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 (key.isEncryptionKey()) { return key; } } } throw new IllegalArgumentException("Can't find encryption key in key ring."); }
static PGPSecretKey readSecretKey(String fileName) throws IOException, PGPException { InputStream keyIn = new BufferedInputStream(new FileInputStream(fileName)); PGPSecretKey secKey = readSecretKey(keyIn); keyIn.close(); return secKey; }
/** * A simple routine that opens a key ring file and loads the first available * key suitable for signature generation. * * @param input * stream to read the secret key ring collection from. * @return a secret key. * @throws IOException * on a problem with using the input stream. * @throws PGPException * if there is an issue parsing the input stream. */ static PGPSecretKey readSecretKey(InputStream input) throws IOException, PGPException { PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input), new JcaKeyFingerprintCalculator()); // // 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. // Iterator keyRingIter = pgpSec.getKeyRings(); while (keyRingIter.hasNext()) { PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRingIter.next(); Iterator keyIter = keyRing.getSecretKeys(); while (keyIter.hasNext()) { PGPSecretKey key = (PGPSecretKey) keyIter.next(); if (key.isSigningKey()) { return key; } } } throw new IllegalArgumentException("Can't find signing key in key ring."); }
public static PGPPublicKey readPublicKey(InputStream in, int algorithm) throws IOException, PGPException { // Get the decoder stream (auto-disarming) in = PGPUtil.getDecoderStream(in); // Open the key ring PGPPublicKeyRingCollection coll = new PGPPublicKeyRingCollection(in); // Find key encryption key for algorithm, if given return readPublicKey(coll, algorithm); }
public static PGPSecretKey readSecretKey(InputStream in) throws IOException, PGPException, NoSuchProviderException { // Get the decoder stream (auto-disarming) in = PGPUtil.getDecoderStream(in); // Open the key ring PGPSecretKeyRingCollection coll = new PGPSecretKeyRingCollection(in); // Find key return readSecretKey(coll); }
public static PGPPrivateKey readPrivateKey(PGPSecretKey secret, char[] pass) throws PGPException, NoSuchProviderException { PGPPrivateKey key = null; try { key = secret.extractPrivateKey(pass, PGPInit.PROVIDER.getName()); } catch (PGPException pgpe) { if (pgpe.getMessage().indexOf("checksum mismatch") >= 0) { throw new PGPException("Private key password invalid"); } else { throw pgpe; } } return key; }
@Override public void start(Stage primaryStage) throws IOException, PGPException { // Load crypto stuff CryptographyHandler.getInstance().loadKeys(); TrayIcon icon = new TrayIcon(); if(icon.addAppToTray()) { backgroundService.registerListener(icon); } // Polling service runs as a background service that periodically checks the server. Thread t = new Thread(backgroundService); t.setDaemon(true); t.start(); Parent page = FXMLLoader.load(getClass().getResource("/fxml/MainWindow.fxml")); Scene scene = new Scene(page, 1200, 900); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); // JavascriptVerifier verifier = new JavascriptVerifier(); // Log.i(verifier.validate().toString()); }
private PGPKeyPair getKeyPair(PrivateKeyLabel keyLabel) { try { return KeySerializer.deserializeKeyPair(getDecryptedData(keyLabel.getLabel())); } catch (IOException | PGPException e) { throw new KeyringException( String.format("Could not parse private keyLabel %s", keyLabel), e); } }
private static PGPPublicKey findPublicKeyWithKeyId(InputStream input, long keyid) throws IOException, PGPException, NoSuchProviderException { PGPPublicKeyRingCollection pgpSec = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input), new BcKeyFingerprintCalculator()); return pgpSec.getPublicKey(keyid); }
static public void addPrivateKeyToKeyring(final String gpgHomeDirectory, final String keyringFile) throws FileNotFoundException, IOException, PGPException { Security.addProvider(new BouncyCastleProvider()); // Read user secret keyring FileInputStream inPriv = new FileInputStream(gpgHomeDirectory + "/secring.gpg"); PGPSecretKeyRingCollection privRings = new PGPSecretKeyRingCollection(inPriv, new JcaKeyFingerprintCalculator()); // Read keys (public and private) from armored file PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream(new FileInputStream(keyringFile)), new JcaKeyFingerprintCalculator()); // Iterate over the keys Iterator keyRingIter = pgpSec.getKeyRings(); while (keyRingIter.hasNext()) { PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRingIter.next(); privRings = PGPSecretKeyRingCollection.addSecretKeyRing(privRings, keyRing); Iterator keyIter = keyRing.getSecretKeys(); while (keyIter.hasNext()) { PGPSecretKey key = (PGPSecretKey) keyIter.next(); if (key.isSigningKey()) { System.out.println("Private key imported " + Long.toHexString(key.getKeyID()).toUpperCase()); } } } try (FileOutputStream out = new FileOutputStream(new File(gpgHomeDirectory + "/secring.gpg"))) { privRings.encode(out); } }
static public void addPublicKeyToKeyring(String gpgHomeDirectory, String keyringFile) throws FileNotFoundException, IOException, PGPException { Security.addProvider(new BouncyCastleProvider()); FileInputStream in = new FileInputStream(gpgHomeDirectory + "/pubring.gpg"); PGPPublicKeyRingCollection pubRings = new PGPPublicKeyRingCollection(in, new JcaKeyFingerprintCalculator()); PGPPublicKeyRing pgpKeyring = new PGPPublicKeyRing(PGPUtil.getDecoderStream(new FileInputStream(keyringFile)), new JcaKeyFingerprintCalculator()); pubRings = PGPPublicKeyRingCollection.addPublicKeyRing(pubRings, pgpKeyring); try (FileOutputStream out = new FileOutputStream(new File(gpgHomeDirectory + "/pubring.gpg"))) { pubRings.encode(out); } }
/** Creates a {@code .ryde} and {@code .sig} file, provided an XML deposit file. */ void encrypt(String tld, Path xmlFile, Path outdir) throws IOException, PGPException, XmlException { try (InputStream xmlFileInput = Files.newInputStream(xmlFile); BufferedInputStream xmlInput = new BufferedInputStream(xmlFileInput, PEEK_BUFFER_SIZE)) { DateTime watermark = RdeUtil.peekWatermark(xmlInput); String name = RdeNamingUtils.makeRydeFilename(tld, watermark, FULL, 1, 0); Path rydePath = outdir.resolve(name + ".ryde"); Path sigPath = outdir.resolve(name + ".sig"); Path pubPath = outdir.resolve(tld + ".pub"); PGPKeyPair signingKey = rdeSigningKey.get(); try (OutputStream rydeOutput = Files.newOutputStream(rydePath); RydePgpSigningOutputStream signLayer = pgpSigningFactory.create(rydeOutput, signingKey)) { try (RydePgpEncryptionOutputStream encryptLayer = pgpEncryptionFactory.create(signLayer, rdeReceiverKey.get()); RydePgpCompressionOutputStream compressLayer = pgpCompressionFactory.create(encryptLayer); RydePgpFileOutputStream fileLayer = pgpFileFactory.create(compressLayer, watermark, name + ".tar"); RydeTarOutputStream tarLayer = tarFactory.create(fileLayer, Files.size(xmlFile), watermark, name + ".xml")) { ByteStreams.copy(xmlInput, tarLayer); } Files.write(sigPath, signLayer.getSignature()); try (OutputStream pubOutput = Files.newOutputStream(pubPath); ArmoredOutputStream ascOutput = new ArmoredOutputStream(pubOutput)) { signingKey.getPublicKey().encode(ascOutput); } } } }
/** * Extracts the private key from this subkey's secret key * using the specified passphrase. */ protected PGPPrivateKey extractPrivateKey(String passphrase) throws PGPException { if (secretKey == null) return null; try { return secretKey.extractPrivateKey(buildDecryptor(passphrase)); } catch (PGPException e) { throw new PassphraseException( "incorrect passphrase for subkey " + this, e); } }
@Test public void testExceptionForSignatureVerificationOptionRequired() throws Exception { encryptor.setSignatureKeyUserid(null); // no signature decryptor.setSignatureVerificationOption(PGPKeyAccessDataFormat.SIGNATURE_VERIFICATION_OPTION_REQUIRED); MockEndpoint mock = getMockEndpoint("mock:exception"); mock.expectedMessageCount(1); template.sendBody("direct:subkey", "Test Message"); assertMockEndpointsSatisfied(); checkThrownException(mock, PGPException.class, null, "PGP message does not contain any signatures although a signature is expected"); }
@Deprecated public static PGPPublicKey findPublicKeyWithKeyId(CamelContext context, String filename, byte[] keyRing, long keyid, boolean forEncryption) throws IOException, PGPException, NoSuchProviderException { InputStream is = determineKeyRingInputStream(context, filename, keyRing, forEncryption); PGPPublicKey pubKey; try { pubKey = findPublicKeyWithKeyId(is, keyid); } finally { IOHelper.close(is); } return pubKey; }
private KmsUpdater setKeyPair( PGPKeyPair keyPair, PrivateKeyLabel privateKeyLabel, PublicKeyLabel publicKeyLabel) throws IOException, PGPException { checkArgumentNotNull(keyPair); setSecret(privateKeyLabel.getLabel(), KeySerializer.serializeKeyPair(keyPair)); setSecret(publicKeyLabel.getLabel(), KeySerializer.serializePublicKey(keyPair.getPublicKey())); return this; }