Package org.bouncycastle.openpgp

Examples of org.bouncycastle.openpgp.PGPPrivateKey


        char[]                  passP = "FIXCITY_QA".toCharArray();

        if (!noIDEA())
        {
            PGPSecretKeyRing        pgpPriv = new PGPSecretKeyRing(testPrivKeyV3);
            PGPPrivateKey           pgpPrivKey = pgpPriv.getSecretKey().extractPrivateKey(passP, "BC");

            //
            // write a v3 private key
            //
            bOut = new ByteArrayOutputStream();
            pOut = new BCPGOutputStream(bOut);

            pgpPriv.encode(pOut);

            if (!areEqual(bOut.toByteArray(), testPrivKeyV3))
            {
                fail("private key V3 rewrite failed");
            }
        }

        //
        // Read the private key
        //
        PGPSecretKeyRing pgpPriv = new PGPSecretKeyRing(testPrivKey);
        PGPPrivateKey pgpPrivKey = pgpPriv.getSecretKey().extractPrivateKey(pass, "BC");
       
        //
        // write a private key
        //
        bOut = new ByteArrayOutputStream();
        pOut = new BCPGOutputStream(bOut);
       
        pgpPriv.encode(pOut);

        if (!areEqual(bOut.toByteArray(), testPrivKey))   
        {
            fail("private key rewrite failed");
        }
       

        //
        // test encryption
        //
        Cipher c = Cipher.getInstance("RSA", "BC");

        c.init(Cipher.ENCRYPT_MODE, pubKey);
       
        byte[]  in = "hello world".getBytes();

        byte[]  out = c.doFinal(in);
       
        c.init(Cipher.DECRYPT_MODE, pgpPrivKey.getKey());
       
        out = c.doFinal(out);
       
        if (!areEqual(in, out))
        {
            fail("decryption failed.");
        }

        //
        // test signature message
        //
        PGPObjectFactory           pgpFact = new PGPObjectFactory(sig1);

        PGPCompressedData          c1 = (PGPCompressedData)pgpFact.nextObject();

        pgpFact = new PGPObjectFactory(c1.getDataStream());
       
        PGPOnePassSignatureList    p1 = (PGPOnePassSignatureList)pgpFact.nextObject();
       
        PGPOnePassSignature        ops = p1.get(0);
       
        PGPLiteralData             p2 = (PGPLiteralData)pgpFact.nextObject();

        InputStream                dIn = p2.getInputStream();
        int                        ch;

        ops.initVerify(pgpPub.getPublicKey(ops.getKeyID()), "BC");
       
        while ((ch = dIn.read()) >= 0)
        {
            ops.update((byte)ch);
        }

        PGPSignatureList                        p3 = (PGPSignatureList)pgpFact.nextObject();

        if (!ops.verify(p3.get(0)))
        {
            fail("Failed signature check");
        }
       
        //
        // encrypted message - read subkey
        //
        pgpPriv = new PGPSecretKeyRing(subKey);

        //
        // encrypted message
        //
        byte[]    text = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', (byte)' ', (byte)'w', (byte)'o', (byte)'r', (byte)'l', (byte)'d', (byte)'!', (byte)'\n' };
       
        PGPObjectFactory pgpF = new PGPObjectFactory(enc1);

        PGPEncryptedDataList            encList = (PGPEncryptedDataList)pgpF.nextObject();
   
        PGPPublicKeyEncryptedData    encP = (PGPPublicKeyEncryptedData)encList.get(0);
       
        pgpPrivKey = pgpPriv.getSecretKey(encP.getKeyID()).extractPrivateKey(pass, "BC");

        InputStream clear = encP.getDataStream(pgpPrivKey, "BC");
                
        pgpFact = new PGPObjectFactory(clear);

        c1 = (PGPCompressedData)pgpFact.nextObject();

        pgpFact = new PGPObjectFactory(c1.getDataStream());
       
        PGPLiteralData    ld = (PGPLiteralData)pgpFact.nextObject();
   
        bOut = new ByteArrayOutputStream();
       
        if (!ld.getFileName().equals("test.txt"))
        {
            throw new RuntimeException("wrong filename in packet");
        }

        InputStream    inLd = ld.getDataStream();
       
        while ((ch = inLd.read()) >= 0)
        {
            bOut.write(ch);
        }

        if (!areEqual(bOut.toByteArray(), text))
        {
            fail("wrong plain text in decrypted packet");
        }

        //
        // encrypt - short message
        //
        byte[]    shortText = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' };
   
        ByteArrayOutputStream        cbOut = new ByteArrayOutputStream();
        PGPEncryptedDataGenerator    cPk = new PGPEncryptedDataGenerator(SymmetricKeyAlgorithmTags.CAST5, new SecureRandom(), "BC");           
        PGPPublicKey                 puK = pgpPriv.getSecretKey(encP.getKeyID()).getPublicKey();
       
        cPk.addMethod(puK);
       
        OutputStream    cOut = cPk.open(new UncloseableOutputStream(cbOut), shortText.length);

        cOut.write(shortText);

        cOut.close();

        pgpF = new PGPObjectFactory(cbOut.toByteArray());

        encList = (PGPEncryptedDataList)pgpF.nextObject();
   
        encP = (PGPPublicKeyEncryptedData)encList.get(0);
       
        pgpPrivKey = pgpPriv.getSecretKey(encP.getKeyID()).extractPrivateKey(pass, "BC");

        if (encP.getSymmetricAlgorithm(pgpPrivKey, "BC") != SymmetricKeyAlgorithmTags.CAST5)
        {
            fail("symmetric algorithm mismatch");
        }

        clear = encP.getDataStream(pgpPrivKey, "BC");
       
        bOut.reset();
       
        while ((ch = clear.read()) >= 0)
        {
            bOut.write(ch);
        }

        out = bOut.toByteArray();

        if (!areEqual(out, shortText))
        {
            fail("wrong plain text in generated short text packet");
        }
       
        //
        // encrypt
        //
        cbOut = new ByteArrayOutputStream();
        cPk = new PGPEncryptedDataGenerator(SymmetricKeyAlgorithmTags.CAST5, new SecureRandom(), "BC");           
        puK = pgpPriv.getSecretKey(encP.getKeyID()).getPublicKey();
       
        cPk.addMethod(puK);

        cOut = cPk.open(new UncloseableOutputStream(cbOut), text.length);

        cOut.write(text);

        cOut.close();

        pgpF = new PGPObjectFactory(cbOut.toByteArray());

        encList = (PGPEncryptedDataList)pgpF.nextObject();
   
        encP = (PGPPublicKeyEncryptedData)encList.get(0);
       
        pgpPrivKey = pgpPriv.getSecretKey(encP.getKeyID()).extractPrivateKey(pass, "BC");

        clear = encP.getDataStream(pgpPrivKey, "BC");
       
        bOut.reset();
       
        while ((ch = clear.read()) >= 0)
        {
            bOut.write(ch);
        }

        out = bOut.toByteArray();

        if (!areEqual(out, text))
        {
            fail("wrong plain text in generated packet");
        }
       
        //
        // read public key with sub key.
        //
        pgpF = new PGPObjectFactory(subPubKey);
        Object    o;
       
        while ((o = pgpFact.nextObject()) != null)
        {
            // System.out.println(o);
        }

        //
        // key pair generation - CAST5 encryption
        //
        char[]                    passPhrase = "hello".toCharArray();
       
        KeyPairGenerator    kpg = KeyPairGenerator.getInstance("RSA", "BC");
   
        kpg.initialize(1024);
   
        KeyPair                    kp = kpg.generateKeyPair();

        PGPSecretKey    secretKey = new PGPSecretKey(PGPSignature.DEFAULT_CERTIFICATION, PublicKeyAlgorithmTags.RSA_GENERAL, kp.getPublic(), kp.getPrivate(), new Date(), "fred", SymmetricKeyAlgorithmTags.CAST5, passPhrase, null, null, new SecureRandom(), "BC");
   
        PGPPublicKey    key = secretKey.getPublicKey();

        it = key.getUserIDs();

        uid = (String)it.next();

        it = key.getSignaturesForID(uid);

        sig = (PGPSignature)it.next();

        sig.initVerify(key, "BC");

        if (!sig.verifyCertification(uid, key))
        {
            fail("failed to verify certification");
        }

        pgpPrivKey = secretKey.extractPrivateKey(passPhrase, "BC");
       
        key = PGPPublicKey.removeCertification(key, uid, sig);
       
        if (key == null)
        {
            fail("failed certification removal");
        }
       
        byte[]    keyEnc = key.getEncoded();
       
        key = PGPPublicKey.addCertification(key, uid, sig);
       
        keyEnc = key.getEncoded();

        PGPSignatureGenerator sGen = new PGPSignatureGenerator(PublicKeyAlgorithmTags.RSA_GENERAL, HashAlgorithmTags.SHA1, "BC");
       
        sGen.initSign(PGPSignature.KEY_REVOCATION, secretKey.extractPrivateKey(passPhrase, "BC"));

        sig = sGen.generateCertification(key);

        key = PGPPublicKey.addCertification(key, sig);

        keyEnc = key.getEncoded();

        PGPPublicKeyRing    tmpRing = new PGPPublicKeyRing(keyEnc);

        key = tmpRing.getPublicKey();

        Iterator            sgIt = key.getSignaturesOfType(PGPSignature.KEY_REVOCATION);

        sig = (PGPSignature)sgIt.next();

        sig.initVerify(key, "BC");

        if (!sig.verifyCertification(key))
        {
            fail("failed to verify revocation certification");
        }

        //
        // use of PGPKeyPair
        //
        PGPKeyPair    pgpKp = new PGPKeyPair(PGPPublicKey.RSA_GENERAL , kp.getPublic(), kp.getPrivate(), new Date(), "BC");
       
        PGPPublicKey k1 = pgpKp.getPublicKey();
       
        PGPPrivateKey k2 = pgpKp.getPrivateKey();
       
        k1.getEncoded();

        mixedTest(k2, k1);
