Example usage for org.bouncycastle.openpgp.operator.jcajce JcaKeyFingerprintCalculator JcaKeyFingerprintCalculator

List of usage examples for org.bouncycastle.openpgp.operator.jcajce JcaKeyFingerprintCalculator JcaKeyFingerprintCalculator

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp.operator.jcajce JcaKeyFingerprintCalculator JcaKeyFingerprintCalculator.

Prototype

public JcaKeyFingerprintCalculator() 

Source Link

Document

Base Constructor - use the JCA defaults.

Usage

From source file:bisq.desktop.main.overlays.windows.downloadupdate.BisqInstaller.java

License:Open Source License

/**
 * Verifies detached PGP signatures against GPG/openPGP RSA public keys. Does currently not work with openssl or JCA/JCE keys.
 *
 * @param pubKeyFile Path to file providing the public key to use
 * @param sigFile    Path to detached signature file
 * @param dataFile   Path to signed data file
 * @return {@code true} if signature is valid, {@code false} if signature is not valid
 * @throws Exception throws various exceptions in case something went wrong. Main reason should be that key or
 *                   signature could be extracted from the provided files due to a "bad" format.<br>
 *                   <code>FileNotFoundException, IOException, SignatureException, PGPException</code>
 *///from   w  ww  . j av  a 2 s. co m
public static VerifyStatusEnum verifySignature(File pubKeyFile, File sigFile, File dataFile) throws Exception {
    InputStream inputStream;
    int bytesRead;
    PGPPublicKey publicKey;
    PGPSignature pgpSignature;
    boolean result;

    // Read keys from file
    inputStream = PGPUtil.getDecoderStream(new FileInputStream(pubKeyFile));
    PGPPublicKeyRingCollection publicKeyRingCollection = new PGPPublicKeyRingCollection(inputStream,
            new JcaKeyFingerprintCalculator());
    inputStream.close();

    Iterator<PGPPublicKeyRing> iterator = publicKeyRingCollection.getKeyRings();
    PGPPublicKeyRing pgpPublicKeyRing;
    if (iterator.hasNext()) {
        pgpPublicKeyRing = iterator.next();
    } else {
        throw new PGPException("Could not find public keyring in provided key file");
    }

    // Would be the solution for multiple keys in one file
    //        Iterator<PGPPublicKey> kIt;
    //        kIt = pgpPublicKeyRing.getPublicKeys();
    //        publicKey = pgpPublicKeyRing.getPublicKey(0xF5B84436F379A1C6L);

    // Read signature from file
    inputStream = PGPUtil.getDecoderStream(new FileInputStream(sigFile));
    PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(inputStream, new JcaKeyFingerprintCalculator());
    Object o = pgpObjectFactory.nextObject();
    if (o instanceof PGPSignatureList) {
        PGPSignatureList signatureList = (PGPSignatureList) o;
        checkArgument(!signatureList.isEmpty(), "signatureList must not be empty");
        pgpSignature = signatureList.get(0);
    } else if (o instanceof PGPSignature) {
        pgpSignature = (PGPSignature) o;
    } else {
        throw new SignatureException("Could not find signature in provided signature file");
    }
    inputStream.close();
    log.debug("KeyID used in signature: %X\n", pgpSignature.getKeyID());
    publicKey = pgpPublicKeyRing.getPublicKey(pgpSignature.getKeyID());

    // If signature is not matching the key used for signing we fail
    if (publicKey == null)
        return VerifyStatusEnum.FAIL;

    log.debug("The ID of the selected key is %X\n", publicKey.getKeyID());
    pgpSignature.init(new BcPGPContentVerifierBuilderProvider(), publicKey);

    // Read file to verify
    byte[] data = new byte[1024];
    inputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile)));
    while (true) {
        bytesRead = inputStream.read(data, 0, 1024);
        if (bytesRead == -1)
            break;
        pgpSignature.update(data, 0, bytesRead);
    }
    inputStream.close();

    // Verify the signature
    result = pgpSignature.verify();
    return result ? VerifyStatusEnum.OK : VerifyStatusEnum.FAIL;
}

