org.bouncycastle.openpgp.PGPException Java Examples

The following examples show how to use org.bouncycastle.openpgp.PGPException. 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 vote down vote up
@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: Marksdb.java    From nomulus with Apache License 2.0 6 votes vote down vote up
List<String> fetchSignedCsv(Optional<String> loginAndPassword, String csvPath, String sigPath)
    throws IOException, SignatureException, PGPException {
  checkArgument(
      loginAndPassword.isPresent(), "Cannot fetch from MarksDB without login credentials");

  String csvUrl = tmchMarksdbUrl + csvPath;
  byte[] csv = fetch(new URL(csvUrl), loginAndPassword);
  logFetchedBytes(csvUrl, csv);

  String sigUrl = tmchMarksdbUrl + sigPath;
  byte[] sig = fetch(new URL(sigUrl), loginAndPassword);
  logFetchedBytes(sigUrl, sig);

  pgpVerifySignature(csv, sig, marksdbPublicKey);
  ImmutableList<String> lines = ByteSource.wrap(csv).asCharSource(US_ASCII).readLines();
  logger.atInfo().log("Parsed %d lines.", lines.size());
  return lines;
}
 
Example #3
Source File: Ring.java    From jpgpj with MIT License 6 votes vote down vote up
/**
 * Loads all keys from the specified input stream,
 * and adds them to this ring's existing list of keys.
 */
public List<Key> load(InputStream stream) throws IOException, PGPException {
    List<Key> keys = new ArrayList<Key>();

    Iterator<?> packets = parse(stream);
    while (packets.hasNext()) {
        Object packet = packets.next();

        if (packet instanceof PGPSecretKeyRing)
            keys.add(newKey((PGPSecretKeyRing) packet));
        else if (packet instanceof PGPPublicKeyRing)
            keys.add(newKey((PGPPublicKeyRing) packet));
        else if (packet instanceof PublicKeyRingBlob)
            keys.add(newKey(
                ((PublicKeyRingBlob) packet).getPGPPublicKeyRing()));
    }

    this.keys.addAll(keys);
    return keys;
}
 
Example #4
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static String armorByteArrayToString( byte[] data ) throws PGPException
{
    try
    {
        ByteArrayOutputStream encOut = new ByteArrayOutputStream();
        ArmoredOutputStream armorOut = new ArmoredOutputStream( encOut );

        armorOut.write( data );
        armorOut.flush();
        armorOut.close();
        return new String( encOut.toByteArray() );
    }
    catch ( Exception e )
    {
        throw new PGPException( "Error loading keyring", e );
    }
}
 
Example #5
Source File: Encryptor.java    From jpgpj with MIT License 6 votes vote down vote up
/**
 * Wraps with stream that outputs signature packets
 * as header and footer to envelope.
 */
protected SigningOutputStream sign(OutputStream out, FileMetadata meta)
        throws IOException, PGPException {
    HashingAlgorithm sigAlg = getSigningAlgorithm();
    log.trace("using signing algorithm {}", sigAlg);

    if (sigAlg == HashingAlgorithm.Unsigned)
        return null;

    Ring encRing = getRing();
    List<Key> signers = encRing.getSigningKeys();
    // skip keys without a passphrase set
    for (int i = signers.size() - 1; i >= 0; i--) {
        Key key = signers.get(i);
        Subkey subkey = key.getSigning();
        if (!isUsableForSigning(subkey)) {
            log.info("not using signing key {}", subkey);
            signers.remove(i);
        }
    }

    if (Util.isEmpty(signers))
        throw new PGPException("no suitable signing key found");

    return new SigningOutputStream(out, signers, meta);
}
 