View Full Code Here


        //
        // Read the private key
        //
        PGPSecretKeyRing        sKey = new PGPSecretKeyRing(testPrivKey);
        PGPPrivateKey           pgpPrivKey = sKey.getSecretKey().extractPrivateKey(pass, "BC");
       
        //
        // test signature message
        //
        PGPObjectFactory        pgpFact = new PGPObjectFactory(sig1);

        PGPCompressedData       c1 = (PGPCompressedData)pgpFact.nextObject();

        pgpFact = new PGPObjectFactory(c1.getDataStream());
       
        PGPOnePassSignatureList p1 = (PGPOnePassSignatureList)pgpFact.nextObject();
       
        PGPOnePassSignature     ops = p1.get(0);
       
        PGPLiteralData          p2 = (PGPLiteralData)pgpFact.nextObject();

        InputStream             dIn = p2.getInputStream();
        int                     ch;

        ops.initVerify(pubKey, "BC");
       
        while ((ch = dIn.read()) >= 0)
        {
            ops.update((byte)ch);
        }

        PGPSignatureList        p3 = (PGPSignatureList)pgpFact.nextObject();

        if (!ops.verify(p3.get(0)))
        {
            fail("Failed signature check");
        }
       
        //
        // signature generation
        //
        generateTest(sKey, pubKey, pgpPrivKey);
       
        //
        // signature generation - canonical text
        //
        String                      data = "hello world!";
        ByteArrayOutputStream       bOut = new ByteArrayOutputStream();
        ByteArrayInputStream        testIn = new ByteArrayInputStream(data.getBytes());
        PGPSignatureGenerator       sGen = new PGPSignatureGenerator(PGPPublicKey.DSA, PGPUtil.SHA1, "BC");

        sGen.initSign(PGPSignature.CANONICAL_TEXT_DOCUMENT, pgpPrivKey);

        PGPCompressedDataGenerator  cGen = new PGPCompressedDataGenerator(
            PGPCompressedData.ZIP);

        BCPGOutputStream bcOut = new BCPGOutputStream(
            cGen.open(new UncloseableOutputStream(bOut)));

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

        PGPLiteralDataGenerator     lGen = new PGPLiteralDataGenerator();
        Date testDate = new Date((System.currentTimeMillis() / 1000) * 1000);
        OutputStream lOut = lGen.open(
            new UncloseableOutputStream(bcOut),
            PGPLiteralData.TEXT,
            "_CONSOLE",
            data.getBytes().length,
            testDate);

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

        lGen.close();

        sGen.generate().encode(bcOut);

        cGen.close();

        //
        // verify generated signature - canconical text
        //
        pgpFact = new PGPObjectFactory(bOut.toByteArray());

        c1 = (PGPCompressedData)pgpFact.nextObject();

        pgpFact = new PGPObjectFactory(c1.getDataStream());
   
        p1 = (PGPOnePassSignatureList)pgpFact.nextObject();
   
        ops = p1.get(0);
   
        p2 = (PGPLiteralData)pgpFact.nextObject();
        if (!p2.getModificationTime().equals(testDate))
        {
            fail("Modification time not preserved");
        }

        dIn = p2.getInputStream();

        ops.initVerify(pubKey, "BC");
   
        while ((ch = dIn.read()) >= 0)
        {
            ops.update((byte)ch);
        }

        p3 = (PGPSignatureList)pgpFact.nextObject();

        if (!ops.verify(p3.get(0)))
        {
            fail("Failed generated signature check");
        }
       
        //
        // Read the public key with user attributes
        //
        pgpPub = new PGPPublicKeyRing(testPubWithUserAttr);

        pubKey = pgpPub.getPublicKey();

        Iterator it = pubKey.getUserAttributes();
        int      count = 0;
        while (it.hasNext())
        {
            PGPUserAttributeSubpacketVector attributes = (PGPUserAttributeSubpacketVector)it.next();
           
            Iterator    sigs = pubKey.getSignaturesForUserAttribute(attributes);
            int sigCount = 0;
            while (sigs.hasNext())
            {
                sigs.next();
               
                sigCount++;
            }
           
            if (sigCount != 1)
            {
                fail("Failed user attributes signature check");
            }
            count++;
        }

        if (count != 1)
        {
            fail("Failed user attributes check");
        }

        byte[]  pgpPubBytes = pgpPub.getEncoded();

        pgpPub = new PGPPublicKeyRing(pgpPubBytes);

           pubKey = pgpPub.getPublicKey();

        it = pubKey.getUserAttributes();
        count = 0;
        while (it.hasNext())
        {
            it.next();
            count++;
        }

        if (count != 1)
        {
            fail("Failed user attributes reread");
        }

        //
        // reading test extra data - key with edge condition for DSA key password.
        //
        char []   passPhrase = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

        sKey = new PGPSecretKeyRing(testPrivKey2);
        pgpPrivKey = sKey.getSecretKey().extractPrivateKey(passPhrase, "BC");

        byte[]    bytes = pgpPrivKey.getKey().getEncoded();
       
        //
        // reading test - aes256 encrypted passphrase.
        //
        sKey = new PGPSecretKeyRing(aesSecretKey);
        pgpPrivKey = sKey.getSecretKey().extractPrivateKey(pass, "BC");

        bytes = pgpPrivKey.getKey().getEncoded();
       
        //
        // reading test - twofish encrypted passphrase.
        //
        sKey = new PGPSecretKeyRing(twofishSecretKey);
        pgpPrivKey = sKey.getSecretKey().extractPrivateKey(pass, "BC");

        bytes = pgpPrivKey.getKey().getEncoded();
       
        //
        // use of PGPKeyPair
        //
        KeyPairGenerator    kpg = KeyPairGenerator.getInstance("DSA", "BC");
       
        kpg.initialize(512);
       
        KeyPair kp = kpg.generateKeyPair();
       
        PGPKeyPair    pgpKp = new PGPKeyPair(PGPPublicKey.DSA , kp.getPublic(), kp.getPrivate(), new Date(), "BC");
       
        PGPPublicKey k1 = pgpKp.getPublicKey();
       
        PGPPrivateKey k2 = pgpKp.getPrivateKey();
    }