From source file:com.arcusx.simplepgp.PgpDataDecryptor.java

public void decrypt(InputStream encryptedIn, InputStream privateKeyIn, InputStream publicKeyIn,
        OutputStream plainOut, boolean signatureRequired) throws PGPException, IOException {
    encryptedIn = PGPUtil.getDecoderStream(encryptedIn);

    try {//  ww w.  j  a v  a2  s  .  co  m
        JcaPGPObjectFactory pgpObjectFactory = new JcaPGPObjectFactory(encryptedIn);

        Object o = pgpObjectFactory.nextObject();

        //
        // the first object might be a PGP marker packet.
        //
        PGPEncryptedDataList enc;
        if (o instanceof PGPEncryptedDataList) {
            enc = (PGPEncryptedDataList) o;
        } else {
            enc = (PGPEncryptedDataList) pgpObjectFactory.nextObject();
        }

        //
        // find the secret key
        //
        Iterator it = enc.getEncryptedDataObjects();
        PGPPrivateKey privateKey = null;
        PGPPublicKeyEncryptedData publicKeyEncryptedData = null;
        PGPSecretKeyRingCollection privateKeyRingCollection = new PGPSecretKeyRingCollection(
                PGPUtil.getDecoderStream(privateKeyIn), new JcaKeyFingerprintCalculator());

        while (privateKey == null && it.hasNext()) {
            publicKeyEncryptedData = (PGPPublicKeyEncryptedData) it.next();
            privateKey = findSecretKey(privateKeyRingCollection, publicKeyEncryptedData.getKeyID(),
                    "".toCharArray());
        }

        if (privateKey == null) {
            throw new IllegalArgumentException("Secret key for message not found.");
        }

        PublicKeyDataDecryptorFactory decryptorFactory = new JcePublicKeyDataDecryptorFactoryBuilder()
                .setProvider("BC").build(privateKey);
        InputStream clearTextIn = publicKeyEncryptedData.getDataStream(decryptorFactory);

        PGPOnePassSignature onePassSignature = null;
        JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(clearTextIn);

        Object message = pgpFact.nextObject();
        if (message instanceof PGPCompressedData) {
            PGPCompressedData cData = (PGPCompressedData) message;
            pgpFact = new JcaPGPObjectFactory(cData.getDataStream());

            message = pgpFact.nextObject();
        }

        if (message instanceof PGPOnePassSignatureList) {
            PGPOnePassSignatureList onePassSignatureList = (PGPOnePassSignatureList) message;
            onePassSignature = onePassSignatureList.get(0);
            message = pgpFact.nextObject();
        }

        if (onePassSignature == null && signatureRequired) {
            throw new SecurityException("No signature object found.");
        }

        if (message instanceof PGPLiteralData) {
            PGPLiteralData literalData = (PGPLiteralData) message;
            InputStream literalDataIn = literalData.getInputStream();

            PGPPublicKey publicKey = PgpKeyUtils.readPublicKey(publicKeyIn);
            if (onePassSignature != null) {
                onePassSignature.init(new BcPGPContentVerifierBuilderProvider(), publicKey);
            }

            int len = 0;
            byte[] buf = new byte[BUFFER_SIZE];
            while ((len = literalDataIn.read(buf, 0, buf.length)) >= 0) {
                if (onePassSignature != null) {
                    onePassSignature.update(buf, 0, len);
                }

                plainOut.write(buf, 0, len);
            }

            if (onePassSignature != null) {
                PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject();
                PGPSignature signature = p3.get(0);
                if (!onePassSignature.verify(signature))
                    throw new PGPException("Signature invalid.");
            }

            plainOut.close();
        } else {
            throw new PGPException("message is not a simple encrypted file - type unknown." + message);
        }

        if (!publicKeyEncryptedData.isIntegrityProtected())
            throw new IllegalStateException("Message is not integrity protected.");

        if (!publicKeyEncryptedData.verify())
            throw new IllegalStateException("Message is integrity protected but integrity check failed.");
    } catch (NoSuchProviderException ex) {
        throw new PGPException("Decryption failed.", ex);
    } finally {
        IOUtils.closeQuietly(encryptedIn);
        IOUtils.closeQuietly(privateKeyIn);
        IOUtils.closeQuietly(publicKeyIn);
        IOUtils.closeQuietly(plainOut);
    }
}

