Package java.security

Examples of java.security.KeyPair


    public void performTest()
        throws Exception
    {
        String signDN = "O=Bouncy Castle, C=AU";
        KeyPair signKP = OCSPTestUtil.makeKeyPair();
        X509Certificate testCert = OCSPTestUtil.makeCertificate(signKP, signDN, signKP, signDN);

        String origDN = "CN=Eric H. Echidna, E=eric@bouncycastle.org, O=Bouncy Castle, C=AU";
        GeneralName origName = new GeneralName(new X509Name(origDN));

        //
        // general id value for our test issuer cert and a serial number.
        //
        CertificateID id = new CertificateID(CertificateID.HASH_SHA1, testCert, BigInteger.valueOf(1));

        //
        // general id value for our test issuer cert and a serial number and the default provider
        //
        id = new CertificateID(CertificateID.HASH_SHA1, testCert, BigInteger.valueOf(1), null);

        //
        // basic request generation
        //
        OCSPReqGenerator gen = new OCSPReqGenerator();

        gen.addRequest(
            new CertificateID(CertificateID.HASH_SHA1, testCert, BigInteger.valueOf(1)));

        OCSPReq req = gen.generate();

        if (req.isSigned())
        {
            fail("signed but shouldn't be");
        }

        X509Certificate[] certs = req.getCerts("BC");

        if (certs != null)
        {
            fail("null certs expected, but not found");
        }

        Req[] requests = req.getRequestList();

        if (!requests[0].getCertID().equals(id))
        {
            fail("Failed isFor test");
        }

        //
        // request generation with signing
        //
        X509Certificate[] chain = new X509Certificate[1];

        gen = new OCSPReqGenerator();

        gen.setRequestorName(new GeneralName(GeneralName.directoryName, new X509Principal("CN=fred")));

        gen.addRequest(
            new CertificateID(CertificateID.HASH_SHA1, testCert, BigInteger.valueOf(1)));

        chain[0] = testCert;

        req = gen.generate("SHA1withRSA", signKP.getPrivate(), chain, "BC");

        if (!req.isSigned())
        {
            fail("not signed but should be");
        }

        if (!req.verify(signKP.getPublic(), "BC"))
        {
            fail("signature failed to verify");
        }

        requests = req.getRequestList();

        if (!requests[0].getCertID().equals(id))
        {
            fail("Failed isFor test");
        }

        certs = req.getCerts("BC");

        if (certs == null)
        {
            fail("null certs found");
        }

        if (certs.length != 1 || !certs[0].equals(testCert))
        {
            fail("incorrect certs found in request");
        }

        //
        // encoding test
        //
        byte[] reqEnc = req.getEncoded();

        OCSPReq newReq = new OCSPReq(reqEnc);

        if (!newReq.verify(signKP.getPublic(), "BC"))
        {
            fail("newReq signature failed to verify");
        }

        //
        // request generation with signing and nonce
        //
        chain = new X509Certificate[1];

        gen = new OCSPReqGenerator();

        Vector oids = new Vector();
        Vector values = new Vector();
        byte[] sampleNonce = new byte[16];
        Random rand = new Random();

        rand.nextBytes(sampleNonce);

        gen.setRequestorName(new GeneralName(GeneralName.directoryName, new X509Principal("CN=fred")));

        oids.addElement(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
        values.addElement(new X509Extension(false, new DEROctetString(new DEROctetString(sampleNonce))));

        gen.setRequestExtensions(new X509Extensions(oids, values));

        gen.addRequest(
            new CertificateID(CertificateID.HASH_SHA1, testCert, BigInteger.valueOf(1)));

        chain[0] = testCert;

        req = gen.generate("SHA1withRSA", signKP.getPrivate(), chain, "BC");

        if (!req.isSigned())
        {
            fail("not signed but should be");
        }

        if (!req.verify(signKP.getPublic(), "BC"))
        {
            fail("signature failed to verify");
        }

        //
View Full Code Here


        String keyStorePass = "myPass";
        ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(
                ecParameterEncoded));
        X9ECParameters params = X9ECParameters.getInstance(in
                .readObject());
        KeyPair kp = null;
        boolean success = false;
        while (!success)
        {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECDSA");
            kpg.initialize(new ECParameterSpec(params.getCurve(),
                    params.getG(), params.getN(), params.getH(), params
                            .getSeed()));
            kp = kpg.generateKeyPair();
            // The very old Problem... we need a certificate chain to
            // save a private key...
            ECPublicKey pubKey = (ECPublicKey)kp.getPublic();
            if (!compress)
            {
                ((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED");
            }
            byte[] x = pubKey.getQ().getX().toBigInteger().toByteArray();
            byte[] y = pubKey.getQ().getY().toBigInteger().toByteArray();
            if (x.length == y.length)
            {
                success = true;
            }
        }

        // The very old Problem... we need a certificate chain to
        // save a private key...

        Certificate[] chain = new Certificate[] { generateSelfSignedSoftECCert(
                kp, compress) };

        KeyStore keyStore = KeyStore.getInstance("BKS");
        keyStore.load(null, keyStorePass.toCharArray());

        keyStore.setCertificateEntry("ECCert", chain[0]);

        ECPrivateKey privateECKey = (ECPrivateKey)kp.getPrivate();
        keyStore.setKeyEntry("ECPrivKey", privateECKey, keyStorePass
                .toCharArray(), chain);

        // Test ec sign / verify
        ECPublicKey pub = (ECPublicKey)kp.getPublic();
        String oldPrivateKey = new String(Hex.encode(privateECKey.getEncoded()));
        String oldPublicKey = new String(Hex.encode(pub.getEncoded()));
        ECPrivateKey newKey = (ECPrivateKey)keyStore.getKey("ECPrivKey",
                keyStorePass.toCharArray());
        ECPublicKey newPubKey = (ECPublicKey)keyStore.getCertificate(
View Full Code Here

    {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyName, "BC");

        kpg.initialize(keySize);

        KeyPair kp = kpg.genKeyPair();

        Hashtable                   attrs = new Hashtable();

        attrs.put(X509Principal.C, "AU");
        attrs.put(X509Principal.O, "The Legion of the Bouncy Castle");
        attrs.put(X509Principal.L, "Melbourne");
        attrs.put(X509Principal.ST, "Victoria");
        attrs.put(X509Principal.EmailAddress, "feedback-crypto@bouncycastle.org");

        Vector                      order = new Vector();

        order.addElement(X509Principal.C);
        order.addElement(X509Principal.O);
        order.addElement(X509Principal.L);
        order.addElement(X509Principal.ST);
        order.addElement(X509Principal.EmailAddress);

        X509Name    subject = new X509Name(order, attrs);

        PKCS10CertificationRequest req1 = new PKCS10CertificationRequest(
                                                    sigName,
                                                    subject,
                                                    kp.getPublic(),
                                                    null,
                                                    kp.getPrivate(), provider);
                           
        byte[]  bytes = req1.getEncoded();

        PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bytes);
View Full Code Here

        throws Exception
    {
        KeyPairGenerator     kpGen = KeyPairGenerator.getInstance("RSA", "BC");
        X509V2CRLGenerator   crlGen = new X509V2CRLGenerator();
        Date                 now = new Date();
        KeyPair              pair = kpGen.generateKeyPair();
       
        crlGen.setIssuerDN(new X500Principal("CN=Test CA"));
       
        crlGen.setThisUpdate(now);
        crlGen.setNextUpdate(new Date(now.getTime() + 100000));
        crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
       
        Vector extOids = new Vector();
        Vector extValues = new Vector();
       
        CRLReason crlReason = CRLReason.lookup(CRLReason.privilegeWithdrawn);
       
        try
        {
            extOids.addElement(X509Extensions.ReasonCode);
            extValues.addElement(new X509Extension(false, new DEROctetString(crlReason.getEncoded())));
        }
        catch (IOException e)
        {
            throw new IllegalArgumentException("error encoding reason: " + e);
        }
       
        X509Extensions entryExtensions = new X509Extensions(extOids, extValues);
       
        crlGen.addCRLEntry(BigInteger.ONE, now, entryExtensions);
       
        crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.getPublic()));
       
        X509CRL    crl = crlGen.generate(pair.getPrivate(), "BC");
       
        if (!crl.getIssuerX500Principal().equals(new X500Principal("CN=Test CA")))
        {
            fail("failed CRL issuer test");
        }
       
        byte[] authExt = crl.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
       
        if (authExt == null)
        {
            fail("failed to find CRL extension");
        }
       
        AuthorityKeyIdentifier authId = new AuthorityKeyIdentifierStructure(authExt);
       
        X509CRLEntry entry = crl.getRevokedCertificate(BigInteger.ONE);
       
        if (entry == null)
        {
            fail("failed to find CRL entry");
        }
       
        if (!entry.getSerialNumber().equals(BigInteger.ONE))
        {
            fail("CRL cert serial number does not match");
        }
       
        if (!entry.hasExtensions())
        {
            fail("CRL entry extension not found");
        }
   
        byte[]  ext = entry.getExtensionValue(X509Extensions.ReasonCode.getId());
   
        if (ext != null)
        {
            DEREnumerated   reasonCode = (DEREnumerated)X509ExtensionUtil.fromExtensionValue(ext);
                                                                      
            if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn)
            {
                fail("CRL entry reasonCode wrong");
            }
        }
        else
        {
            fail("CRL entry reasonCode not found");
        }
       
        //
        // check loading of existing CRL
        //
        crlGen = new X509V2CRLGenerator();
        now = new Date();
       
        crlGen.setIssuerDN(new X500Principal("CN=Test CA"));
       
        crlGen.setThisUpdate(now);
        crlGen.setNextUpdate(new Date(now.getTime() + 100000));
        crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
       
        crlGen.addCRL(crl);
       
        crlGen.addCRLEntry(BigInteger.valueOf(2), now, entryExtensions);
       
        crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.getPublic()));
       
        X509CRL    newCrl = crlGen.generate(pair.getPrivate(), "BC");
       
        int     count = 0;
        boolean oneFound = false;
        boolean twoFound = false;
       