View Full Code Here

    private PGPSignatureGenerator createPGPSignatureGenerator(final char[] keyPassPhrase) throws PGPException {
        final PGPContentSignerBuilder csBuilder = new JcaPGPContentSignerBuilder(key
                .getPublicKey().getAlgorithm(), hashAlgorithm);
        final PGPSignatureGenerator generator = new PGPSignatureGenerator(csBuilder);
        final PGPPrivateKey privateKey = extractPGPPrivateKey(keyPassPhrase);

        init(generator, privateKey);
        return generator;
    }
View Full Code Here

                setProvider(BouncyCastleProvider.PROVIDER_NAME).
                build();
        PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder(calcProvider).
                setProvider(BouncyCastleProvider.PROVIDER_NAME).
                build(keyPassPhrase);
        final PGPPrivateKey pgpPrivKey = key.extractPrivateKey(decryptor);
        return pgpPrivKey;
    }
View Full Code Here

    public static PGPPrivateKey findPrivateKey(CamelContext context, String keychainFilename, byte[] secKeyRing,
        InputStream encryptedInput, String passphrase) throws IOException, PGPException, NoSuchProviderException {

        InputStream keyChainInputStream = determineKeyRingInputStream(context, keychainFilename, secKeyRing, true);
        PGPPrivateKey privKey = null;
        try {
            privKey = findPrivateKey(keyChainInputStream, encryptedInput, passphrase);
        } finally {
            IOHelper.close(keyChainInputStream);
        }
View Full Code Here

        } else {
            enc = (PGPEncryptedDataList) factory.nextObject();
        }
        encryptedInput.reset(); // nextObject() method reads from the InputStream, so rewind it!
        Iterator<?> encryptedDataObjects = enc.getEncryptedDataObjects();
        PGPPrivateKey privateKey = null;
        PGPPublicKeyEncryptedData encryptedData;
        while (privateKey == null && encryptedDataObjects.hasNext()) {
            encryptedData = (PGPPublicKeyEncryptedData) encryptedDataObjects.next();
            PGPSecretKey pgpSecKey = pgpSec.getSecretKey(encryptedData.getKeyID());
            privateKey = pgpSecKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(passphrase.toCharArray()));
