Example usage for org.bouncycastle.openpgp PGPPublicKey getAlgorithm

List of usage examples for org.bouncycastle.openpgp PGPPublicKey getAlgorithm

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp PGPPublicKey getAlgorithm.

Prototype

public int getAlgorithm() 

Source Link

Document

Return the algorithm code associated with the public key.

Usage

From source file:bisq.common.crypto.PGP.java

License:Open Source License

@Nullable
public static PGPPublicKey getPubKeyFromPem(@Nullable String pem) {
    if (pem != null) {
        InputStream inputStream = new ByteArrayInputStream(pem.getBytes(Charsets.UTF_8));
        try {//from   w  w  w . j a  v a2s. c  o  m
            inputStream = PGPUtil.getDecoderStream(inputStream);
            try {
                JcaPGPPublicKeyRingCollection ringCollection = new JcaPGPPublicKeyRingCollection(inputStream);
                Iterator<PGPPublicKeyRing> keyRingsIterator = ringCollection.getKeyRings();
                while (keyRingsIterator.hasNext()) {
                    PGPPublicKeyRing pgpPublicKeyRing = keyRingsIterator.next();
                    Iterator<PGPPublicKey> pubKeysIterator = pgpPublicKeyRing.getPublicKeys();
                    while (pubKeysIterator.hasNext()) {
                        final PGPPublicKey pgpPublicKey = pubKeysIterator.next();
                        if ((pgpPublicKey).isEncryptionKey()) {
                            log.debug(pgpPublicKey.getClass().getName() + " KeyID: "
                                    + Long.toHexString(pgpPublicKey.getKeyID()) + " type: "
                                    + pgpPublicKey.getAlgorithm() + " fingerprint: "
                                    + new String(Hex.encode(pgpPublicKey.getFingerprint())));

                            BCPGKey bcKey = pgpPublicKey.getPublicKeyPacket().getKey();
                            log.debug(bcKey.getClass().getName());
                            if (bcKey instanceof RSAPublicBCPGKey) {
                                RSAPublicBCPGKey bcRSA = (RSAPublicBCPGKey) bcKey;
                                RSAPublicKeySpec specRSA = new RSAPublicKeySpec(bcRSA.getModulus(),
                                        bcRSA.getPublicExponent());
                                PublicKey jceKey = KeyFactory.getInstance("RSA").generatePublic(specRSA);
                                // if you want to use the key in JCE, use jceKey
                                // if you want to write "X.509" (SPKI) DER format to a file:
                                //Files.write(new File(pubKeyAsString).toPath(), jceKey.getEncoded());
                                // if you want to write in PEM, bouncycastle can do that
                                // or you can just do base64 and add BEGIN/END lines
                                // return pubKeyAsString; // assume only one key; if need to handle multiple keys
                                // or select other than the first, specify more clearly
                            }

                            return pgpPublicKey;
                        }
                    }
                }
                return null;
            } catch (PGPException | InvalidKeySpecException | NoSuchAlgorithmException e) {
                log.error("Error creating publicKey from pem. pem={}, error={}", pem, e);
                e.printStackTrace();
                throw new KeyConversionException(e);
            }

        } catch (IOException e) {
            log.error("Error creating publicKey from pem. pem={}, error={}", pem, e);
            e.printStackTrace();
            throw new KeyConversionException(e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException ignore) {
            }
        }
    } else {
        log.warn("Error creating publicKey from pem. pem=null");
        return null;
    }
}

From source file:com.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * UNUSED IN FRIENDLY BACKUP/*from w  w w.  j  a  v  a  2 s  .  c o  m*/
 * Sign the passed in message stream (version 3 signature)
 */