View Full Code Here

        KeyPairGenerator    g = KeyPairGenerator.getInstance("GOST3410", "BC");
        GOST3410ParameterSpec gost3410P = new GOST3410ParameterSpec("GostR3410-94-CryptoPro-A");

        g.initialize(gost3410P, new SecureRandom());

        KeyPair p = g.generateKeyPair();

        privKey = p.getPrivate();
        pubKey = p.getPublic();

        //
        // distinguished name table.
        //
        Hashtable                   attrs = new Hashtable();
View Full Code Here

    }

    private void createPSSCert(String algorithm)
        throws Exception
    {
        KeyPair pair = generateLongFixedKeys();

        PrivateKey privKey = pair.getPrivate();
        PublicKey pubKey = pair.getPublic();

        //
        // distinguished name table.
        //
        Vector                      ord = new Vector();
View Full Code Here

            new BigInteger("1a8b38f398fa712049898d7fb79ee0a77668791299cdfa09efc0e507acb21ed74301ef5bfd48be455eaeb6e1678255827580a8e4e8e14151d1510a82a3f2e729",16),
            new BigInteger("27156aba4126d24a81f3a528cbfb27f56886f840a9f6e86e17a44b94fe9319584b8e22fdde1e5a2e3bd8aa5ba8d8584194eb2190acf832b847f13a3d24a79f4d",16));

        KeyFactory fact = KeyFactory.getInstance("RSA", "BC");

        return new KeyPair(fact.generatePublic(pubKeySpec), fact.generatePrivate(privKeySpec));
    }
