Package org.bouncycastle.bcpg

Examples of org.bouncycastle.bcpg.BCPGOutputStream


       
        //
        // write a public key
        //
        ByteArrayOutputStream    bOut = new ByteArrayOutputStream();
        BCPGOutputStream         pOut = new BCPGOutputStream(bOut);
       
        pgpPub.encode(pOut);

        if (!areEqual(bOut.toByteArray(), testPubKey))   
        {
            fail("public key rewrite failed");
        }
       
        //
        // Read the public key
        //
        PGPPublicKeyRing     pgpPubV3 = new PGPPublicKeyRing(testPubKeyV3);
        PublicKey            pubKeyV3 = pgpPub.getPublicKey().getKey("BC");

        //
        // write a V3 public key
        //
        bOut = new ByteArrayOutputStream();
        pOut = new BCPGOutputStream(bOut);
       
        pgpPubV3.encode(pOut);

        //
        // Read a v3 private key
        //
        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);

        //
        // key pair generation - AES_256 encryption.
        //
        kp = kpg.generateKeyPair();

        secretKey = new PGPSecretKey(PGPSignature.DEFAULT_CERTIFICATION, PublicKeyAlgorithmTags.RSA_GENERAL, kp.getPublic(), kp.getPrivate(), new Date(), "fred", SymmetricKeyAlgorithmTags.AES_256, passPhrase, null, null, new SecureRandom(), "BC");
   
        secretKey.extractPrivateKey(passPhrase, "BC");
       
        secretKey.encode(new ByteArrayOutputStream());
       
        //
        // secret key password changing.
        //
        String  newPass = "newPass";
       
        secretKey = PGPSecretKey.copyWithNewPassword(secretKey, passPhrase, newPass.toCharArray(), secretKey.getKeyEncryptionAlgorithm(), new SecureRandom(), "BC");
       
        secretKey.extractPrivateKey(newPass.toCharArray(), "BC");
       
        secretKey.encode(new ByteArrayOutputStream());
       
        key = secretKey.getPublicKey();

        key.encode(new ByteArrayOutputStream());
       
        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(newPass.toCharArray(), "BC");
       
        //
        // signature generation
        //
        String                                data = "hello world!";
       
        bOut = new ByteArrayOutputStream();
       
        ByteArrayInputStream        testIn = new ByteArrayInputStream(data.getBytes());
       
        sGen = new PGPSignatureGenerator(PublicKeyAlgorithmTags.RSA_GENERAL, HashAlgorithmTags.SHA1, "BC");
   
        sGen.initSign(PGPSignature.BINARY_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.BINARY,
            "_CONSOLE",
            data.getBytes().length,
            testDate);

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

        lOut.close();

        sGen.generate().encode(bcOut);

        bcOut.close();

        //
        // verify generated signature
        //
        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: " + p2.getModificationTime() + " " + testDate);
        }

        dIn = p2.getInputStream();

        ops.initVerify(secretKey.getPublicKey(), "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");
        }
       
        //
        // signature generation - version 3
        //
        bOut = new ByteArrayOutputStream();
       
        testIn = new ByteArrayInputStream(data.getBytes());
        PGPV3SignatureGenerator    sGenV3 = new PGPV3SignatureGenerator(PGPPublicKey.RSA_GENERAL, PGPUtil.SHA1, "BC");
   
        sGen.initSign(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);

        cGen = new PGPCompressedDataGenerator(
                                                                PGPCompressedData.ZIP);

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

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

        lGen = new PGPLiteralDataGenerator();
        lOut = lGen.open(
            new UncloseableOutputStream(bcOut),
            PGPLiteralData.BINARY,
            "_CONSOLE",
            data.getBytes().length,
            testDate);

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

        lOut.close();

        sGen.generate().encode(bcOut);

        bcOut.close();

        //
        // verify generated signature
        //
        pgpFact = new PGPObjectFactory(bOut.toByteArray());