Example #6
Source File: EnvironmentManagerImpl.java    From peer-os with Apache License 2.0 6 votes vote down vote up
PGPSecretKeyRing createEnvironmentKeyPair( EnvironmentId envId ) throws EnvironmentCreationException
{
    KeyManager keyManager = securityManager.getKeyManager();
    String pairId = envId.getId();
    try
    {
        KeyPair keyPair = keyManager.generateKeyPair( pairId, false );

        //******Create PEK *****************************************************************
        PGPSecretKeyRing secRing = pgpKeyUtil.getSecretKeyRing( keyPair.getSecKeyring() );
        PGPPublicKeyRing pubRing = pgpKeyUtil.getPublicKeyRing( keyPair.getPubKeyring() );

        //***************Save Keys *********************************************************
        keyManager.saveSecretKeyRing( pairId, SecurityKeyType.ENVIRONMENT_KEY.getId(), secRing );
        keyManager.savePublicKeyRing( pairId, SecurityKeyType.ENVIRONMENT_KEY.getId(), pubRing );


        return secRing;
    }
    catch ( PGPException ex )
    {
        throw new EnvironmentCreationException( ex );
    }
}
 
Example #7
Source File: PgpHelper.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * 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: RemotePeerImpl.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@Override
public void updatePeerEnvironmentPubKey( final EnvironmentId environmentId, final PGPPublicKeyRing publicKeyRing )
        throws PeerException
{
    Preconditions.checkNotNull( environmentId, "Invalid environmentId" );
    Preconditions.checkNotNull( publicKeyRing, "Public key ring is null" );


    try
    {
        String exportedPubKeyRing =
                securityManager.getEncryptionTool().armorByteArrayToString( publicKeyRing.getEncoded() );
        final PublicKeyContainer publicKeyContainer =
                new PublicKeyContainer( environmentId.getId(), publicKeyRing.getPublicKey().getFingerprint(),
                        exportedPubKeyRing );
        peerWebClient.updateEnvironmentPubKey( publicKeyContainer );
    }
    catch ( IOException | PGPException e )
    {
        throw new PeerException( e.getMessage() );
    }
}
 
Example #9
Source File: RydeEncryptionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testFail_oneReceiver_decryptWithWrongKey() throws Exception {
  FakeKeyringModule keyringModule = new FakeKeyringModule();
  PGPKeyPair key = keyringModule.get("[email protected]", ENCRYPT);
  PGPKeyPair wrongKey = keyringModule.get("[email protected]", ENCRYPT);
  assertThat(key.getKeyID()).isNotEqualTo(wrongKey.getKeyID());
  byte[] expected = "Testing 1, 2, 3".getBytes(UTF_8);

  ByteArrayOutputStream output = new ByteArrayOutputStream();
  try (OutputStream encryptor =
      RydeEncryption.openEncryptor(output, false, ImmutableList.of(key.getPublicKey()))) {
    encryptor.write(expected);
  }
  byte[] encryptedData = output.toByteArray();

  ByteArrayInputStream input = new ByteArrayInputStream(encryptedData);
  RuntimeException thrown =
      assertThrows(
          RuntimeException.class,
          () -> {
            RydeEncryption.openDecryptor(input, false, wrongKey.getPrivateKey()).read();
          });

  assertThat(thrown).hasCauseThat().isInstanceOf(PGPException.class);
}
 