View Full Code Here

    }

    private void testNullDerNullCert()
        throws Exception
    {
        KeyPair pair = generateLongFixedKeys();
        PublicKey pubKey = pair.getPublic();
        PrivateKey privKey = pair.getPrivate();

        X509V3CertificateGenerator  certGen = new X509V3CertificateGenerator();

        certGen.setSerialNumber(BigInteger.valueOf(1));
        certGen.setIssuerDN(new X509Principal("CN=Test"));
View Full Code Here

        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ElGamal", "BC");
        byte[]           in = "This is a test".getBytes();

        keyGen.initialize(elParams);
       
        KeyPair         keyPair = keyGen.generateKeyPair();
        SecureRandom    rand = new SecureRandom();

        checkKeySize(privateValueSize, keyPair);

        Cipher  cipher = Cipher.getInstance("ElGamal", "BC");
       
        cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic(), rand);
       
        if (cipher.getOutputSize(in.length) != (size / 8) * 2)
        {
            fail("getOutputSize wrong on encryption");
        }

        byte[]  out = cipher.doFinal(in);
       
        cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
       
        if (cipher.getOutputSize(out.length) != (size / 8) - 1)
        {
            fail("getOutputSize wrong on decryption");
        }
       
        //
        // No Padding - maximum length
        //
        byte[]  modBytes = ((DHPublicKey)keyPair.getPublic()).getParams().getP().toByteArray();
        byte[]  maxInput = new byte[modBytes.length - 1];

        maxInput[0] |= 0x7f;

        cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic(), rand);

        out = cipher.doFinal(maxInput);

        cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());

        out = cipher.doFinal(out);

        if (!areEqual(out, maxInput))
        {
            fail("NoPadding test failed on decrypt expected " + new String(Hex.encode(maxInput)) + " got " + new String(Hex.encode(out)));
        }

        //
        // encrypt/decrypt
        //

        Cipher  c1 = Cipher.getInstance("ElGamal", "BC");
        Cipher  c2 = Cipher.getInstance("ElGamal", "BC");

        c1.init(Cipher.ENCRYPT_MODE, keyPair.getPublic(), rand);

        byte[]  out1 = c1.doFinal(in);

        c2.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());

        byte[]  out2 = c2.doFinal(out1);

        if (!areEqual(in, out2))
        {
            fail(size + " encrypt test failed");
        }
       
        //
        // encrypt/decrypt with update
        //
        int outLen = c1.update(in, 0, 2, out1, 0);
       
        outLen += c1.doFinal(in, 2, in.length - 2, out1, outLen);

        outLen = c2.update(out1, 0, 2, out2, 0);
       
        outLen += c2.doFinal(out1, 2, out1.length - 2, out2, outLen);

        if (!areEqual(in, out2))
        {
            fail(size + " encrypt with update test failed");
        }

        //
        // public key encoding test
        //
        byte[]                  pubEnc = keyPair.getPublic().getEncoded();
        KeyFactory              keyFac = KeyFactory.getInstance("ElGamal", "BC");
        X509EncodedKeySpec      pubX509 = new X509EncodedKeySpec(pubEnc);
        DHPublicKey             pubKey = (DHPublicKey)keyFac.generatePublic(pubX509);
        DHParameterSpec         spec = pubKey.getParams();

        if (!spec.getG().equals(elParams.getG()) || !spec.getP().equals(elParams.getP()))
        {
            fail(size + " bit public key encoding/decoding test failed on parameters");
        }

        if (!((DHPublicKey)keyPair.getPublic()).getY().equals(pubKey.getY()))
        {
            fail(size + " bit public key encoding/decoding test failed on y value");
        }

        //
        // public key serialisation test
        //
        pubKey = (DHPublicKey)serializeDeserialize(keyPair.getPublic());
        spec = pubKey.getParams();

        if (!spec.getG().equals(elParams.getG()) || !spec.getP().equals(elParams.getP()))
        {
            fail(size + " bit public key serialisation test failed on parameters");
        }

        if (!((DHPublicKey)keyPair.getPublic()).getY().equals(pubKey.getY()))
        {
            fail(size + " bit public key serialisation test failed on y value");
        }

        if (!keyPair.getPublic().equals(pubKey))
        {
            fail("equals test failed");
        }

        if (keyPair.getPublic().hashCode() != pubKey.hashCode())
        {
            fail("hashCode test failed");
        }

        //
        // private key encoding test
        //
        byte[]              privEnc = keyPair.getPrivate().getEncoded();
        PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
        DHPrivateKey        privKey = (DHPrivateKey)keyFac.generatePrivate(privPKCS8);

        spec = privKey.getParams();

        if (!spec.getG().equals(elParams.getG()) || !spec.getP().equals(elParams.getP()))
        {
            fail(size + " bit private key encoding/decoding test failed on parameters");
        }

        if (!((DHPrivateKey)keyPair.getPrivate()).getX().equals(privKey.getX()))
        {
            fail(size + " bit private key encoding/decoding test failed on y value");
        }

        //
        // private key serialisation test
        //
        privKey = (DHPrivateKey)serializeDeserialize(keyPair.getPrivate());
        spec = privKey.getParams();

        if (!spec.getG().equals(elParams.getG()) || !spec.getP().equals(elParams.getP()))
        {
            fail(size + " bit private key serialisation test failed on parameters");
        }

        if (!((DHPrivateKey)keyPair.getPrivate()).getX().equals(privKey.getX()))
        {
            fail(size + " bit private key serialisation test failed on y value");
        }

        if (!keyPair.getPrivate().equals(privKey))
        {
            fail("equals test failed");
        }

        if (keyPair.getPrivate().hashCode() != privKey.hashCode())
        {
            fail("hashCode test failed");
        }

        if (!(privKey instanceof PKCS12BagAttributeCarrier))
