org.bouncycastle.openpgp.PGPSecretKey Java Examples
The following examples show how to use
org.bouncycastle.openpgp.PGPSecretKey.
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: KeyManagerImpl.java From peer-os with Apache License 2.0 | 6 votes |
@Override public PGPSecretKey getSecretKeyByFingerprint( String fingerprint ) { PGPSecretKey secretKey = null; try { ByteArrayInputStream barIn = new ByteArrayInputStream( securityDataService.getSecretKeyData( fingerprint ).getData() ); secretKey = PGPEncryptionUtil.findSecretKeyByFingerprint( barIn, fingerprint ); } catch ( Exception ex ) { LOG.error( " ***** Error getting Secret key:" + ex.toString(), ex ); } return secretKey; }
Example #2
Source File: EncryptionServicePgpImpl.java From pgptool with GNU General Public License v3.0 | 6 votes |
private PGPPrivateKey getPrivateKey(String passphrase, PGPSecretKey secretKey) throws InvalidPasswordException { try { PBESecretKeyDecryptor decryptorFactory = new BcPBESecretKeyDecryptorBuilder( new BcPGPDigestCalculatorProvider()).build(passphrase.toCharArray()); PGPPrivateKey privateKey = secretKey.extractPrivateKey(decryptorFactory); return privateKey; } catch (Throwable t) { log.warn("Failed to extract private key. Most likely it because of incorrect passphrase provided", t); throw new InvalidPasswordException(); } }
Example #3
Source File: PgpHelper.java From packagedrone with Eclipse Public License 1.0 | 6 votes |
public static Predicate<PGPSecretKey> keyShortId ( final String keyId ) { final long keyIdNum = Long.parseUnsignedLong ( keyId, 16 ); return new Predicate<PGPSecretKey> () { @Override public boolean test ( final PGPSecretKey key ) { final long shortId = key.getKeyID () & 0xFFFFFFFFL; if ( key.getKeyID () != keyIdNum && shortId != keyIdNum ) { return false; } return true; } }; }
Example #4
Source File: PGPKeyUtil.java From peer-os with Apache License 2.0 | 6 votes |
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; }
Example #5
Source File: Entry.java From packagedrone with Eclipse Public License 1.0 | 6 votes |
protected void registerKey ( final PGPSecretKey key, final List<String> users ) throws Exception { final String keyId = String.format ( "%016X", key.getKeyID () ); final SigningService service = new ManagedSigningService ( key, this.cfg.getPassphrase () ); final Dictionary<String, Object> properties = new Hashtable<> ( 1 ); properties.put ( Constants.SERVICE_PID, "pgp." + keyId ); final String usersString = users.stream ().collect ( Collectors.joining ( "; " ) ); if ( !users.isEmpty () ) { properties.put ( Constants.SERVICE_DESCRIPTION, String.format ( "Managed PGP key (%s) %s: %s", keyId, !key.isMasterKey () ? "(sub)" : "", usersString ) ); } else { properties.put ( Constants.SERVICE_DESCRIPTION, String.format ( "Managed PGP key (%s) %s", keyId, !key.isMasterKey () ? "(sub)" : "" ) ); } this.regs.add ( this.context.registerService ( SigningService.class, service, properties ) ); }
Example #6
Source File: PGPEncryptionUtil.java From peer-os with Apache License 2.0 | 6 votes |
/** * *********************************************** */ public static PGPPrivateKey getPrivateKey( final PGPSecretKey secretKey, final String secretPwd ) { Preconditions.checkNotNull( secretKey ); Preconditions.checkNotNull( secretPwd ); try { return secretKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider( provider ).build( secretPwd.toCharArray() ) ); } catch ( Exception e ) { LOG.error( "Unable to extract key {}: {}", secretKey.getKeyID(), e.getMessage() ); } return null; }
Example #7
Source File: PGPEncryptionUtil.java From peer-os with Apache License 2.0 | 6 votes |
/** * *********************************************** */ private static PGPPrivateKey getPrivateKey( final PGPSecretKeyRingCollection keys, final long id, final String secretPwd ) { try { final PGPSecretKey key = keys.getSecretKey( id ); if ( key != null ) { return key.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider( provider ) .build( secretPwd.toCharArray() ) ); } } catch ( final Exception e ) { // Don't print the passphrase but do print null if thats what it was final String passphraseMessage = ( secretPwd == null ) ? "null" : "supplied"; LOG.warn( "Unable to extract key " + id + " using " + passphraseMessage + " passphrase: {}", e.getMessage() ); } return null; }
Example #8
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 #9
Source File: AptSigningFacet.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
public byte[] signExternal(final String input) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try { 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); try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) { BCPGOutputStream bOut = new BCPGOutputStream(aOut); sigGenerator.update(input.getBytes(Charsets.UTF_8)); sigGenerator.generate().encode(bOut); } } catch (PGPException ex) { throw new RuntimeException(ex); } return buffer.toByteArray(); }
Example #10
Source File: PGPEncryptionUtil.java From peer-os with Apache License 2.0 | 6 votes |
public static X509Certificate getX509CertificateFromPgpKeyPair( PGPPublicKey pgpPublicKey, PGPSecretKey pgpSecretKey, String secretPwd, String issuer, String subject, Date dateOfIssue, Date dateOfExpiry, BigInteger serial ) throws PGPException, CertificateException, IOException { JcaPGPKeyConverter c = new JcaPGPKeyConverter(); PublicKey publicKey = c.getPublicKey( pgpPublicKey ); PrivateKey privateKey = c.getPrivateKey( pgpSecretKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider( provider ).build( secretPwd.toCharArray() ) ) ); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( new X500Name( issuer ), serial, dateOfIssue, dateOfExpiry, new X500Name( subject ), SubjectPublicKeyInfo.getInstance( publicKey.getEncoded() ) ); byte[] certBytes = certBuilder.build( new JCESigner( privateKey, "SHA256withRSA" ) ).getEncoded(); CertificateFactory certificateFactory = CertificateFactory.getInstance( "X.509" ); return ( X509Certificate ) certificateFactory.generateCertificate( new ByteArrayInputStream( certBytes ) ); }
Example #11
Source File: PGPEncryptionUtilTest.java From peer-os with Apache License 2.0 | 6 votes |
@Test public void testSignEncryptAndDecryptVerify() throws Exception { PGPSecretKey signingKey = PGPEncryptionUtil.findSecretKeyByFingerprint( findFile( SECRET_KEYRING ), SECRET_KEY_FINGERPRINT ); PGPPublicKey encryptingKey = PGPEncryptionUtil.findPublicKeyByFingerprint( findFile( PUBLIC_KEYRING ), PUBLIC_KEY_FINGERPRINT ); byte[] signedAndEncryptedMessage = PGPEncryptionUtil.signAndEncrypt( MESSAGE.getBytes(), signingKey, SECRET_PWD, encryptingKey, true ); PGPSecretKey decryptingSecretKey = PGPEncryptionUtil.findSecretKeyByFingerprint( findFile( SECRET_KEYRING ), PGPEncryptionUtil.BytesToHex( encryptingKey.getFingerprint() ) ); byte[] decryptedAndVerifiedMessage = PGPEncryptionUtil .decryptAndVerify( signedAndEncryptedMessage, decryptingSecretKey, SECRET_PWD, signingKey.getPublicKey() ); assertTrue( Arrays.equals( MESSAGE.getBytes(), decryptedAndVerifiedMessage ) ); }
Example #12
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 #13
Source File: PGPEncryptionUtilTest.java From peer-os with Apache License 2.0 | 6 votes |
@Test public void testGetX509CertificateFromPgpKeyPair() throws Exception { Date today = new Date(); PGPPublicKey pgpPublicKey = PGPEncryptionUtil.findPublicKeyById( findFile( PUBLIC_KEYRING ), PUBLIC_KEY_ID ); PGPSecretKey pgpSecretKey = PGPEncryptionUtil.findSecretKeyById( findFile( SECRET_KEYRING ), SECRET_KEY_ID ); X509Certificate x509Certificate = PGPEncryptionUtil .getX509CertificateFromPgpKeyPair( pgpPublicKey, pgpSecretKey, SECRET_PWD, "C=ZA, ST=Western Cape, L=Cape Town, O=Thawte Consulting cc," + " OU=Certification Services Division," + " CN=Thawte Server CA/[email protected]", "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala," + "OU=FreeSoft, CN=www.freesoft.org/[email protected]", today, new Date( today.getTime() + ( 1000 * 60 * 60 * 24 ) ), new BigInteger( "1" ) ); assertNotNull( x509Certificate ); JcaPGPKeyConverter c = new JcaPGPKeyConverter(); PublicKey publicKey = c.getPublicKey( pgpSecretKey.getPublicKey() ); x509Certificate.verify( publicKey, new BouncyCastleProvider() ); }
Example #14
Source File: KeySerializer.java From nomulus with Apache License 2.0 | 6 votes |
/** * Serialize a PGPKeyPair * * <p>Use this to serialize a PGPPrivateKey as well (pairing it with the corresponding * PGPPublicKey), as private keys can't be serialized on their own. */ public static byte[] serializeKeyPair(PGPKeyPair keyPair) throws IOException, PGPException { try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) { // NOTE: We have to close the ArmoredOutputStream before calling the underlying OutputStream's // "toByteArray". Failing to do so would result in a truncated serialization as we took the // byte array before the ArmoredOutputStream wrote all the data. // // Even "flushing" the ArmoredOutputStream isn't enough - as there are parts that are only // written by the ArmoredOutputStream when it is closed: the "-----END PGP PRIVATE KEY // BLOCK-----" (or similar) footer. try (ArmoredOutputStream out = new ArmoredOutputStream(byteStream)) { new PGPSecretKey( keyPair.getPrivateKey(), keyPair.getPublicKey(), new JcaPGPDigestCalculatorProviderBuilder() .setProvider("BC") .build() .get(HashAlgorithmTags.SHA256), true, null).encode(out); } return byteStream.toByteArray(); } }
Example #15
Source File: PgpHelper.java From nomulus with Apache License 2.0 | 6 votes |
/** * Same as {@link #lookupPublicKey} but also retrieves the associated private key. * * @throws VerifyException if either keys couldn't be found. * @see #lookupPublicKey */ 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(String.format("Could not load PGP private key for: %s", query), e); } return new PGPKeyPair(publicKey, privateKey); }
Example #16
Source File: EncryptionToolImpl.java From peer-os with Apache License 2.0 | 6 votes |
/** * Signs a public key * * @param publicKeyRing a public key ring containing the single public key to sign * @param id the id we are certifying against the public key * @param secretKey the signing key * @param secretKeyPassword the signing key password * * @return a public key ring with the signed public key */ @Override public PGPPublicKeyRing signPublicKey( PGPPublicKeyRing publicKeyRing, String id, PGPSecretKey secretKey, String secretKeyPassword ) { try { if ( StringUtils.isBlank( secretKeyPassword ) ) { secretKeyPassword = keyManager.getSecurityKeyData().getSecretKeyringPwd(); } return PGPEncryptionUtil.signPublicKey( publicKeyRing, id, secretKey, secretKeyPassword ); } catch ( Exception e ) { //throw custom exception throw new ActionFailedException( e ); } }
Example #17
Source File: KeyManagerImpl.java From peer-os with Apache License 2.0 | 5 votes |
@Override public PGPPrivateKey getPrivateKey( String identityId ) { if ( StringUtils.isBlank( identityId ) ) { identityId = keyData.getManHostId(); } try { PGPSecretKey secretKey = getSecretKey( identityId ); if ( secretKey != null ) { return PGPEncryptionUtil.getPrivateKey( secretKey, keyData.getSecretKeyringPwd() ); } else { return null; } } catch ( Exception ex ) { LOG.error( " ***** Error getting Private key:" + ex.toString(), ex ); return null; } }
Example #18
Source File: PgpSigningService.java From packagedrone with Eclipse Public License 1.0 | 5 votes |
private static PGPSecretKey loadKey ( final InputStream keyring, final String keyId ) throws IOException, PGPException { final PGPSecretKey secretKey = PgpHelper.loadSecretKey ( keyring, keyId ); if ( secretKey == null ) { throw new IllegalStateException ( String.format ( "Signing key '%08X' could not be found", keyId ) ); } return secretKey; }
Example #19
Source File: AptSigningFacet.java From nexus-repository-apt with Eclipse Public License 1.0 | 5 votes |
public Content getPublicKey() throws IOException, PGPException { PGPSecretKey signKey = readSecretKey(); PGPPublicKey publicKey = signKey.getPublicKey(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try (BCPGOutputStream os = new BCPGOutputStream(new ArmoredOutputStream(buffer))) { publicKey.encode(os); } return new Content(new BytesPayload(buffer.toByteArray(), AptMimeTypes.PUBLICKEY)); }
Example #20
Source File: KeySerializerTest.java From nomulus with Apache License 2.0 | 5 votes |
private static PGPPrivateKey extractPrivateKey(PGPSecretKey secretKey, String password) { try { return secretKey.extractPrivateKey( new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()) .build(password.toCharArray())); } catch (PGPException e) { throw new Error(e); } }
Example #21
Source File: PgpHelper.java From packagedrone with Eclipse Public License 1.0 | 5 votes |
public static Stream<PGPSecretKey> streamSecretKeys ( final InputStream input ) throws IOException, PGPException { final Stream<PGPSecretKeyRing> s = streamSecretKeyring ( input ); return s.flatMap ( k -> { final Iterator<?> i = k.getSecretKeys (); final Stream<?> ks = StreamSupport.stream ( Spliterators.spliteratorUnknownSize ( i, Spliterator.ORDERED ), false ); return ks.map ( o -> (PGPSecretKey)o ); } ); }
Example #22
Source File: KmsTestHelper.java From nomulus with Apache License 2.0 | 5 votes |
static PGPKeyPair getKeyPair() throws Exception { PGPSecretKey secretKey = getPrivateKeyring().getSecretKey(); return new PGPKeyPair( secretKey.getPublicKey(), secretKey.extractPrivateKey( new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()) .build(new char[0]))); }
Example #23
Source File: KeySerializer.java From nomulus with Apache License 2.0 | 5 votes |
/** Deserialize a PGPKeyPair */ public static PGPKeyPair deserializeKeyPair(byte[] serialized) throws IOException, PGPException { PGPSecretKey secretKey = new BcPGPSecretKeyRing( PGPUtil.getDecoderStream( new ByteArrayInputStream(serialized))).getSecretKey(); return new PGPKeyPair( secretKey.getPublicKey(), secretKey.extractPrivateKey(createSecretKeyDecryptor())); }
Example #24
Source File: GPGFileDecryptor.java From incubator-gobblin with Apache License 2.0 | 5 votes |
/** * Private util function that finds the private key from keyring collection based on keyId and passPhrase * @param pgpSec keyring collection * @param keyID keyID for this encryption file * @param passPhrase passPhrase for this encryption file * @throws PGPException */ private PGPPrivateKey findSecretKey(PGPSecretKeyRingCollection pgpSec, long keyID, String passPhrase) throws PGPException { PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID); if (pgpSecKey == null) { return null; } return pgpSecKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(passPhrase.toCharArray())); }
Example #25
Source File: PGPUtils.java From desktopclient-java with GNU General Public License v3.0 | 5 votes |
static PGPKeyPair decrypt(PGPSecretKey secretKey, PBESecretKeyDecryptor dec) throws KonException { try { return new PGPKeyPair(secretKey.getPublicKey(), secretKey.extractPrivateKey(dec)); } catch (PGPException ex) { LOGGER.log(Level.WARNING, "failed", ex); throw new KonException(KonException.Error.LOAD_KEY_DECRYPT, ex); } }
Example #26
Source File: EncryptionToolImpl.java From peer-os with Apache License 2.0 | 5 votes |
@Override public byte[] clearSign( final byte[] message, final PGPSecretKey secretKey, final String secretPwd ) throws PGPException { try { return PGPEncryptionUtil.clearSign( message, secretKey, secretPwd.toCharArray(), "" ); } catch ( IOException | SignatureException e ) { throw new PGPException( "Error signing message", e ); } }
Example #27
Source File: EncryptionToolImpl.java From peer-os with Apache License 2.0 | 5 votes |
@Override public byte[] signAndEncrypt( final byte[] message, PGPSecretKey secretKey, String secretPwd, final PGPPublicKey publicKey, final boolean armored ) throws PGPException { if ( StringUtils.isBlank( secretPwd ) ) { secretPwd = keyManager.getSecurityKeyData().getSecretKeyringPwd(); } return PGPEncryptionUtil.signAndEncrypt( message, secretKey, secretPwd, publicKey, armored ); }
Example #28
Source File: EncryptionToolImpl.java From peer-os with Apache License 2.0 | 5 votes |
@Override public byte[] decryptAndVerify( final byte[] message, final String secretKeyHostId, final String pwd, final String publicKeyHostId ) throws PGPException { PGPSecretKey secKey = keyManager.getSecretKeyRing( secretKeyHostId ).getSecretKey(); PGPPublicKey pubKey = keyManager.getPublicKey( publicKeyHostId ); return PGPEncryptionUtil.decryptAndVerify( message, secKey, pwd, pubKey ); }
Example #29
Source File: OpenPgpManager.java From Smack with Apache License 2.0 | 5 votes |
/** * Fetch a secret key backup from the server and try to restore a selected secret key from it. * * @param codeCallback callback for prompting the user to provide the secret backup code. * @return fingerprint of the restored secret key * * @throws InterruptedException if the thread gets interrupted. * @throws PubSubException.NotALeafNodeException if the private node is not a {@link LeafNode}. * @throws XMPPException.XMPPErrorException in case of an XMPP protocol error. * @throws SmackException.NotConnectedException if we are not connected. * @throws SmackException.NoResponseException if the server doesn't respond. * @throws InvalidBackupCodeException if the user-provided backup code is invalid. * @throws SmackException.NotLoggedInException if we are not logged in * @throws IOException IO is dangerous * @throws MissingUserIdOnKeyException if the key that is to be imported is missing a user-id with our jid * @throws NoBackupFoundException if no secret key backup has been found * @throws PGPException in case the restored secret key is damaged. */ public OpenPgpV4Fingerprint restoreSecretKeyServerBackup(AskForBackupCodeCallback codeCallback) throws InterruptedException, PubSubException.NotALeafNodeException, XMPPException.XMPPErrorException, SmackException.NotConnectedException, SmackException.NoResponseException, InvalidBackupCodeException, SmackException.NotLoggedInException, IOException, MissingUserIdOnKeyException, NoBackupFoundException, PGPException { throwIfNoProviderSet(); throwIfNotAuthenticated(); SecretkeyElement backup = OpenPgpPubSubUtil.fetchSecretKey(pepManager); if (backup == null) { throw new NoBackupFoundException(); } String backupCode = codeCallback.askForBackupCode(); PGPSecretKeyRing secretKeys = SecretKeyBackupHelper.restoreSecretKeyBackup(backup, backupCode); provider.getStore().importSecretKey(getJidOrThrow(), secretKeys); provider.getStore().importPublicKey(getJidOrThrow(), BCUtil.publicKeyRingFromSecretKeyRing(secretKeys)); ByteArrayOutputStream buffer = new ByteArrayOutputStream(2048); for (PGPSecretKey sk : secretKeys) { PGPPublicKey pk = sk.getPublicKey(); if (pk != null) pk.encode(buffer); } PGPPublicKeyRing publicKeys = new PGPPublicKeyRing(buffer.toByteArray(), new BcKeyFingerprintCalculator()); provider.getStore().importPublicKey(getJidOrThrow(), publicKeys); return new OpenPgpV4Fingerprint(secretKeys); }
Example #30
Source File: AptSigningFacet.java From nexus-repository-apt with Eclipse Public License 1.0 | 5 votes |
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(); }