org.bouncycastle.openpgp.PGPPublicKey Java Examples
The following examples show how to use
org.bouncycastle.openpgp.PGPPublicKey.
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: SecurityManagerImpl.java From peer-os with Apache License 2.0 | 6 votes |
@Override public String signNEncryptRequestToHost( final String message, final String hostId ) throws PGPException { //obtain target host pub key for encrypting PGPPublicKey hostKeyForEncrypting = keyManager.getPublicKey( hostId ); if ( hostKeyForEncrypting == null ) { throw new PGPException( String.format( "Public key not found by host id %s", hostId ) ); } String encryptedRequestString = new String( encryptionTool.signAndEncrypt( message.getBytes(), hostKeyForEncrypting, true ) ); EncryptedRequestWrapper encryptedRequestWrapper = new EncryptedRequestWrapper( encryptedRequestString, hostId ); return JsonUtil.toJson( encryptedRequestWrapper ); }
Example #2
Source File: RydeEncoder.java From nomulus with Apache License 2.0 | 6 votes |
private RydeEncoder( OutputStream rydeOutput, OutputStream sigOutput, long dataLength, String filenamePrefix, DateTime modified, PGPKeyPair signingKey, Collection<PGPPublicKey> receiverKeys) { super(null); this.sigOutput = sigOutput; signer = closer.register(new RydePgpSigningOutputStream(checkNotNull(rydeOutput), signingKey)); OutputStream encryptLayer = closer.register(openEncryptor(signer, RYDE_USE_INTEGRITY_PACKET, receiverKeys)); OutputStream kompressor = closer.register(openCompressor(encryptLayer)); OutputStream fileLayer = closer.register(openPgpFileWriter(kompressor, filenamePrefix + ".tar", modified)); OutputStream tarLayer = closer.register(openTarWriter(fileLayer, dataLength, filenamePrefix + ".xml", modified)); this.out = tarLayer; }
Example #3
Source File: PGPKeyUtil.java From peer-os with Apache License 2.0 | 6 votes |
public static PGPPublicKey readPublicKey( PGPPublicKeyRing keyRing ) throws PGPException { try { Iterator keyIter = keyRing.getPublicKeys(); while ( keyIter.hasNext() ) { PGPPublicKey key = ( PGPPublicKey ) keyIter.next(); if ( key.isEncryptionKey() ) { return key; } } } catch ( Exception e ) { LOG.error( e.getMessage() ); } return null; }
Example #4
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 #5
Source File: Ghostryde.java From nomulus with Apache License 2.0 | 6 votes |
/** * Creates a Ghostryde Encoder. * * <p>Optionally can also save the total length of the data written to an OutputStream. * * <p>This is necessary because the RyDE format uses a tar file which requires the total length in * the header. We don't want to have to decrypt the entire ghostryde file to determine the length, * so we just save it separately. * * @param output where to write the encrypted data * @param encryptionKey the encryption key to use * @param lengthOutput if not null - will save the total length of the data written to this * output. See {@link #readLength}. */ public static ImprovedOutputStream encoder( OutputStream output, PGPPublicKey encryptionKey, @Nullable OutputStream lengthOutput) { // We use a Closer to handle the stream .close, to make sure it's done correctly. Closer closer = Closer.create(); OutputStream encryptionLayer = closer.register( openEncryptor(output, GHOSTRYDE_USE_INTEGRITY_PACKET, ImmutableList.of(encryptionKey))); OutputStream kompressor = closer.register(openCompressor(encryptionLayer)); OutputStream fileLayer = closer.register(openPgpFileWriter(kompressor, INNER_FILENAME, INNER_MODIFICATION_TIME)); return new ImprovedOutputStream("GhostrydeEncoder", fileLayer) { @Override public void onClose() throws IOException { // Close all the streams we opened closer.close(); // Optionally also output the size of the encoded data - which is needed for the RyDE // encoding. if (lengthOutput != null) { lengthOutput.write(Long.toString(getBytesWritten()).getBytes(US_ASCII)); } } }; }
Example #6
Source File: PeerManagerImpl.java From peer-os with Apache License 2.0 | 6 votes |
private void setApprovedResult( final RegistrationData result, final String keyPhrase ) { String sslCert = securityManager.getKeyStoreManager().exportCertificate( Common.DEFAULT_PUBLIC_SECURE_PORT, "" ); PGPPublicKey pkey = securityManager.getKeyManager().getPublicKey( localPeerId ); try { byte[] key = SecurityUtilities.generateKey( keyPhrase.getBytes( StandardCharsets.UTF_8 ) ); Encrypted encryptedSslCert = new Encrypted( sslCert, key ); result.setSslCert( encryptedSslCert ); String publicKey = PGPKeyUtil.exportAscii( pkey ); Encrypted encryptedPublicKey = new Encrypted( publicKey, key ); result.setPublicKey( encryptedPublicKey ); } catch ( Exception e ) { LOG.warn( e.getMessage(), e ); } }
Example #7
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 #8
Source File: KeyManagerImpl.java From peer-os with Apache License 2.0 | 6 votes |
@Override public PGPPublicKey getRemoteHostPublicKey( final String hostIdTarget ) { try { PGPPublicKeyRing pubRing; pubRing = getPublicKeyRing( hostIdTarget ); if ( pubRing != null ) { return PGPKeyUtil.readPublicKey( pubRing ); } } catch ( Exception ex ) { // ignore } return null; }
Example #9
Source File: PGPVerifyMojo.java From pgpverify-maven-plugin with Apache License 2.0 | 6 votes |
private boolean verifySignatureStatus(boolean signatureStatus, Artifact artifact, PGPPublicKey publicKey, PGPPublicKeyRing publicKeyRing) { if (signatureStatus) { logWithQuiet.accept(() -> String.format(PGP_VERIFICATION_RESULT_FORMAT, artifact.getId(), "OK", PublicKeyUtils.keyIdDescription(publicKey, publicKeyRing), PublicKeyUtils.getUserIDs(publicKey, publicKeyRing))); return true; } else if (keysMap.isBrokenSignature(artifact)) { logWithQuiet.accept(() -> String.format("%s PGP Signature is broken, consistent with keys map.", artifact.getId())); return true; } getLog().error(String.format(PGP_VERIFICATION_RESULT_FORMAT, artifact.getId(), "INVALID", PublicKeyUtils.keyIdDescription(publicKey, publicKeyRing), PublicKeyUtils.getUserIDs(publicKey, publicKeyRing))); return false; }
Example #10
Source File: EncryptionToolImpl.java From peer-os with Apache License 2.0 | 5 votes |
@Override public byte[] encrypt( final byte[] message, final PGPPublicKey publicKey, boolean armored ) { try { return PGPEncryptionUtil.encrypt( message, publicKey, armored ); } catch ( Exception ex ) { return ArrayUtils.EMPTY_BYTE_ARRAY; } }
Example #11
Source File: GhostrydeTest.java From nomulus with Apache License 2.0 | 5 votes |
@Theory public void testFailure_tampering(Content content) throws Exception { assumeThat(content.get().length(), is(greaterThan(100))); Keyring keyring = new FakeKeyringModule().get(); PGPPublicKey publicKey = keyring.getRdeStagingEncryptionKey(); PGPPrivateKey privateKey = keyring.getRdeStagingDecryptionKey(); byte[] data = content.get().getBytes(UTF_8); ByteArrayOutputStream bsOut = new ByteArrayOutputStream(); try (OutputStream encoder = Ghostryde.encoder(bsOut, publicKey)) { encoder.write(data); } byte[] ciphertext = bsOut.toByteArray(); korruption(ciphertext, ciphertext.length - 1); ByteArrayInputStream bsIn = new ByteArrayInputStream(ciphertext); IllegalStateException thrown = assertThrows( IllegalStateException.class, () -> { try (InputStream decoder = Ghostryde.decoder(bsIn, privateKey)) { ByteStreams.copy(decoder, ByteStreams.nullOutputStream()); } }); assertThat(thrown).hasMessageThat().contains("tampering"); }
Example #12
Source File: PGPEncryptionUtil.java From peer-os with Apache License 2.0 | 5 votes |
public static byte[] signAndEncrypt( final byte[] message, final PGPSecretKey secretKey, final String secretPwd, final PGPPublicKey publicKey, final boolean armored ) throws PGPException { try { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator( new JcePGPDataEncryptorBuilder( SymmetricKeyAlgorithmTags.AES_256 ).setWithIntegrityPacket( true ) .setSecureRandom( new SecureRandom() ) .setProvider( provider ) ); encryptedDataGenerator.addMethod( new JcePublicKeyKeyEncryptionMethodGenerator( publicKey ).setSecureRandom( new SecureRandom() ) .setProvider( provider ) ); final OutputStream theOut = armored ? new ArmoredOutputStream( out ) : out; final OutputStream encryptedOut = encryptedDataGenerator.open( theOut, new byte[4096] ); final PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator( CompressionAlgorithmTags.ZIP ); final OutputStream compressedOut = compressedDataGenerator.open( encryptedOut, new byte[4096] ); final PGPPrivateKey privateKey = secretKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider( provider ).build( secretPwd.toCharArray() ) ); final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder( secretKey.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1 ) .setProvider( provider ) ); signatureGenerator.init( PGPSignature.BINARY_DOCUMENT, privateKey ); final Iterator<?> it = secretKey.getPublicKey().getUserIDs(); if ( it.hasNext() ) { final PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); spGen.setSignerUserID( false, ( String ) it.next() ); signatureGenerator.setHashedSubpackets( spGen.generate() ); } signatureGenerator.generateOnePassVersion( false ).encode( compressedOut ); final PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator(); final OutputStream literalOut = literalDataGenerator .open( compressedOut, PGPLiteralData.BINARY, "filename", new Date(), new byte[4096] ); final InputStream in = new ByteArrayInputStream( message ); final byte[] buf = new byte[4096]; for ( int len; ( len = in.read( buf ) ) > 0; ) { literalOut.write( buf, 0, len ); signatureGenerator.update( buf, 0, len ); } in.close(); literalDataGenerator.close(); signatureGenerator.generate().encode( compressedOut ); compressedDataGenerator.close(); encryptedDataGenerator.close(); theOut.close(); return out.toByteArray(); } catch ( Exception e ) { throw new PGPException( "Error in signAndEncrypt", e ); } }
Example #13
Source File: KeyManagerImpl.java From peer-os with Apache License 2.0 | 5 votes |
@Override public PGPPublicKey getRemoteHostPublicKey( PeerInfo peerInfo ) { try { PGPPublicKeyRing pubRing; pubRing = getPublicKeyRing( peerInfo.getId() ); if ( pubRing == null ) // Get from HTTP { String baseUrl = String.format( "%s/rest/v1", peerInfo.getPublicUrl() ); WebClient client = RestUtil.createTrustedWebClient( baseUrl ); client.type( MediaType.MULTIPART_FORM_DATA ).accept( MediaType.TEXT_PLAIN ); Response response = client.path( "security/keyman/getpublickeyring" ).query( "hostid", peerInfo.getId() ).get(); if ( response.getStatus() == Response.Status.OK.getStatusCode() ) { String publicKeyring = response.readEntity( String.class ); savePublicKeyRing( peerInfo.getId(), SecurityKeyType.PEER_KEY.getId(), publicKeyring ); } RestUtil.close( response ); RestUtil.close( client ); return getPublicKey( peerInfo.getId() ); } else { return PGPKeyUtil.readPublicKey( pubRing ); } } catch ( Exception ex ) { return null; } }
Example #14
Source File: KontalkKeyring.java From tigase-extension with GNU General Public License v3.0 | 5 votes |
/** * Imports the given revoked key and checks if fingerprint matches and * key is revoked correctly. */ public boolean revoked(byte[] keyData, String fingerprint) throws IOException, PGPException { PGPPublicKeyRing key = keyring.importKey(keyData); PGPPublicKey masterKey = PGPUtils.getMasterKey(key); return masterKey != null && PGPUtils.isRevoked(masterKey) && Arrays.equals(Utils.parseHexBinary(fingerprint), masterKey.getFingerprint()); }
Example #15
Source File: OpenPGPKeyBasedEncryptor.java From localization_nifi with Apache License 2.0 | 5 votes |
@SuppressWarnings("rawtypes") public static PGPPublicKey getPublicKey(String userId, String publicKeyringFile) throws IOException, PGPException { // TODO: Reevaluate the mechanism for executing this task as performance can suffer here and only a specific key needs to be validated // Read in from the public keyring file try (FileInputStream keyInputStream = new FileInputStream(publicKeyringFile)) { // Form the PublicKeyRing collection (1.53 way with fingerprint calculator) PGPPublicKeyRingCollection pgpPublicKeyRingCollection = new PGPPublicKeyRingCollection(keyInputStream, new BcKeyFingerprintCalculator()); // Iterate over all public keyrings Iterator<PGPPublicKeyRing> iter = pgpPublicKeyRingCollection.getKeyRings(); PGPPublicKeyRing keyRing; while (iter.hasNext()) { keyRing = iter.next(); // Iterate over each public key in this keyring Iterator<PGPPublicKey> keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext()) { PGPPublicKey publicKey = keyIter.next(); // Iterate over each userId attached to the public key Iterator userIdIterator = publicKey.getUserIDs(); while (userIdIterator.hasNext()) { String id = (String) userIdIterator.next(); if (userId.equalsIgnoreCase(id)) { return publicKey; } } } } } // If this point is reached, no public key could be extracted with the given userId throw new PGPException("Could not find a public key with the given userId"); }
Example #16
Source File: MessageContentUtilTest.java From peer-os with Apache License 2.0 | 5 votes |
@Test public void testEncryptContent() throws Exception { doReturn( new ByteArrayInputStream( "OK".getBytes() ) ).when( cachedOutputStream ).getInputStream(); doReturn( pgpPublicKey ).when( keyManager ).getRemoteHostPublicKey( anyString() ); doReturn( "OK".getBytes() ).when( encryptionTool ) .encrypt( isA( byte[].class ), isA( PGPPublicKey.class ), eq( true ) ); MessageContentUtil.encryptContent( securityManager, SRC, TARGET, message ); verify( encryptionTool ).encrypt( isA( byte[].class ), eq( pgpPublicKey ), eq( true ) ); }
Example #17
Source File: RydeEncoder.java From nomulus with Apache License 2.0 | 5 votes |
/** Sets the OutputStream for the Ryde-encoded data, and the keys used for the encryption. */ public Builder setRydeOutput( OutputStream rydeOutput, PGPPublicKey receiverKey, PGPPublicKey... moreReceiverKeys) { this.rydeOutput = rydeOutput; this.receiverKeys = new ImmutableList.Builder<PGPPublicKey>().add(receiverKey).add(moreReceiverKeys).build(); return this; }
Example #18
Source File: PGPUtils.java From desktopclient-java with GNU General Public License v3.0 | 5 votes |
private static int getKeyFlags(PGPPublicKey key) { @SuppressWarnings("unchecked") Iterator<PGPSignature> sigs = key.getSignatures(); while (sigs.hasNext()) { PGPSignature sig = sigs.next(); PGPSignatureSubpacketVector subpackets = sig.getHashedSubPackets(); if (subpackets != null) return subpackets.getKeyFlags(); } return 0; }
Example #19
Source File: GhostrydeTest.java From nomulus with Apache License 2.0 | 5 votes |
@Theory public void testSimpleApi(Content content) throws Exception { Keyring keyring = new FakeKeyringModule().get(); byte[] data = content.get().getBytes(UTF_8); PGPPublicKey publicKey = keyring.getRdeStagingEncryptionKey(); PGPPrivateKey privateKey = keyring.getRdeStagingDecryptionKey(); byte[] blob = Ghostryde.encode(data, publicKey); byte[] result = Ghostryde.decode(blob, privateKey); assertThat(new String(result, UTF_8)).isEqualTo(content.get()); }
Example #20
Source File: PGPEncryptionUtil.java From peer-os with Apache License 2.0 | 5 votes |
public static PGPPublicKey findPublicKeyById( InputStream publicKeyRing, String keyId ) throws PGPException { try { return findPublicKey( publicKeyRing, keyId, false ); } catch ( Exception e ) { throw new PGPException( "Error in findPublicKeyById", e ); } }
Example #21
Source File: EncryptionToolImpl.java From peer-os with Apache License 2.0 | 5 votes |
@Override public byte[] signAndEncrypt( final byte[] message, final PGPPublicKey publicKey, final boolean armored ) throws PGPException { return PGPEncryptionUtil.signAndEncrypt( message, keyManager.getSecretKey( null ), keyManager.getSecurityKeyData().getSecretKeyringPwd(), publicKey, armored ); }
Example #22
Source File: PGPKeyHelperTest.java From peer-os with Apache License 2.0 | 5 votes |
@Test public void testReadPublicKeyFromString_success() throws IOException, PGPException { String str = FileUtils.readFileToString( new File( PGPTestDataFactory.PUBLIC_KEY_PATH ) ); PGPPublicKey publicKey = PGPKeyHelper.readPublicKeyFromString( str ); assertNotNull( publicKey ); }
Example #23
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 #24
Source File: KeysMap.java From pgpverify-maven-plugin with Apache License 2.0 | 5 votes |
public boolean isValidKey(Artifact artifact, PGPPublicKey key, PGPPublicKeyRing keyRing) { if (keysMapList.isEmpty()) { return true; } return keysMapList.stream() .filter(artifactInfo -> artifactInfo.isMatch(artifact)) .anyMatch(artifactInfo -> artifactInfo.isKeyMatch(key, keyRing)); }
Example #25
Source File: PGPKeyHelperTest.java From peer-os with Apache License 2.0 | 5 votes |
private static void checkPublicKey( PGPPublicKey publicKey ) { assertNotNull( publicKey ); assertTrue( PGPKeyHelper.getOwnerString( publicKey ).contains( PGPTestDataFactory.PUBLIC_KEY_OWNER ) ); assertEquals( PGPTestDataFactory.PUBLIC_KEY_FIGNERPRINT, PGPKeyHelper.getFingerprint( publicKey ) ); }
Example #26
Source File: PGPSignatureUtilTest.java From peer-os with Apache License 2.0 | 5 votes |
@Test( expected = IllegalArgumentException.class ) public void testMergeSignatures_withDifferentPubKeys() throws Exception { PGPPublicKey alicePuKey = PGPTestDataFactory.getPublicKey( "alice" ); PGPPublicKey applePubKey = PGPTestDataFactory.getPublicKey( "apple" ); PGPSignatureUtil.mergeSignatures( alicePuKey, applePubKey ); }
Example #27
Source File: EncryptionToolImpl.java From peer-os with Apache License 2.0 | 5 votes |
@Override public PGPPublicKeyRing removeSignature( final PGPPublicKey keySignToRemove, final PGPPublicKeyRing keyToRemoveFrom ) { try { return PGPEncryptionUtil.removeSignature( keyToRemoveFrom, keySignToRemove ); } catch ( Exception e ) { //throw custom exception throw new ActionFailedException( e ); } }
Example #28
Source File: PGPSignVerifyTest.java From peer-os with Apache License 2.0 | 5 votes |
@Test( expected = PGPDataValidationException.class ) public void testFail() throws Exception { PGPPrivateKey privateKey = PGPTestDataFactory.getPrivateKey( "alice" ); // Give wrong key for validation PGPPublicKey publicKey = PGPTestDataFactory.getPublicKey( "bobby" ); test( PGPTestDataFactory.getData(), privateKey, publicKey ); }
Example #29
Source File: OpenPGPKeyBasedEncryptor.java From nifi with Apache License 2.0 | 5 votes |
@SuppressWarnings("rawtypes") public static PGPPublicKey getPublicKey(String userId, String publicKeyringFile) throws IOException, PGPException { // TODO: Reevaluate the mechanism for executing this task as performance can suffer here and only a specific key needs to be validated // Read in from the public keyring file try (FileInputStream keyInputStream = new FileInputStream(publicKeyringFile)) { // Form the PublicKeyRing collection (1.53 way with fingerprint calculator) PGPPublicKeyRingCollection pgpPublicKeyRingCollection = new PGPPublicKeyRingCollection(keyInputStream, new BcKeyFingerprintCalculator()); // Iterate over all public keyrings Iterator<PGPPublicKeyRing> iter = pgpPublicKeyRingCollection.getKeyRings(); PGPPublicKeyRing keyRing; while (iter.hasNext()) { keyRing = iter.next(); // Iterate over each public key in this keyring Iterator<PGPPublicKey> keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext()) { PGPPublicKey publicKey = keyIter.next(); // Iterate over each userId attached to the public key Iterator userIdIterator = publicKey.getUserIDs(); while (userIdIterator.hasNext()) { String id = (String) userIdIterator.next(); if (userId.equalsIgnoreCase(id)) { return publicKey; } } } } } // If this point is reached, no public key could be extracted with the given userId throw new PGPException("Could not find a public key with the given userId"); }
Example #30
Source File: GhostrydeTest.java From nomulus with Apache License 2.0 | 5 votes |
@Test public void testFailure_keyMismatch() throws Exception { FakeKeyringModule keyringModule = new FakeKeyringModule(); byte[] data = "Fanatics have their dreams, wherewith they weave.".getBytes(UTF_8); PGPKeyPair dsa1 = keyringModule.get("[email protected]", ENCRYPT); PGPKeyPair dsa2 = keyringModule.get("[email protected]", ENCRYPT); PGPPublicKey publicKey = dsa1.getPublicKey(); PGPPrivateKey privateKey = dsa2.getPrivateKey(); ByteArrayOutputStream bsOut = new ByteArrayOutputStream(); try (OutputStream encoder = Ghostryde.encoder(bsOut, publicKey)) { encoder.write(data); } ByteArrayInputStream bsIn = new ByteArrayInputStream(bsOut.toByteArray()); RuntimeException thrown = assertThrows( RuntimeException.class, () -> { try (InputStream decoder = Ghostryde.decoder(bsIn, privateKey)) { ByteStreams.copy(decoder, ByteStreams.nullOutputStream()); } }); assertThat(thrown).hasCauseThat().isInstanceOf(PGPException.class); assertThat(thrown) .hasCauseThat() .hasMessageThat() .contains( "Message was encrypted for keyids [a59c132f3589a1d5] but ours is c9598c84ec70b9fd"); }