View Full Code Here

        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ElGamal", "BC");
        byte[]           in = "This is a test".getBytes();

        keyGen.initialize(p.bitLength());

        KeyPair         keyPair = keyGen.generateKeyPair();

        new BouncyCastleProvider().setParameter(ConfigurableProvider.DH_DEFAULT_PARAMS, elParams);

        SecureRandom    rand = new SecureRandom();

        checkKeySize(privateValueSize, keyPair);

        Cipher  cipher = Cipher.getInstance("ElGamal", "BC");

        cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic(), rand);

        if (cipher.getOutputSize(in.length) != (size / 8) * 2)
        {
            fail("getOutputSize wrong on encryption");
        }

        byte[]  out = cipher.doFinal(in);

        cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());

        if (cipher.getOutputSize(out.length) != (size / 8) - 1)
        {
            fail("getOutputSize wrong on decryption");
        }

        //
        // No Padding - maximum length
        //
        byte[]  modBytes = ((DHPublicKey)keyPair.getPublic()).getParams().getP().toByteArray();
        byte[]  maxInput = new byte[modBytes.length - 1];

        maxInput[0] |= 0x7f;

        cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic(), rand);

        out = cipher.doFinal(maxInput);

        cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());

        out = cipher.doFinal(out);

        if (!areEqual(out, maxInput))
        {
            fail("NoPadding test failed on decrypt expected " + new String(Hex.encode(maxInput)) + " got " + new String(Hex.encode(out)));
        }

        //
        // encrypt/decrypt
        //

        Cipher  c1 = Cipher.getInstance("ElGamal", "BC");
        Cipher  c2 = Cipher.getInstance("ElGamal", "BC");

        c1.init(Cipher.ENCRYPT_MODE, keyPair.getPublic(), rand);

        byte[]  out1 = c1.doFinal(in);

        c2.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());

        byte[]  out2 = c2.doFinal(out1);

        if (!areEqual(in, out2))
        {
            fail(size + " encrypt test failed");
        }

        //
        // encrypt/decrypt with update
        //
        int outLen = c1.update(in, 0, 2, out1, 0);

        outLen += c1.doFinal(in, 2, in.length - 2, out1, outLen);

        outLen = c2.update(out1, 0, 2, out2, 0);

        outLen += c2.doFinal(out1, 2, out1.length - 2, out2, outLen);

        if (!areEqual(in, out2))
        {
            fail(size + " encrypt with update test failed");
        }

        //
        // public key encoding test
        //
        byte[]                  pubEnc = keyPair.getPublic().getEncoded();
        KeyFactory              keyFac = KeyFactory.getInstance("ElGamal", "BC");
        X509EncodedKeySpec      pubX509 = new X509EncodedKeySpec(pubEnc);
        DHPublicKey             pubKey = (DHPublicKey)keyFac.generatePublic(pubX509);
        DHParameterSpec         spec = pubKey.getParams();

        if (!spec.getG().equals(elParams.getG()) || !spec.getP().equals(elParams.getP()))
        {
            fail(size + " bit public key encoding/decoding test failed on parameters");
        }

        if (!((DHPublicKey)keyPair.getPublic()).getY().equals(pubKey.getY()))
        {
            fail(size + " bit public key encoding/decoding test failed on y value");
        }

        //
        // public key serialisation test
        //
        ByteArrayOutputStream   bOut = new ByteArrayOutputStream();
        ObjectOutputStream      oOut = new ObjectOutputStream(bOut);

        oOut.writeObject(keyPair.getPublic());

        ByteArrayInputStream   bIn = new ByteArrayInputStream(bOut.toByteArray());
        ObjectInputStream      oIn = new ObjectInputStream(bIn);

        pubKey = (DHPublicKey)oIn.readObject();
        spec = pubKey.getParams();

        if (!spec.getG().equals(elParams.getG()) || !spec.getP().equals(elParams.getP()))
        {
            fail(size + " bit public key serialisation test failed on parameters");
        }

        if (!((DHPublicKey)keyPair.getPublic()).getY().equals(pubKey.getY()))
        {
            fail(size + " bit public key serialisation test failed on y value");
        }

        //
        // private key encoding test
        //
        byte[]              privEnc = keyPair.getPrivate().getEncoded();
        PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
        DHPrivateKey        privKey = (DHPrivateKey)keyFac.generatePrivate(privPKCS8);

        spec = privKey.getParams();

        if (!spec.getG().equals(elParams.getG()) || !spec.getP().equals(elParams.getP()))
        {
            fail(size + " bit private key encoding/decoding test failed on parameters");
        }

        if (!((DHPrivateKey)keyPair.getPrivate()).getX().equals(privKey.getX()))
        {
            fail(size + " bit private key encoding/decoding test failed on y value");
        }

        //
        // private key serialisation test
        //
        bOut = new ByteArrayOutputStream();
        oOut = new ObjectOutputStream(bOut);

        oOut.writeObject(keyPair.getPrivate());

        bIn = new ByteArrayInputStream(bOut.toByteArray());
        oIn = new ObjectInputStream(bIn);

        privKey = (DHPrivateKey)oIn.readObject();
        spec = privKey.getParams();

        if (!spec.getG().equals(elParams.getG()) || !spec.getP().equals(elParams.getP()))
        {
            fail(size + " bit private key serialisation test failed on parameters");
        }

        if (!((DHPrivateKey)keyPair.getPrivate()).getX().equals(privKey.getX()))
        {
            fail(size + " bit private key serialisation test failed on y value");
        }
    }
View Full Code Here

TOP

Related Classes of java.security.KeyPair

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.