Example #10
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
/**
 * 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 );
    }
}
 
Example #11
Source File: PGPKeyUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
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 #12
Source File: KeyFilesOperationsPgpImpl.java    From pgptool with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private Key readFromStream(InputStream stream) throws PGPException {
	KeyDataPgp data = new KeyDataPgp();
	try {
		readKeyFromStream(data, stream);
	} catch (Throwable t) {
		throw new RuntimeException("Error happened while parsing key", t);
	}
	if (data.getPublicKeyRing() == null && data.getSecretKeyRing() == null) {
		throw new RuntimeException("Neither Secret nor Public keys were found in the input text");
	}

	Key key = new Key();
	key.setKeyData(data);
	if (data.getSecretKeyRing() != null) {
		key.setKeyInfo(buildKeyInfoFromSecret(data.getSecretKeyRing()));
	} else {
		key.setKeyInfo(buildKeyInfoFromPublic(data.getPublicKeyRing()));
	}
	return key;
}
 
Example #13
Source File: PGPKeyHelperTest.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetPrivateKeyFromPath() throws IOException, PGPException
{
    PGPPrivateKey privateKey = PGPKeyHelper.readPrivateKey( PGPTestDataFactory.PRIVATE_KEY_PATH, PGPTestDataFactory.DEFAULT_PASSWORD );

    assertNotNull( privateKey );
}
 
Example #14
Source File: Ring.java    From jpgpj with MIT License 5 votes vote down vote up
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);
}
 
Example #15
Source File: Decryptor.java    From jpgpj with MIT License 5 votes vote down vote up
/**
 * Wraps stream with ArmoredInputStream if necessary
 * (to convert ASCII-armored content back into binary data).
 */
protected InputStream unarmor(InputStream stream)
        throws IOException, PGPException {
    DetectionResult result =
        FileDetection.detectContainer(stream, getMaxFileBufferSize());
    switch (result.type) {
        case ASCII_ARMOR:
            return new ArmoredInputStream(result.stream);
        case PGP:
            return result.stream;
        default:
            throw new PGPException("not a pgp message");
    }
}
 
Example #16
Source File: EncryptionToolImpl.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@Override
public boolean verifyClearSign( final byte[] message, final PGPPublicKeyRing pgpRings ) throws PGPException
{
    try
    {
        return PGPEncryptionUtil.verifyClearSign( message, pgpRings );
    }
    catch ( Exception e )
    {
        throw new PGPException( "Error verifying message signature", e );
    }
}
 
Example #17
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public static PGPSecretKey findSecretKeyById( InputStream secretKeyRing, String keyId ) throws PGPException
{
    try
    {
        return findSecretKey( secretKeyRing, keyId, false );
    }
    catch ( Exception e )
    {
        throw new PGPException( "Error in findSecretKeyById", e );
    }
}
 
Example #18
Source File: EncryptionToolImpl.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@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 #19
Source File: DependencyResolverFactory.java    From rug-cli with GNU General Public License v3.0 5 votes vote down vote up
public static DependencyVerifier[] verifiers() {
    if (!CommandLineOptions.hasOption("disable-verification")) {
        try {
            return new DependencyVerifier[] { new GpgSignatureVerifier() };
        }
        catch (IOException | PGPException e) {
            throw new RunnerException(e);
        }
    }
    else {
        log.info(Style.yellow(
                "Extension verification is disabled. Please use with extreme caution!"));
    }
    return new DependencyVerifier[0];
}
 
Example #20
Source File: Ring.java    From jpgpj with MIT License 5 votes vote down vote up
/**
 * Separates stream into PGP packets.
 * @see PGPObjectFactory
 */
protected Iterator<?> parse(InputStream stream)
throws IOException, PGPException {
    DetectionResult result = FileDetection.detectContainer(stream);
    switch (result.type) {
        case ASCII_ARMOR:
            result.stream = new ArmoredInputStream(result.stream); // fall thru
        case PGP:
            return new BcPGPObjectFactory(result.stream).iterator();
        case KEYBOX:
            return new BcKeyBox(result.stream).getKeyBlobs().iterator();
        default:
            throw new PGPException("not a keyring");
    }
}
 
Example #21
Source File: Decryptor.java    From jpgpj with MIT License 5 votes vote down vote up
/**
 * Copy of matched key with signingUid configured
 * and only public subkeys, or null.
 */
public Key getSignedBy() throws PGPException {
    if (key == null || sig == null) return null;

    // extract optional uid if available
    String uid = null;
    PGPSignatureSubpacketVector subpackets = sig.getHashedSubPackets();
    if (subpackets != null)
        uid = subpackets.getSignerUserID();

    Key by = key.toPublicKey();
    by.setSigningUid(uid != null ? uid : "");
    return by;
}
 