View Full Code Here


            throw new IllegalStateException("no encryption methods specified");
        }

        Key key = null;

        pOut = new BCPGOutputStream(out);

        if (methods.size() == 1)
        {   
            if (methods.get(0) instanceof PBEMethod)
            {
                PBEMethod m = (PBEMethod)methods.get(0);
               
                key = m.getKey();
            }
            else
            {
                key = PGPUtil.makeRandomKey(defAlgorithm, rand);
                byte[] sessionInfo = createSessionInfo(defAlgorithm, key);

                PubMethod m = (PubMethod)methods.get(0);

                try
                {
                    m.addSessionInfo(sessionInfo);
                }
                catch (Exception e)
                {
                    throw new PGPException("exception encrypting session key", e);
                }
            }
           
            pOut.writePacket((ContainedPacket)methods.get(0));
        }
        else // multiple methods
        {
            key = PGPUtil.makeRandomKey(defAlgorithm, rand);
            byte[] sessionInfo = createSessionInfo(defAlgorithm, key);

            for (int i = 0; i != methods.size(); i++)
            {
                EncMethod m = (EncMethod)methods.get(i);

                try
                {
                    m.addSessionInfo(sessionInfo);
                }
                catch (Exception e)
                {
                    throw new PGPException("exception encrypting session key", e);
                }

                pOut.writePacket(m);
            }
        }

        String cName = PGPUtil.getSymmetricCipherName(defAlgorithm);

        if (cName == null)
        {
            throw new PGPException("null cipher specified");
        }

        try
        {
            if (withIntegrityPacket)
            {
                c = Cipher.getInstance(cName + "/CFB/NoPadding", defProvider);
            }
            else
            {
                c = Cipher.getInstance(cName + "/OpenPGPCFB/NoPadding", defProvider);
            }

            byte[] iv = new byte[c.getBlockSize()];
            c.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv), rand);
           
            if (buffer == null)
            {
                //
                // we have to add block size + 2 for the generated IV and + 1 + 22 if integrity protected
                //
                if (withIntegrityPacket)
                {
                    pOut = new BCPGOutputStream(out, PacketTags.SYM_ENC_INTEGRITY_PRO, length + c.getBlockSize() + 2 + 1 + 22);
                    pOut.write(1);        // version number
                }
                else
                {
                    pOut = new BCPGOutputStream(out, PacketTags.SYMMETRIC_KEY_ENC, length + c.getBlockSize() + 2, oldFormat);
                }
            }
            else
            {
                if (withIntegrityPacket)
                {
                    pOut = new BCPGOutputStream(out, PacketTags.SYM_ENC_INTEGRITY_PRO, buffer);
                    pOut.write(1);        // version number
                }
                else
                {
                    pOut = new BCPGOutputStream(out, PacketTags.SYMMETRIC_KEY_ENC, buffer);
                }
            }


            OutputStream genOut = cOut = new CipherOutputStream(pOut, c);
View Full Code Here

            if (digestOut != null)
            {
                //
                // hand code a mod detection packet
                //
                BCPGOutputStream bOut = new BCPGOutputStream(digestOut, PacketTags.MOD_DETECTION_CODE, 20);

                bOut.flush();
                digestOut.flush();

                byte[] dig = digestOut.getMessageDigest().digest();

                cOut.write(dig);
View Full Code Here

   
    public void encode(
        OutputStream    outStream)
        throws IOException
    {
        BCPGOutputStream    out;
       
        if (outStream instanceof BCPGOutputStream)
        {
            out = (BCPGOutputStream)outStream;
        }
        else
        {
            out = new BCPGOutputStream(outStream);
        }

        out.writePacket(sigPack);
    }
View Full Code Here

            PGPPrivateKey pgpPrivKey = pgpSec.extractPrivateKey(password.toCharArray(), BouncyCastleProvider.PROVIDER_NAME);       
            PGPSignatureGenerator sGen = new PGPSignatureGenerator(pgpSec.getPublicKey().getAlgorithm(), PGPUtil.SHA1, BouncyCastleProvider.PROVIDER_NAME);
            sGen.initSign(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);
   
            in = new FileInputStream(src);
            out = new BCPGOutputStream(new ArmoredOutputStream(new FileOutputStream(dest)));
           
            int ch = 0;
            while ((ch = in.read()) >= 0) {
                sGen.update((byte) ch);
            }
View Full Code Here

        sGen.setHashedSubpackets(spGen.generate());
       
        PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(
                                                                PGPCompressedData.ZIP);

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

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

        PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();
View Full Code Here

        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();
View Full Code Here

        final OutputStream armoredOutputStream = new ArmoredOutputStream(byteArrayOutputStream);
        final PGPSignatureGenerator signatureGenerator = createPGPSignatureGenerator(keyPassPhraseString.toCharArray());

        final PGPCompressedDataGenerator generator = createZlibCompressedDataGenerator();

        final BCPGOutputStream outputStream = new BCPGOutputStream(generator.open(armoredOutputStream));

        signatureGenerator.generateOnePassVersion(false).encode(outputStream);
        encode(licensePlain, using(signatureGenerator), to(outputStream));
        signatureGenerator.generate().encode(outputStream);
        generator.close();
View Full Code Here

        }

        armoredOutput.endClearText();
       
        PGPSignature signature = signatureGenerator.generate();
        signature.encode(new BCPGOutputStream(armoredOutput));
       
        armoredOutput.close();
    }
View Full Code Here

TOP

Related Classes of org.bouncycastle.bcpg.BCPGOutputStream

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.