private void signDataV3(File inFile, OutputStream aOut, PGPPublicKey publicKey, PGPPrivateKey privateKey)
        throws PGPException {
    try {
        PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
        BCPGOutputStream bOut = new BCPGOutputStream(cGen.open(aOut));
        PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator(true);

        PGPV3SignatureGenerator s3Gen = new PGPV3SignatureGenerator(publicKey.getAlgorithm(), PGPUtil.SHA1,
                "BC");

        s3Gen.initSign(PGPSignature.BINARY_DOCUMENT, privateKey);

        s3Gen.generateOnePassVersion(false).encode(bOut);

        OutputStream lOut = lGen.open(bOut, PGPLiteralData.BINARY, inFile);

        FileInputStream fIn = new FileInputStream(inFile);

        int ch;
        while ((ch = fIn.read()) >= 0) {
            lOut.write(ch);
            s3Gen.update((byte) ch);
        }

        fIn.close();

        // close() finishes the writing of the literal data and flushes the stream
        // It does not close bOut so this is ok here
        lGen.close();

        // Generate the signature
        s3Gen.generate().encode(bOut);

        // Must not close bOut here
        bOut.finish();
        bOut.flush();

        cGen.close();
    } catch (PGPException e) {
        throw e;
    } catch (Exception e) {
        throw new PGPException("Error in signing", e);
    }
}

From source file:com.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Sign the passed in message stream/*from  w ww .j  a  va 2s  .co m*/
 */
private void signData(File inFile, OutputStream aOut, PGPPublicKey publicKey, PGPPrivateKey privateKey)
        throws PGPException {
    try {
        PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
        BCPGOutputStream bOut = new BCPGOutputStream(cGen.open(aOut));
        PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();

        PGPSignatureGenerator sGen = new PGPSignatureGenerator(publicKey.getAlgorithm(), PGPUtil.SHA1, "BC");

        sGen.initSign(PGPSignature.BINARY_DOCUMENT, privateKey);

        @SuppressWarnings("unchecked")
        Iterator<String> users = publicKey.getUserIDs();
        if (users.hasNext()) {
            PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
            spGen.setSignerUserID(false, users.next());
            sGen.setHashedSubpackets(spGen.generate());
        }

        sGen.generateOnePassVersion(false).encode(bOut);

        OutputStream lOut = lGen.open(bOut, PGPLiteralData.BINARY, inFile);

        FileInputStream fIn = new FileInputStream(inFile);

        int ch;
        while ((ch = fIn.read()) >= 0) {
            lOut.write(ch);
            sGen.update((byte) ch);
        }

        fIn.close();

        // close() finishes the writing of the literal data and flushes the stream
        // It does not close bOut so this is ok here
        lGen.close();

        // Generate the signature
        sGen.generate().encode(bOut);

        // Must not close bOut here
        bOut.finish();
        bOut.flush();

        cGen.close();
    } catch (PGPException e) {
        throw e;
    } catch (Exception e) {
        throw new PGPException("Error in signing", e);
    }
}

From source file:com.geekcommune.identity.EncryptionUtil.java

License:Open Source License

public PGPSignature makeSignature(byte[] input, PGPPublicKey publicKey, PGPPrivateKey privateKey)
        throws PGPException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException {
    PGPSignatureGenerator sGen = new PGPSignatureGenerator(publicKey.getAlgorithm(), PGPUtil.SHA1, "BC");

    sGen.initSign(PGPSignature.BINARY_DOCUMENT, privateKey);

    @SuppressWarnings("unchecked")
    Iterator<String> users = publicKey.getUserIDs();
    if (users.hasNext()) {
        PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
        spGen.setSignerUserID(false, users.next());
        sGen.setHashedSubpackets(spGen.generate());
    }/*  www. jav  a  2 s  .c om*/

    for (byte b : input) {
        sGen.update(b);
    }

    return sGen.generate();
}

From source file:com.geekcommune.identity.EncryptionUtil.java

License:Open Source License

public PGPPublicKey findFirstSigningKey(PGPPublicKeyRing keyRing) throws PGPException {
    @SuppressWarnings("unchecked")
    Iterator<PGPPublicKey> kIt = keyRing.getPublicKeys();

    PGPPublicKey retval = null;/*from www  . j a  v  a  2s. c o  m*/
    while (retval == null && kIt.hasNext()) {
        PGPPublicKey k = kIt.next();

        if (isSigningAlgorithm(k.getAlgorithm())) {
            retval = k;
        }
    }

    if (retval == null) {
        throw new PGPException("No signing key found in keyring");
    }

    return retval;
}

From source file:com.github.jpks.core.service.impl.PublicKeyReaderServiceImpl.java

License:Apache License