Example #22
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public static byte[] decrypt( final byte[] encryptedMessage, final PGPSecretKeyRing secretKeyRing,
                              final String secretPwd ) throws PGPException
{
    try
    {
        return decrypt( encryptedMessage, new ByteArrayInputStream( secretKeyRing.getEncoded() ), secretPwd );
    }
    catch ( IOException e )
    {
        throw new PGPException( "Error in encrypt", e );
    }
}
 
Example #23
Source File: Key.java    From jpgpj with MIT License 5 votes vote down vote up
/**
 * Loads first key from the specified armored text.
 * @throws PGPException if the text contains no keys.
 */
public void load(String armor) throws IOException, PGPException {
    List<Key> keys = newRing().load(armor);
    if (Util.isEmpty(keys))
        throw new PGPException("no keys found");
    setSubkeys(keys.get(0).getSubkeys());
}
 
Example #24
Source File: PGPVerify.java    From peer-os with Apache License 2.0 5 votes vote down vote up
private static void doVerify( JcaPGPObjectFactory objectFactory, PGPOnePassSignature onePassSignature )
        throws IOException, PGPException
{
    PGPSignatureList signatures = ( PGPSignatureList ) objectFactory.nextObject();

    if ( !onePassSignature.verify( signatures.get( 0 ) ) )
    {
        throw new PGPDataValidationException( "Signature verification failed" );
    }
}
 
Example #25
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public static KeyPair generateKeyPair( String userId, String secretPwd, boolean armored ) throws PGPException
{
    try
    {
        KeyPair keyPair = new KeyPair();

        PGPKeyRingGenerator krgen = generateKeyRingGenerator( userId, secretPwd, keyPair );

        // Generate public key ring
        PGPPublicKeyRing pkr = krgen.generatePublicKeyRing();
        ByteArrayOutputStream pubOut = new ByteArrayOutputStream();
        pkr.encode( pubOut );
        pubOut.close();

        // Generate private key
        PGPSecretKeyRing skr = krgen.generateSecretKeyRing();
        ByteArrayOutputStream secOut = new ByteArrayOutputStream();
        skr.encode( secOut );
        secOut.close();

        keyPair.setPubKeyring( armored ? armorByteArray( pubOut.toByteArray() ) : pubOut.toByteArray() );
        keyPair.setSecKeyring( armored ? armorByteArray( secOut.toByteArray() ) : secOut.toByteArray() );

        return keyPair;
    }
    catch ( Exception e )
    {
        throw new PGPException( "Error in generateKeyPair", e );
    }
}
 
Example #26
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
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 );
    }
}
 
Example #27
Source File: KeyManagerImpl.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@Override
public void updatePublicKeyRing( final PGPPublicKeyRing publicKeyRing )
{
    try
    {
        keyServer.updatePublicKey( publicKeyRing );
    }
    catch ( IOException | PGPException e )
    {
        LOG.warn( e.getMessage() );
    }
}
 
Example #28
Source File: EncryptionToolImpl.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@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 #29
Source File: BuildContainerStateHandler.java    From peer-os with Apache License 2.0 5 votes vote down vote up
/**
 * TODO. Identify for future do we need envKeyId (or do we need keyId for {@link RelationLinkDto})
 */
private void setupPeerEnvironmentKey( EnvironmentPeerDto peerDto ) throws PeerException, PGPException
{
    RelationLinkDto envLink =
            new RelationLinkDto( peerDto.getEnvironmentInfo().getId(), Environment.class.getSimpleName(),
                    PermissionObject.ENVIRONMENT_MANAGEMENT.getName(), peerDto.getEnvironmentInfo().getId() );

    ctx.localPeer.createPeerEnvironmentKeyPair( envLink );
}
 
Example #30
Source File: BrdaCopyAction.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  try {
    copyAsRyde();
  } catch (IOException | PGPException e) {
    throw new RuntimeException(e);
  }
}