From source file:de.sandmage.opportunisticmail.crypto.OpenPGP.java

License:Open Source License

public PGPPublicKey getPublicKeyFromString(String data) {
    InputStream input = new ByteArrayInputStream(data.getBytes());
    try {/*from  w  w  w . j a v  a  2s.  c o  m*/
        PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input),
                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.");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (PGPException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:divconq.pgp.EncryptedFileStream.java

License:Open Source License

public void loadPublicKey(Path keyring) throws IOException, PGPException {
    // TODO move some of this to dcPGPUtil
    PGPPublicKey pubKey = null;//from   w  ww.ja va  2  s  .c  o  m

    InputStream keyIn = new BufferedInputStream(new FileInputStream(keyring.toFile()));

    PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(
            org.bouncycastle.openpgp.PGPUtil.getDecoderStream(keyIn), 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.
    //

    @SuppressWarnings("rawtypes")
    Iterator keyRingIter = pgpPub.getKeyRings();

    while (keyRingIter.hasNext() && (pubKey == null)) {
        PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next();

        @SuppressWarnings("rawtypes")
        Iterator keyIter = keyRing.getPublicKeys();

        while (keyIter.hasNext() && (pubKey == null)) {
            PGPPublicKey key = (PGPPublicKey) keyIter.next();

            if (key.isEncryptionKey())
                pubKey = key;
        }
    }

    if (pubKey == null)
        throw new IllegalArgumentException("Can't find encryption key in key ring.");

    this.methods.add(new JcePublicKeyKeyEncryptionMethodGenerator(pubKey));
}

From source file:divconq.test.pgp.PGPWriter2.java

License:Open Source License

@SuppressWarnings("resource")
public void test2(String srcpath, String destpath, String keyring) throws Exception {
    Path src = Paths.get(srcpath);

    // file data 
    byte[] fileData = Files.readAllBytes(src);

    // dest//w  w  w.  j  a v a 2 s .c om
    OutputStream dest = new BufferedOutputStream(new FileOutputStream(destpath));

    // encryption key
    PGPPublicKey pubKey = null;

    InputStream keyIn = new BufferedInputStream(new FileInputStream(keyring));

    PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(
            org.bouncycastle.openpgp.PGPUtil.getDecoderStream(keyIn), 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.
    //

    @SuppressWarnings("rawtypes")
    Iterator keyRingIter = pgpPub.getKeyRings();

    while (keyRingIter.hasNext() && (pubKey == null)) {
        PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next();

        @SuppressWarnings("rawtypes")
        Iterator keyIter = keyRing.getPublicKeys();

        while (keyIter.hasNext() && (pubKey == null)) {
            PGPPublicKey key = (PGPPublicKey) keyIter.next();

            if (key.isEncryptionKey())
                pubKey = key;
        }
    }

    if (pubKey == null)
        throw new IllegalArgumentException("Can't find encryption key in key ring.");

    String fileName = src.getFileName().toString();
    byte[] encName = Utf8Encoder.encode(fileName);
    long modificationTime = System.currentTimeMillis();

    SecureRandom rand = new SecureRandom();
    int algorithm = PGPEncryptedData.AES_256;

    Cipher cipher = null;

    ByteBuf leadingbuf = Hub.instance.getBufferAllocator().heapBuffer(1024 * 1024); // 1 mb
    ByteBuf encbuf = Hub.instance.getBufferAllocator().heapBuffer(1024 * 1024); // 1 mb

    // *******************************************************************
    // public key packet
    // *******************************************************************

    PGPKeyEncryptionMethodGenerator method = new JcePublicKeyKeyEncryptionMethodGenerator(pubKey);

    byte[] key = org.bouncycastle.openpgp.PGPUtil.makeRandomKey(algorithm, rand);

    byte[] sessionInfo = new byte[key.length + 3];

    // add algorithm
    sessionInfo[0] = (byte) algorithm;

    // add key
    System.arraycopy(key, 0, sessionInfo, 1, key.length);

    // add checksum 
    int check = 0;

    for (int i = 1; i != sessionInfo.length - 2; i++)
        check += sessionInfo[i] & 0xff;

    sessionInfo[sessionInfo.length - 2] = (byte) (check >> 8);
    sessionInfo[sessionInfo.length - 1] = (byte) (check);

    ContainedPacket packet1 = method.generate(algorithm, sessionInfo);

    byte[] encoded1 = packet1.getEncoded();

    leadingbuf.writeBytes(encoded1);

    // *******************************************************************
    // encrypt packet, add IV to encryption though
    // *******************************************************************

    leadingbuf.writeByte(0xC0 | PacketTags.SYM_ENC_INTEGRITY_PRO);

    this.writePacketLength(leadingbuf, 0); // 0 = we don't know

    leadingbuf.writeByte(1); // version number

    String cName = PGPUtil.getSymmetricCipherName(algorithm) + "/CFB/NoPadding";

    DefaultJcaJceHelper helper = new DefaultJcaJceHelper();

    cipher = helper.createCipher(cName);

    byte[] iv = new byte[cipher.getBlockSize()];

    cipher.init(Cipher.ENCRYPT_MODE, PGPUtil.makeSymmetricKey(algorithm, key), new IvParameterSpec(iv));

    // ******************** start encryption **********************

    // --- encrypt checksum for encrypt packet, part of the encrypted output --- 

    byte[] inLineIv = new byte[cipher.getBlockSize() + 2];

    rand.nextBytes(inLineIv);

    inLineIv[inLineIv.length - 1] = inLineIv[inLineIv.length - 3];
    inLineIv[inLineIv.length - 2] = inLineIv[inLineIv.length - 4];

    encbuf.writeBytes(inLineIv);

    System.out.println("bytes written a: " + encbuf.readableBytes());

    // --- data packet ---

    int chunkpos = 0;

    int headerlen = 1 // format
            + 1 // name length
            + encName.length // file name
            + 4; // time

    encbuf.writeByte(0xC0 | PacketTags.LITERAL_DATA);

    int packetsize = 512 - headerlen;

    if (fileData.length - chunkpos < packetsize) {
        packetsize = fileData.length - chunkpos;

        this.writePacketLength(encbuf, headerlen + packetsize);
    } else {
        encbuf.writeByte(0xE9); // 512 packet length
    }

    System.out.println("bytes written b: " + encbuf.readableBytes());

    encbuf.writeByte(PGPLiteralData.BINARY); // data format

    encbuf.writeByte((byte) encName.length); // file name

    encbuf.writeBytes(encName);

    encbuf.writeInt((int) (modificationTime / 1000)); // mod time

    System.out.println("bytes written c: " + encbuf.readableBytes());

    encbuf.writeBytes(fileData, chunkpos, packetsize);

    System.out.println("bytes written d: " + encbuf.readableBytes());

    chunkpos += packetsize;

    // write one or more literal packets
    while (chunkpos < fileData.length) {
        packetsize = 512;

        // check if this is the final packet
        if (fileData.length - chunkpos <= packetsize) {
            packetsize = fileData.length - chunkpos;

            this.writePacketLength(encbuf, packetsize);
        } else {
            encbuf.writeByte(0xE9); // full 512 packet length
        }

        encbuf.writeBytes(fileData, chunkpos, packetsize);

        chunkpos += packetsize;
    }

    // protection packet
    encbuf.writeByte(0xC0 | PacketTags.MOD_DETECTION_CODE);
    encbuf.writeByte(20); // packet length

    MessageDigest md = MessageDigest.getInstance("SHA-1");
    md.update(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex());

    byte[] rv = md.digest();

    encbuf.writeBytes(rv);

    System.out.println("Pre-Encrypted Hex");

    this.hexDump(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex());

    System.out.println();
    System.out.println();

    // ***** encryption data ready *********

    byte[] encdata = cipher.doFinal(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex());

    // add encrypted data to main buffer
    leadingbuf.writeBytes(encdata);

    System.out.println("Final Hex");

    this.hexDump(leadingbuf.array(), leadingbuf.arrayOffset(), leadingbuf.writerIndex());

    System.out.println();
    System.out.println();

    // write to file
    dest.write(leadingbuf.array(), leadingbuf.arrayOffset(), leadingbuf.writerIndex());

    dest.flush();
    dest.close();
}

From source file:divconq.test.pgp.PGPWriter2.java

License:Open Source License

@SuppressWarnings("resource")
public void test1(String srcpath, String destpath, String keyring) throws Exception {
    Path src = Paths.get(srcpath);

    // file data 
    byte[] story = Files.readAllBytes(src);

    // dest/*from w w w. j a va 2  s.c  o m*/
    OutputStream dest = new BufferedOutputStream(new FileOutputStream(destpath));

    // encryption key
    PGPPublicKey pubKey = null;

    InputStream keyIn = new BufferedInputStream(new FileInputStream(keyring));

    PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(
            org.bouncycastle.openpgp.PGPUtil.getDecoderStream(keyIn), 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.
    //

    @SuppressWarnings("rawtypes")
    Iterator keyRingIter = pgpPub.getKeyRings();

    while (keyRingIter.hasNext() && (pubKey == null)) {
        PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next();

        @SuppressWarnings("rawtypes")
        Iterator keyIter = keyRing.getPublicKeys();

        while (keyIter.hasNext() && (pubKey == null)) {
            PGPPublicKey key = (PGPPublicKey) keyIter.next();

            if (key.isEncryptionKey())
                pubKey = key;
        }
    }

    if (pubKey == null)
        throw new IllegalArgumentException("Can't find encryption key in key ring.");

    String fileName = src.getFileName().toString();
    byte[] encName = Utf8Encoder.encode(fileName);
    long modificationTime = System.currentTimeMillis();

    SecureRandom rand = new SecureRandom();
    int algorithm = PGPEncryptedData.AES_256;

    Cipher cipher = null;

    ByteBuf leadingbuf = Hub.instance.getBufferAllocator().heapBuffer(1024 * 1024); // 1 mb
    ByteBuf encbuf = Hub.instance.getBufferAllocator().heapBuffer(1024 * 1024); // 1 mb

    // *******************************************************************
    // public key packet
    // *******************************************************************

    PGPKeyEncryptionMethodGenerator method = new JcePublicKeyKeyEncryptionMethodGenerator(pubKey);

    byte[] key = org.bouncycastle.openpgp.PGPUtil.makeRandomKey(algorithm, rand);

    byte[] sessionInfo = new byte[key.length + 3];

    // add algorithm
    sessionInfo[0] = (byte) algorithm;

    // add key
    System.arraycopy(key, 0, sessionInfo, 1, key.length);

    // add checksum 
    int check = 0;

    for (int i = 1; i != sessionInfo.length - 2; i++)
        check += sessionInfo[i] & 0xff;

    sessionInfo[sessionInfo.length - 2] = (byte) (check >> 8);
    sessionInfo[sessionInfo.length - 1] = (byte) (check);

    ContainedPacket packet1 = method.generate(algorithm, sessionInfo);

    byte[] encoded1 = packet1.getEncoded();

    leadingbuf.writeBytes(encoded1);

    // *******************************************************************
    // encrypt packet, add IV to 
    // *******************************************************************

    String cName = PGPUtil.getSymmetricCipherName(algorithm) + "/CFB/NoPadding";

    DefaultJcaJceHelper helper = new DefaultJcaJceHelper();

    cipher = helper.createCipher(cName);

    byte[] iv = new byte[cipher.getBlockSize()];

    cipher.init(Cipher.ENCRYPT_MODE, PGPUtil.makeSymmetricKey(algorithm, key), new IvParameterSpec(iv));

    // ******************** start encryption **********************

    // --- encrypt checksum for encrypt packet, part of the encrypted output --- 

    byte[] inLineIv = new byte[cipher.getBlockSize() + 2];

    rand.nextBytes(inLineIv);

    inLineIv[inLineIv.length - 1] = inLineIv[inLineIv.length - 3];
    inLineIv[inLineIv.length - 2] = inLineIv[inLineIv.length - 4];

    encbuf.writeBytes(inLineIv);

    // --- data packet ---

    encbuf.writeByte(0xC0 | PacketTags.LITERAL_DATA);

    this.writePacketLength(encbuf, 1 // format
            + 1 // name length
            + encName.length // file name
            + 4 // time
            + story.length // data
    );

    encbuf.writeByte(PGPLiteralData.BINARY);

    encbuf.writeByte((byte) encName.length);

    encbuf.writeBytes(encName);

    encbuf.writeInt((int) (modificationTime / 1000));

    encbuf.writeBytes(story);

    // protection packet
    encbuf.writeByte(0xC0 | PacketTags.MOD_DETECTION_CODE);
    encbuf.writeByte(20); // packet length

    MessageDigest md = MessageDigest.getInstance("SHA-1");
    md.update(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex());

    byte[] rv = md.digest();

    encbuf.writeBytes(rv);

    System.out.println("Encrypted Hex");

    this.hexDump(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex());

    System.out.println();
    System.out.println();

    // ***** encryption data ready *********

    byte[] encdata = cipher.doFinal(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex());

    leadingbuf.writeByte(0xC0 | PacketTags.SYM_ENC_INTEGRITY_PRO);

    /*
    this.writePacketLength(leadingbuf, 
     1      // version 
     + encdata.length       // encrypted data
       );
       */

    this.writePacketLength(leadingbuf, 0); // 0 = we don't know

    leadingbuf.writeByte(1); // version number

    // add encrypted data to main buffer
    leadingbuf.writeBytes(encdata);

    System.out.println("Final Hex");

    this.hexDump(leadingbuf.array(), leadingbuf.arrayOffset(), leadingbuf.writerIndex());

    System.out.println();
    System.out.println();

    // write to file
    dest.write(leadingbuf.array(), leadingbuf.arrayOffset(), leadingbuf.writerIndex());

    dest.flush();
    dest.close();
}

From source file:hh.learnj.test.license.test.lincense3j.KeyBasedFileProcessor.java

/**
 * decrypt the passed in message stream//w  w w  .  jav  a  2 s.  com
 */
private static void decryptFile(InputStream in, InputStream keyIn, char[] passwd, String defaultFileName)
        throws IOException, NoSuchProviderException {
    in = PGPUtil.getDecoderStream(in);
    try {
        JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(in);
        PGPEncryptedDataList enc;

        Object o = pgpF.nextObject();
        //
        // the first object might be a PGP marker packet.
        //
        if (o instanceof PGPEncryptedDataList) {
            enc = (PGPEncryptedDataList) o;
        } else {
            enc = (PGPEncryptedDataList) pgpF.nextObject();
        }
        //
        // find the secret key
        //
        Iterator it = enc.getEncryptedDataObjects();
        PGPPrivateKey sKey = null;
        PGPPublicKeyEncryptedData pbe = null;
        PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn),
                new JcaKeyFingerprintCalculator());

        while (sKey == null && it.hasNext()) {
            pbe = (PGPPublicKeyEncryptedData) it.next();
            sKey = MyPGPUtil.findSecretKey(pgpSec, pbe.getKeyID(), passwd);
        }
        if (sKey == null) {
            throw new IllegalArgumentException("secret key for message not found.");
        }
        InputStream clear = pbe
                .getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(sKey));
        JcaPGPObjectFactory plainFact = new JcaPGPObjectFactory(clear);
        Object message = plainFact.nextObject();
        if (message instanceof PGPCompressedData) {
            PGPCompressedData cData = (PGPCompressedData) message;
            JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(cData.getDataStream());
            message = pgpFact.nextObject();
        }
        if (message instanceof PGPLiteralData) {
            PGPLiteralData ld = (PGPLiteralData) message;

            String outFileName = ld.getFileName();
            if (outFileName.length() == 0) {
                outFileName = defaultFileName;
            } else {
                /**
                 * modify 20160520 set fileName ????????
                 */
                String separator = "";
                if (outFileName.contains("/")) {
                    separator = "/";
                } else if (outFileName.contains("\\")) {
                    separator = "\\";

                }
                String fileName = outFileName.substring(outFileName.lastIndexOf(separator) + 1);
                //
                String defseparator = "";
                if (defaultFileName.contains("/")) {
                    defseparator = "/";
                } else if (defaultFileName.contains("\\")) {
                    defseparator = "\\";
                }

                defaultFileName = defaultFileName.substring(0, defaultFileName.lastIndexOf(defseparator));

                outFileName = defaultFileName + File.separator + fileName;

            }

            InputStream unc = ld.getInputStream();
            OutputStream fOut = new BufferedOutputStream(new FileOutputStream(outFileName));

            Streams.pipeAll(unc, fOut);

            fOut.close();
        } else if (message instanceof PGPOnePassSignatureList) {
            throw new PGPException("encrypted message contains a signed message - not literal data.");
        } else {
            throw new PGPException("message is not a simple encrypted file - type unknown.");
        }

        if (pbe.isIntegrityProtected()) {
            if (!pbe.verify()) {
                System.err.println("message failed integrity check");
            } else {
                System.err.println("message integrity check passed");
            }
        } else {
            System.err.println("no message integrity check");
        }
    } catch (PGPException e) {
        System.err.println(e);
        if (e.getUnderlyingException() != null) {
            e.getUnderlyingException().printStackTrace();
        }
    }
}

From source file:hh.learnj.test.license.test.lincense3j.MyPGPUtil.java

/**
 * A simple routine that opens a key ring file and loads the first available
 * key suitable for encryption.//from   w w  w.j  ava  2 s .  c o  m
 *
 * @param input
 *            data stream containing the public key data
 * @return the first public key found.
 * @throws IOException
 * @throws PGPException
 */
public 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.");
}

From source file:hh.learnj.test.license.test.lincense3j.MyPGPUtil.java

/**
 * A simple routine that opens a key ring file and loads the first available
 * key suitable for signature generation.
 *
 * @param input//from w  w  w  . jav a  2 s . c om
 *            stream to read the secret key ring collection from.
 * @return a secret key.
 * @throws IOException
 *             on a problem with using the input stream.
 * @throws PGPException
 *             if there is an issue parsing the input stream.
 */
public static PGPSecretKey readSecretKey(InputStream input) throws IOException, PGPException {
    PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(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 = pgpSec.getKeyRings();
    while (keyRingIter.hasNext()) {
        PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRingIter.next();

        Iterator keyIter = keyRing.getSecretKeys();
        while (keyIter.hasNext()) {
            PGPSecretKey key = (PGPSecretKey) keyIter.next();

            if (key.isSigningKey()) {
                return key;
            }
        }
    }
    throw new IllegalArgumentException("Can't find signing key in key ring.");
}

From source file:net.staticsnow.nexus.repository.apt.internal.gpg.AptSigningFacet.java

License:Open Source License

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;
            }/*from   ww  w . j ava  2s  . co m*/
        }
    }

    throw new IllegalStateException("Can't find signing key in key ring.");
}