private PublicKeyImpl convert(final PGPPublicKey pgpPublicKey) {
    PublicKeyImpl key = new PublicKeyImpl();
    key.setUserIds(new ArrayList<UserIdImpl>());

    key.setKeyId(Long.toHexString(pgpPublicKey.getKeyID()).toUpperCase());
    key.setAlgo(pgpPublicKey.getAlgorithm());
    key.setKeyLen(pgpPublicKey.getBitStrength());
    key.setCreationDate(pgpPublicKey.getCreationTime());

    key.setMaster(pgpPublicKey.isMasterKey());
    key.setRevoked(pgpPublicKey.isRevoked());
    Iterator userIDs = pgpPublicKey.getUserIDs();

    while (userIDs.hasNext()) {
        String userUd = (String) userIDs.next();
        UserIdImpl userId = convert(userUd);
        userId.setCreationDate(pgpPublicKey.getCreationTime());
        key.addUserId(userId);// w  w w. ja  v a  2 s . c  o m
    }

    return key;
}

From source file:de.softwareforge.pgpsigner.commands.SignCommand.java

License:Apache License

@Override
public void executeInteractiveCommand(final String[] args) {

    PGPSignatureGenerator signatureGenerator = null;

    SecretKey signKey = getContext().getSignKey();
    PGPPublicKey pubKey = signKey.getPGPPublicKey();

    try {// w  w w .  j  a  v  a 2  s.c o m
        signatureGenerator = new PGPSignatureGenerator(pubKey.getAlgorithm(), PGPUtil.SHA1, "BC");
        signatureGenerator.initSign(PGPSignature.DEFAULT_CERTIFICATION, signKey.getPGPPrivateKey());

        PGPSignatureSubpacketGenerator subpacketGenerator = new PGPSignatureSubpacketGenerator();
        for (Iterator it = pubKey.getUserIDs(); it.hasNext();) {
            subpacketGenerator.setSignerUserID(false, (String) it.next());
            signatureGenerator.setHashedSubpackets(subpacketGenerator.generate());
        }
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        System.out.println("Could not generate signature for signing.");
        return;
    }

    for (PublicKey key : getContext().getPartyRing().getVisibleKeys().values()) {

        if (!key.isSigned()) {
            try {
                PGPPublicKey newKey = key.getPGPPublicKey();
                PGPSignature signature = signatureGenerator.generateCertification(newKey);

                for (Iterator it = key.getUserIds(); it.hasNext();) {
                    String userId = (String) it.next();
                    newKey = PGPPublicKey.addCertification(newKey, userId, signature);
                }

                key.setPGPPublicKey(newKey);
                key.setSigned(true);
                System.out.println("Signed Key " + key.getKeyId() + " with " + signKey.getKeyId());

            } catch (RuntimeException re) {
                throw re;
            } catch (Exception e) {
                System.out.println("Could not sign key " + DisplayHelpers.showKey(key) + ", skipping.");
            }
        }
    }
}

From source file:google.registry.keyring.api.PgpHelper.java

License:Open Source License

/** 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://from   w w  w.  ja v  a  2s.  c o m
    case ELGAMAL_GENERAL:
        return true;
    default:
        return false;
    }
}

From source file:org.apache.camel.converter.crypto.PGPDataFormatUtil.java

License:Apache License

private static boolean isSignatureKey(PGPPublicKey key) {
    int algorithm = key.getAlgorithm();
    return algorithm == RSA_GENERAL || algorithm == RSA_SIGN || algorithm == DSA || algorithm == ECDSA
            || algorithm == ELGAMAL_GENERAL;
}

From source file:org.multibit.hd.brit.crypto.PGPUtilsTest.java

License:MIT License

@Test
public void testLoadPGPPublicKeyFromASCIIArmoredFile() throws Exception {
    File publicKeyFile = makeFile(TEST_MATCHER_PUBLIC_KEY_FILE);
    log.debug("Loading public key from '" + publicKeyFile.getAbsolutePath() + "'");
    FileInputStream publicKeyInputStream = new FileInputStream(publicKeyFile);
    PGPPublicKey publicKey = PGPUtils.readPublicKey(publicKeyInputStream);
    assertThat(publicKey).isNotNull();/*w  ww  .j a v  a2s. c o m*/
    log.debug("Loaded PGP public key :\nAlgorithm: " + publicKey.getAlgorithm() + ", bitStrength: "
            + publicKey.getBitStrength() + ", fingerprint: " + Utils.HEX.encode(publicKey.getFingerprint()));
}