public static void writeData(List<Calendar> data) throws Exception { List<PGPPublicKey> pubKeys = new ArrayList<PGPPublicKey>(); pubKeys.add(ppk); pubKeys.add(davidPub); try { if (!dataFile.exists()) dataFile.createNewFile(); DataXMLParser.writeData(dataFile, data, pubKeys); } catch (Exception e) { Main.logger.error("Error while writing data!", e); throw e; } }
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."); }
/** * Returns information on a public key * @param key A PGP public key * @return Key information */ public static String getKeyInfo(PGPPublicKey key) { StringBuffer info = new StringBuffer(PGPInit.getKeyExchangeAlgorithm(key.getAlgorithm())) .append(" (").append(key.getBitStrength()).append(")") .append(" v").append(key.getVersion()) .append(" id:").append(key.getKeyID()) .append(" ").append(key.getCreationTime()); if (key.isEncryptionKey()) { info.append(" [").append("encryption").append("]"); } if (key.isMasterKey()) { info.append(" [").append("master").append("]"); } if (key.isRevoked()) { info.append(" [").append("revoked").append("]"); } return info.toString(); }
/** * Verify a signature. Only return true if signature matches calculated signature of signedData * and if it was signed by the publicKey * * @param signedData * @param signature * @return */ public boolean verify(InputStream signedData, InputStream signature) { try { signature = PGPUtil.getDecoderStream(signature); JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(signature); PGPSignature sig = ((PGPSignatureList) pgpFact.nextObject()).get(0); PGPPublicKey key = pgpPubRingCollection.getPublicKey(sig.getKeyID()); sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), key); byte[] buff = new byte[1024]; int read = 0; while ((read = signedData.read(buff)) != -1) { sig.update(buff, 0, read); } signedData.close(); return sig.verify(); } catch (Exception ex) { // can we put a logger here please? return false; } }
@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); } }
private void test11() throws Exception { PGPPublicKeyRing pubRing = new PGPPublicKeyRing(subKeyBindingKey, new BcKeyFingerprintCalculator()); Iterator it = pubRing.getPublicKeys(); while (it.hasNext()) { PGPPublicKey key = (PGPPublicKey)it.next(); if (key.getValidSeconds() != 0) { fail("expiration time non-zero"); } } }
@Theory public void testEncryptOnly(Content content) throws Exception { Keyring keyring = new FakeKeyringModule().get(); byte[] data = content.get().getBytes(UTF_8); PGPPublicKey publicKey = keyring.getRdeStagingEncryptionKey(); PGPPrivateKey privateKey = keyring.getRdeStagingDecryptionKey(); Ghostryde ghost = new Ghostryde(1024); ByteArrayOutputStream bsOut = new ByteArrayOutputStream(); try (Ghostryde.Encryptor encryptor = ghost.openEncryptor(bsOut, publicKey)) { encryptor.write(data); } ByteArrayInputStream bsIn = new ByteArrayInputStream(bsOut.toByteArray()); bsOut.reset(); try (Ghostryde.Decryptor decryptor = ghost.openDecryptor(bsIn, privateKey)) { ByteStreams.copy(decryptor, bsOut); } assertThat(new String(bsOut.toByteArray(), UTF_8)).isEqualTo(content.get()); }
/** * 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; } }
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( "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 ); } }
/** * Verifies that a public key is signed with another public key * * @param keyToVerify the public key to verify * @param id the id we are verifying against the public key * @param keyToVerifyWith the key to verify with * * @return true if verified, false otherwise */ public static boolean verifyPublicKey( PGPPublicKey keyToVerify, String id, PGPPublicKey keyToVerifyWith ) throws PGPException { try { Iterator<PGPSignature> signIterator = keyToVerify.getSignatures(); while ( signIterator.hasNext() ) { PGPSignature signature = signIterator.next(); signature.init( new JcaPGPContentVerifierBuilderProvider().setProvider( provider ), keyToVerifyWith ); if ( signature.verifyCertification( id.getBytes(), keyToVerify ) ) { return true; } } return false; } catch ( Exception e ) { //throw custom exception throw new PGPException( "Error verifying public key", e ); } }
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 ); } }
@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 ) ); }
public static PGPPublicKey readPublicKey( InputStream is ) throws IOException, PGPException { PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream( is ), new JcaKeyFingerprintCalculator() ); 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." ); }
/** * Simply stores the key ID in {@link #discoveredKeyIds} for future * reference of all Key IDs we've come across. This method uses a * {@link PGPPublicKeyRing} to ensure the input is actually a valid key, * plus locating any key IDs that have signed the key. * <p> * Please note {@link #discoveredKeyIds} is not used for any key functions * of this class. It is simply for user interface convenience. * * @param keyRing the key ID to store (required) */ @SuppressWarnings("unchecked") private void rememberKey(final PGPPublicKeyRing keyRing) { final PGPPublicKey key = keyRing.getPublicKey(); if (key != null) { final PgpKeyId keyId = new PgpKeyId(key); discoveredKeyIds.add(keyId); final Iterator<String> userIdIterator = key.getUserIDs(); while (userIdIterator.hasNext()) { final String userId = userIdIterator.next(); final Iterator<PGPSignature> signatureIterator = key .getSignaturesForID(userId); while (signatureIterator.hasNext()) { final PGPSignature signature = signatureIterator.next(); final PgpKeyId signatureKeyId = new PgpKeyId(signature); discoveredKeyIds.add(signatureKeyId); } } } }
@Override public Response getPublicKeyId( final String identityId ) { try { PGPPublicKeyRing pubRing = securityManager.getKeyManager().getPublicKeyRing( identityId ); PGPPublicKey key = pubRing.getPublicKey(); if ( key == null ) { logger.info( " ************* Public Key not found with id:" + identityId ); return Response.status( Response.Status.NOT_FOUND ).entity( "Object Not found" ).build(); } else { return Response.ok( PGPKeyUtil.encodeNumericKeyId( key.getKeyID() ) ).build(); } } catch ( Exception ex ) { logger.info( " ************* Error ! Public Key not found with id:" + identityId, ex ); return Response.status( Response.Status.NOT_FOUND ).entity( "Object Not found" ).build(); } }
@Override public boolean isKeyTrustedForURI(String uri, PGPPublicKey publicKey) { LOG.info("isValidKey({}, {}) ?", uri, String.format("0x%X", publicKey.getKeyID())); String fingerprint = Hex.toHexString(publicKey.getFingerprint()).toUpperCase(Locale.US); LOG.info("fingerprint: {}", fingerprint); String allowedPath = properties.getProperty(FINGERPRINT_PREFIX + "." + fingerprint); if (allowedPath == null) { LOG.info("No entry for {}", fingerprint); return false; } else { boolean allowed = false; String[] paths = allowedPath.split(","); for (String path : paths) { if (uri.startsWith(path)) { allowed = true; break; } } return allowed; } }
@Override public PGPPublicKey getPublicKey( String identityId ) { PGPPublicKeyRing publicKeyRing; try { publicKeyRing = getPublicKeyRing( identityId ); if ( publicKeyRing != null ) { return PGPKeyUtil.readPublicKey( publicKeyRing ); } else { LOG.info( "********* Public key not found with identityId:" + identityId ); return null; } } catch ( PGPException e ) { return null; } }
/** * 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."); }
@Override protected Void doInBackground() throws Exception { Main.logger.info("Neue Schlüssel werden generiert..."); PGPKeyRingGenerator pkg = RSAGen.generateKeyRingGenerator(mail, pass, this); PGPPublicKeyRing pkr = pkg.generatePublicKeyRing(); PGPSecretKeyRing skr = pkg.generateSecretKeyRing(); Main.psk = skr.getSecretKey(); Iterator<PGPPublicKey> rIt = pkr.getPublicKeys(); // Sucht den Verschlüsselungsschlüssel while (Main.ppk == null && rIt.hasNext()) { PGPPublicKey temp_key = rIt.next(); if (temp_key.isEncryptionKey()) { Main.ppk = temp_key; break; } } PBESecretKeyDecryptor secretKeyDecryptor = new JcePBESecretKeyDecryptorBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(pass); Main.pprk = Main.psk.extractPrivateKey(secretKeyDecryptor); setProgress(90); // Speichern der Schlüssel PGPSecretKeyRing pskr = pkg.generateSecretKeyRing(); ArmoredOutputStream secout = new ArmoredOutputStream( new BufferedOutputStream(new FileOutputStream(Main.secKey))); // Geheimer Schlüssel pskr.encode(secout); secout.close(); ArmoredOutputStream pubout = new ArmoredOutputStream( new BufferedOutputStream(new FileOutputStream(Main.pubKey))); pkr.encode(pubout); pubout.close(); setProgress(100); return null; }
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 String getKeyInfo(PGPPublicKeyRingCollection coll) { StringBuffer info = new StringBuffer(); // Iterate through key rings Iterator<?> rings = coll.getKeyRings(); while (rings.hasNext()) { PGPPublicKeyRing ring = (PGPPublicKeyRing)rings.next(); Iterator<?> keys = ring.getPublicKeys(); while (keys.hasNext()) { info.append(getKeyInfo((PGPPublicKey)keys.next())).append("\n"); } } return info.toString(); }
/** Returns {@code true} if this key can be used for signing. */ public static boolean isSigningKey(PGPPublicKey key) { switch (key.getAlgorithm()) { case RSA_GENERAL: case RSA_SIGN: case DSA: case ELGAMAL_GENERAL: return true; default: return false; } }
protected PGPOnePassSignature getSignature(Exchange exchange, PGPOnePassSignatureList signatureList) throws Exception { if (SIGNATURE_VERIFICATION_OPTION_IGNORE.equals(getSignatureVerificationOption())) { return null; } if (SIGNATURE_VERIFICATION_OPTION_NO_SIGNATURE_ALLOWED.equals(getSignatureVerificationOption())) { throw new PGPException( "PGP message contains a signature although a signature is not expected. Either change the configuration of the PGP decryptor or send a PGP message with no signature."); } List<String> allowedUserIds = determineSignaturenUserIds(exchange); for (int i = 0; i < signatureList.size(); i++) { PGPOnePassSignature signature = signatureList.get(i); // Determine public key from signature keyId PGPPublicKey sigPublicKey = publicKeyAccessor.getPublicKey(exchange, signature.getKeyID(), allowedUserIds); if (sigPublicKey == null) { continue; } // choose that signature for which a public key exists! signature.init(new JcaPGPContentVerifierBuilderProvider().setProvider(getProvider()), sigPublicKey); return signature; } if (signatureList.isEmpty()) { return null; } else { throw new IllegalArgumentException("Cannot verify the PGP signature: No public key found for the key ID(s) contained in the PGP signature(s). " + "Either the received PGP message contains a signature from an unexpected sender or the Public Keyring does not contain the public key of the sender."); } }
/** * Builds a PublicKeyKeyEncryptionMethodGenerator * for the specified key. */ protected PublicKeyKeyEncryptionMethodGenerator buildPublicKeyEncryptor( Key key) { if (log.isLoggable(Level.INFO)) log.info("using encryption key " + key.getEncryption()); PGPPublicKey publicKey = key.getEncryption().getPublicKey(); return new BcPublicKeyKeyEncryptionMethodGenerator(publicKey); }
protected Key newKey(PGPPublicKeyRing ring) throws PGPException { ArrayList<Subkey> subkeys = new ArrayList<Subkey>(); Iterator<PGPPublicKey> i = ring.iterator(); while (i.hasNext()) subkeys.add(newSubkey(i.next())); return newKey(subkeys); }
private String readKeyText( PGPPublicKey key ) throws HubManagerException { try { return PGPEncryptionUtil.armorByteArrayToString( key.getEncoded() ); } catch ( PGPException | IOException e ) { throw new HubManagerException( "Error to read PGP key as text", e ); } }
public boolean isKeyMatch(PGPPublicKey pgpPublicKeyey) { if (matchAny) { return true; } byte[] fingerprint = pgpPublicKeyey.getFingerprint(); for (byte[] keyBytes : keysID) { if (compareArrays(keyBytes, fingerprint)) { return true; } } return false; }
@Override public Collection<String> getTrustedURIs(PGPPublicKey publicKey) { String fingerprint = Hex.toHexString(publicKey.getFingerprint()).toUpperCase(Locale.US); LOG.info("fingerprint: {}", fingerprint); String allowedPath = properties.getProperty(FINGERPRINT_PREFIX + "." + fingerprint); return allowedPath == null ? Collections.emptyList() : Arrays.asList(allowedPath); }
/** * Reads the public key from the specified key file. * * @param in - Stream pointing to key store. * @param fingerPrintCalculator - An alogrithm to be used for fingerprint calculation. * This sample uses BcKeyFingerprintCalculator algorithm. * @return Returns a public key read from the specified key file. * @throws IOException * @throws PGPException * @throws CryptDecryptException */ private PGPPublicKey readPublicKey() throws IOException, PGPException, CryptDecryptException { if(enableDebugLog)Trace.logInfo("CryptDecryptUtil.readPublicKey", "Entry"); PGPPublicKey publicKey = null; InputStream publicKeyStream = new FileInputStream(keyRing); // Read the key file using BouncyCastle utility class to build a collection. PGPPublicKeyRingCollection keyRingCollection = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(publicKeyStream), fingerPrintCalculator); // Iterate through the key rings to find a key that can be used for encryption Iterator<PGPPublicKeyRing> rIt = keyRingCollection.getKeyRings(); while (publicKey == null && rIt.hasNext()) { PGPPublicKeyRing kRing = rIt.next(); Iterator<PGPPublicKey> kIt = kRing.getPublicKeys(); while (publicKey == null && kIt.hasNext()) { PGPPublicKey key = kIt.next(); if (key.isEncryptionKey()) { publicKey = key; } } } // The key store does not contain any key. if (publicKey == null) { throw new CryptDecryptException("Can't find public key in the key ring."); } // Check if the key can be used for encryption. If not throw an exception if (!isForEncryption(publicKey)) { throw new CryptDecryptException("KeyID " + publicKey.getKeyID() + " not flagged for encryption."); } if(enableDebugLog)Trace.logInfo("CryptDecryptUtil.readPublicKey", "Exit"); return publicKey; }
public static List<PGPPublicKey> findPublicKeys(CamelContext context, String filename, byte[] keyRing, List<String> userids, boolean forEncryption) throws IOException, PGPException, NoSuchProviderException { InputStream is = determineKeyRingInputStream(context, filename, keyRing, forEncryption); try { return findPublicKeys(is, userids, forEncryption); } finally { IOHelper.close(is); } }
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)); }
@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; }
@Test public void testEncryptDecrypt_ExplicitStyle() throws Exception { int bufferSize = 64 * 1024; // Alice loads Bob's "publicKey" into memory. PGPPublicKeyRing publicKeyRing = new BcPGPPublicKeyRing(PUBLIC_KEY); 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.info("Encrypted data: " + dumpHex(encryptedData)); // Bob loads his "privateKey" into memory. PGPSecretKeyRing privateKeyRing = new BcPGPSecretKeyRing(PRIVATE_KEY); PGPPrivateKey privateKey = extractPrivateKey(privateKeyRing.getSecretKey()); // 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); assertThat(encData.getKeyID()).isEqualTo(publicKey.getKeyID()); assertThat(encData.getKeyID()).isEqualTo(privateKey.getKeyID()); try (InputStream original = encData.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey))) { assertThat(CharStreams.toString(new InputStreamReader(original, UTF_8))) .isEqualTo(FALL_OF_HYPERION_A_DREAM); } } }
/** Deserialize a PGPPublicKey */ public static PGPPublicKey deserializePublicKey(byte[] serialized) throws IOException { return new BcPGPPublicKeyRing( PGPUtil.getDecoderStream( new ByteArrayInputStream(serialized))).getPublicKey(); }
public static boolean verifySignature( ContentAndSignatures contentAndSignatures, PGPPublicKey publicKey ) throws PGPException { Preconditions.checkNotNull( contentAndSignatures ); Preconditions.checkNotNull( publicKey ); try { for ( int i = 0; i < contentAndSignatures.getOnePassSignatureList().size(); i++ ) { PGPOnePassSignature ops = contentAndSignatures.getOnePassSignatureList().get( 0 ); ops.init( new JcaPGPContentVerifierBuilderProvider().setProvider( provider ), publicKey ); ops.update( contentAndSignatures.getDecryptedContent() ); PGPSignature signature = contentAndSignatures.getSignatureList().get( i ); if ( !ops.verify( signature ) ) { return false; } } return true; } catch ( Exception e ) { throw new PGPException( "Error in verifySignature", e ); } }
public static PGPPublicKey findPublicKeyByFingerprint( InputStream publicKeyRing, String fingerprint ) throws PGPException { try { return findPublicKey( publicKeyRing, fingerprint, true ); } catch ( Exception e ) { throw new PGPException( "Error in findPublicKeyByFingerprint", e ); } }
/******************************************** * Convert BouncyCastle PGPKeyRing to SecurityKey entity */ public static PublicKeyStore convert( PGPPublicKeyRing pgpKeyRing ) throws IOException { try { PGPPublicKey pgpKey = PGPKeyUtil.readPublicKey( pgpKeyRing ); if ( pgpKey != null ) { String fingerprint = new String( Hex.encodeHex( pgpKey.getFingerprint(), false ) ); PublicKeyStore pk = new PublicKeyStoreEntity(); pk.setFingerprint( fingerprint ); pk.setKeyId( PGPKeyUtil.getKeyId( fingerprint ) ); pk.setShortKeyId( PGPKeyUtil.getShortKeyId( fingerprint ) ); pk.setKeyData( pgpKeyRing.getEncoded() ); return pk; } else { return null; } } catch ( Exception ex ) { return null; } }
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() ); } } }