View Full Code Here

        for (Iterator<?> i = pgpSec.getKeyRings(); i.hasNext() && pgpSecKey == null;) {
            Object data = i.next();
            if (data instanceof PGPSecretKeyRing) {
                PGPSecretKeyRing keyring = (PGPSecretKeyRing) data;
                PGPSecretKey secKey = keyring.getSecretKey();
                PGPPrivateKey privateKey = secKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(passphrase.toCharArray()));
                if (privateKey != null) {
                    pgpSecKey = secKey;
                }
            }
        }
View Full Code Here

        PGPSecretKey sigSecretKey = PGPDataFormatUtil.findSecretKey(exchange.getContext(), sigKeyFileName, sigKeyRing, sigKeyPassword);
        if (sigSecretKey == null) {
            throw new IllegalArgumentException("Signature secret key is null, cannot proceed");
        }

        PGPPrivateKey sigPrivateKey = sigSecretKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(sigKeyPassword.toCharArray()));
        if (sigPrivateKey == null) {
            throw new IllegalArgumentException("Signature private key is null, cannot proceed");
        }

        PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
View Full Code Here

    public Object unmarshal(Exchange exchange, InputStream encryptedStream) throws Exception {
        if (encryptedStream == null) {
            return null;
        }

        PGPPrivateKey key = PGPDataFormatUtil.findPrivateKey(exchange.getContext(), findKeyFileName(exchange), findEncryptionKeyRing(exchange), encryptedStream, findKeyPassword(exchange));
        if (key == null) {
            throw new IllegalArgumentException("Private key is null, cannot proceed");
        }

        InputStream in;
View Full Code Here

    public Object unmarshal(Exchange exchange, InputStream encryptedStream) throws Exception {
        if (encryptedStream == null) {
            return null;
        }

        PGPPrivateKey key = PGPDataFormatUtil.findPrivateKey(exchange.getContext(), keyFileName, encryptedStream, password);
        if (key == null) {
            throw new IllegalArgumentException("Private key is null, cannot proceed");
        }

        InputStream in = new ByteArrayInputStream(IOUtils.toByteArray(encryptedStream));
View Full Code Here

TOP

Related Classes of org.bouncycastle.openpgp.PGPPrivateKey

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.