Example usage for java.security KeyPair getPrivate

List of usage examples for java.security KeyPair getPrivate

Introduction

In this page you can find the example usage for java.security KeyPair getPrivate.

Prototype

public PrivateKey getPrivate() 

Source Link

Document

Returns a reference to the private key component of this key pair.

Usage

From source file:org.mitre.openid.connect.client.AbstractOIDCAuthenticationFilter.java

@Override
public void afterPropertiesSet() {
    super.afterPropertiesSet();

    Assert.notNull(errorRedirectURI, "An Error Redirect URI must be supplied");

    KeyPairGenerator keyPairGenerator;

    try {/*  w  w w.j a  va  2s. c om*/
        keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(KEY_SIZE);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        publicKey = keyPair.getPublic();
        privateKey = keyPair.getPrivate();

        signer = Signature.getInstance(SIGNING_ALGORITHM);
    } catch (GeneralSecurityException generalSecurityException) {
        // generalSecurityException.printStackTrace();
        throw new IllegalStateException(generalSecurityException);
    }

    // prepend the spec necessary SCOPE
    setScope((scope != null && !scope.isEmpty()) ? SCOPE + " " + scope : SCOPE);
}

From source file:co.cask.cdap.security.tools.KeyStores.java

/**
 * Generate an X.509 certificate//from ww w. j a  v  a  2s  .c o  m
 *
 * @param dn Distinguished name for the owner of the certificate, it will also be the signer of the certificate.
 * @param pair Key pair used for signing the certificate.
 * @param days Validity of the certificate.
 * @param algorithm Name of the signature algorithm used.
 * @return A X.509 certificate
 */
private static X509Certificate getCertificate(String dn, KeyPair pair, int days, String algorithm)
        throws IOException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException,
        InvalidKeyException, SignatureException {
    // Calculate the validity interval of the certificate
    Date from = new Date();
    Date to = DateUtils.addDays(from, days);
    CertificateValidity interval = new CertificateValidity(from, to);
    // Generate a random number to use as the serial number for the certificate
    BigInteger sn = new BigInteger(64, new SecureRandom());
    // Create the name of the owner based on the provided distinguished name
    X500Name owner = new X500Name(dn);
    // Create an info objects with the provided information, which will be used to create the certificate
    X509CertInfo info = new X509CertInfo();
    info.set(X509CertInfo.VALIDITY, interval);
    info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
    // This certificate will be self signed, hence the subject and the issuer are same.
    info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
    info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
    info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
    info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
    AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
    info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));
    // Create the certificate and sign it with the private key
    X509CertImpl cert = new X509CertImpl(info);
    PrivateKey privateKey = pair.getPrivate();
    cert.sign(privateKey, algorithm);
    return cert;
}

From source file:org.asimba.wa.integrationtest.saml2.model.Response.java

/**
 * Requires the responseDocument to be already initialized, just adding another
 * Signature section to the existing documnet
 * @param signatureHelper//w w  w. ja va 2 s  .  c  o  m
 * @return
 */
public String getMessageWithSignedAssertion(SignatureHelper signatureHelper) {
    if (_responseDocument == null) {
        try {
            _responseDocument = XMLUtils.getDocumentFromString(getResponse(plain), true);
        } catch (OAException | XMLStreamException e) {
            _logger.error("Problem when establishing XML document to sign: {}", e.getMessage(), e);
            return null;
        }
    }

    KeyPair keypair = signatureHelper.getKeyPairFromKeystore();

    // Set signing context with PrivateKey and root of the Document
    Node localRoot = _assertion.getAssertionNode();
    signatureHelper.tagIdAttributes(localRoot.getOwnerDocument());

    DOMSignContext dsc = new DOMSignContext(keypair.getPrivate(), localRoot);

    // Get SignatureFactory for creating signatures in DOM:
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

    Reference refAssertion = null;
    SignedInfo si = null;
    XMLSignature signature = null;

    try {
        // Create reference for "" -> Assertion in the document
        // SAML requires enveloped transform
        List<Transform> transformsList = new ArrayList<>();
        transformsList.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
        // transformsList.add(fac.newTransform(Transforms.TRANSFORM_C14N_OMIT_COMMENTS, (TransformParameterSpec) null));

        refAssertion = fac.newReference("#" + getAssertion().getId(),
                fac.newDigestMethod(DigestMethod.SHA1, null), transformsList, null, null);

        // Create SignedInfo (SAML2: Exclusive with or without comments is specified)
        // .. some selection here; nothing fancy, just trying to switch based on signing key format
        String sigMethod;
        String keyAlg = keypair.getPrivate().getAlgorithm();
        if (keyAlg.contains("RSA")) {
            sigMethod = SignatureMethod.RSA_SHA1;
        } else if (keyAlg.contains("DSA")) {
            sigMethod = SignatureMethod.DSA_SHA1;
        } else {
            _logger.error("Unknown signing key algorithm: {}", keyAlg);
            return null;
        }

        si = fac.newSignedInfo(
                fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null),
                fac.newSignatureMethod(sigMethod, null), Collections.singletonList(refAssertion));

        // Add KeyInfo to the document:
        KeyInfoFactory kif = fac.getKeyInfoFactory();

        // .. get key from the generated keypair:
        KeyValue kv = kif.newKeyValue(keypair.getPublic());
        KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));

        signature = fac.newXMLSignature(si, ki);

        // before:
        _logger.info("Signing assertion in document");
        //         _logger.info("Document to sign:\n{}", XMLUtils.getStringFromDocument(localRoot.getOwnerDocument()));

        // Sign!
        signature.sign(dsc);

        return XMLUtils.getStringFromDocument(localRoot.getOwnerDocument());

    } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
        _logger.error("Could not create reference to signable content: {}", e.getMessage(), e);
        return null;
    } catch (KeyException e) {
        _logger.error("Could not establish key info: {}", e.getMessage(), e);
        return null;
    } catch (MarshalException | XMLSignatureException e) {
        _logger.error("Error signing document: {}", e.getMessage(), e);
        return null;
    } catch (OAException e) {
        _logger.error("Error creating string from XML document: {}", e.getMessage(), e);
        return null;
    }
}

From source file:test.integ.be.fedict.hsm.ws.WebServiceSecurityTest.java

@Test
public void testWSSecurityTS_BST_Signature_ProtectTokens() throws Exception {
    DigitalSignatureServicePortType dssPort = getPort();

    KeyPair keyPair = HSMProxyTestCredential.generateKeyPair();
    X509Certificate certificate = HSMProxyTestCredential.generateSelfSignedCertificate(keyPair);

    WSSecurityTestSOAPHandler securityTestSOAPHandler = new WSSecurityTestSOAPHandler();
    securityTestSOAPHandler.addTimestamp(true);
    securityTestSOAPHandler.addBinarySecurityToken(certificate);
    securityTestSOAPHandler.setSignBinarySecurityToken(true);
    securityTestSOAPHandler.addSignature(keyPair.getPrivate());
    addSOAPHandler(securityTestSOAPHandler, dssPort);

    ObjectFactory objectFactory = new ObjectFactory();
    SignRequest signRequest = objectFactory.createSignRequest();

    dssPort.sign(signRequest);/*  w  ww .j a v  a2 s .c  om*/
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data,
        String type, String fileName, String path, String storepass, KeyStore store)
        throws KeystoreEditorException {
    OutputStream fos = null;/* ww  w .  j  a  va2 s  . c o  m*/
    try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) {
        if (StringUtils.isBlank(alias)) {
            throw new IllegalArgumentException("Alias cannot be null.");
        }
        Path storeFile = Paths.get(path);
        //check the two most common key/cert stores first (pkcs12 and jks)
        if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) {
            //priv key + cert chain
            KeyStore pkcs12Store = KeyStore.getInstance("PKCS12");
            pkcs12Store.load(inputStream, storePassword.toCharArray());
            Certificate[] chain = pkcs12Store.getCertificateChain(alias);
            Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray());
            if (key != null) {
                store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain);
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        } else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) {
            //java keystore file
            KeyStore jks = KeyStore.getInstance("jks");
            jks.load(inputStream, storePassword.toCharArray());
            Enumeration<String> aliases = jks.aliases();

            //we are going to store all entries from the jks regardless of the passed in alias
            while (aliases.hasMoreElements()) {
                String jksAlias = aliases.nextElement();

                if (jks.isKeyEntry(jksAlias)) {
                    Key key = jks.getKey(jksAlias, keyPassword.toCharArray());
                    Certificate[] certificateChain = jks.getCertificateChain(jksAlias);
                    store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain);
                } else {
                    Certificate certificate = jks.getCertificate(jksAlias);
                    store.setCertificateEntry(jksAlias, certificate);
                }
            }

            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //need to parse der separately from pem, der has the same mime type but is binary hence checking both
        } else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) {
            ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream);
            ASN1Primitive asn1Primitive = asn1InputStream.readObject();
            X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded());
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
            Certificate certificate = certificateFactory
                    .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
            X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
            RDN cn = x500name.getRDNs(BCStyle.CN)[0];
            String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
            if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                store.setCertificateEntry(cnStr, certificate);
            }
            store.setCertificateEntry(alias, certificate);
            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //if it isn't one of the stores we support, it might be a key or cert by itself
        } else if (isPemParsable(type, fileName)) {
            //This is the catch all case for PEM, P7B, etc. with common file extensions if the mime type isn't read correctly in the browser
            Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            PEMParser pemParser = new PEMParser(reader);
            Object object;
            boolean setEntry = false;
            while ((object = pemParser.readObject()) != null) {
                if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) {
                    PEMKeyPair pemKeyPair;
                    if (object instanceof PEMEncryptedKeyPair) {
                        PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object;
                        JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
                        pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair(
                                jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray()));
                    } else {
                        pemKeyPair = (PEMKeyPair) object;
                    }

                    KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair);
                    PrivateKey privateKey = keyPair.getPrivate();
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain);
                    setEntry = true;
                } else if (object instanceof X509CertificateHolder) {
                    X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object;
                    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
                    Certificate certificate = certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
                    X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate)
                            .getSubject();
                    RDN cn = x500name.getRDNs(BCStyle.CN)[0];
                    String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
                    if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                        store.setCertificateEntry(cnStr, certificate);
                    }
                    store.setCertificateEntry(alias, certificate);
                    setEntry = true;
                } else if (object instanceof ContentInfo) {
                    ContentInfo contentInfo = (ContentInfo) object;
                    if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) {
                        CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo);
                        OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure();
                        ASN1Set certificates = originatorInfo.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    } else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) {
                        SignedData signedData = SignedData.getInstance(contentInfo.getContent());
                        ASN1Set certificates = signedData.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    }
                } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
                    PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    try {
                        store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain);
                        setEntry = true;
                    } catch (KeyStoreException keyEx) {
                        try {
                            PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(),
                                    keyPassword.toCharArray());
                            store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(),
                                    chain);
                            setEntry = true;
                        } catch (GeneralSecurityException e) {
                            LOGGER.error(
                                    "Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.",
                                    e);
                            throw keyEx;
                        }
                    }
                }
            }
            if (setEntry) {
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Unable to add entry {} to store", alias, e);
        throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ignore) {
            }
        }
    }
    init();
}

From source file:org.apache.xml.security.test.encryption.XMLCipherTester.java

/**
 * Test encryption using a generated AES 256 bit key that is
 * encrypted using an RSA key.  Reverse using KEK
 *///from  w  ww. ja v a 2 s  .  c  o  m

public void testAES128ElementRSAKWCipherUsingKEK() throws Exception {

    Document d = document(); // source
    Document ed = null;
    Document dd = null;
    Element e = (Element) d.getElementsByTagName(element()).item(index());
    Element ee = null;

    String source = null;
    String target = null;

    if (haveISOPadding) {

        source = toString(d);

        // Generate an RSA key
        KeyPairGenerator rsaKeygen = KeyPairGenerator.getInstance("RSA");
        KeyPair kp = rsaKeygen.generateKeyPair();
        PrivateKey priv = kp.getPrivate();
        PublicKey pub = kp.getPublic();

        // Generate a traffic key
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        keygen.init(256);
        Key key = keygen.generateKey();

        cipher = XMLCipher.getInstance(XMLCipher.RSA_v1dot5);
        cipher.init(XMLCipher.WRAP_MODE, pub);
        EncryptedKey encryptedKey = cipher.encryptKey(d, key);

        // encrypt
        cipher = XMLCipher.getInstance(XMLCipher.AES_256);
        cipher.init(XMLCipher.ENCRYPT_MODE, key);
        EncryptedData builder = cipher.getEncryptedData();

        KeyInfo builderKeyInfo = builder.getKeyInfo();
        if (builderKeyInfo == null) {
            builderKeyInfo = new KeyInfo(d);
            builder.setKeyInfo(builderKeyInfo);
        }

        builderKeyInfo.add(encryptedKey);

        ed = cipher.doFinal(d, e);
        log.debug("Encrypted document");
        log.debug(toString(ed));

        //decrypt
        key = null;
        ee = (Element) ed.getElementsByTagName("xenc:EncryptedData").item(0);
        cipher = XMLCipher.getInstance(XMLCipher.AES_128);
        cipher.init(XMLCipher.DECRYPT_MODE, null);
        cipher.setKEK(priv);
        dd = cipher.doFinal(ed, ee);

        target = toString(dd);
        log.debug("Output document");
        log.debug(target);

        Assert.assertEquals(source, target);
    } else {
        log.warn("Test testAES128ElementRSAKWCipherUsingKEK skipped as necessary algorithms not available");
    }
}

From source file:com.streamsets.datacollector.credential.cyberark.TestWebServicesFetcher.java

@SuppressWarnings("deprecation")
/**/*from w  w w .jav a  2s .com*/
 * Create a self-signed X.509 Certificate.
 *
 * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
 * @param pair the KeyPair
 * @param days how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 * @return the self-signed certificate
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm)
        throws CertificateEncodingException, InvalidKeyException, IllegalStateException,
        NoSuchProviderException, NoSuchAlgorithmException, SignatureException {

    Date from = new Date();
    Date to = new Date(from.getTime() + days * 86400000l);
    BigInteger sn = new BigInteger(64, new SecureRandom());
    KeyPair keyPair = pair;
    X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
    X500Principal dnName = new X500Principal(dn);

    certGen.setSerialNumber(sn);
    certGen.setIssuerDN(dnName);
    certGen.setNotBefore(from);
    certGen.setNotAfter(to);
    certGen.setSubjectDN(dnName);
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm(algorithm);

    X509Certificate cert = certGen.generate(pair.getPrivate());
    return cert;
}

From source file:mitm.common.security.ca.handlers.comodo.ComodoCertificateRequestHandler.java

private KeyAndCertificate handleWaitingForRetrieval(CertificateRequest request, DataWrapper data)
        throws CAException {
    logger.debug("handling state: " + data.getState());

    try {/*from   ww  w .  j  a va 2 s . co  m*/
        KeyAndCertificate keyAndCertificate = null;

        ComodoSettings settings = settingsProvider.getSettings();

        assertEnabled(settings);

        CollectCustomClientCert collector = new CollectCustomClientCert(connectionSettings);

        collector.setLoginName(settings.getLoginName());
        collector.setLoginPassword(settings.getLoginPassword());
        collector.setOrderNumber(data.getOrderNumber());

        boolean success = collector.collectCertificate();

        if (success) {
            if (collector.getErrorCode() == CustomClientStatusCode.CERTIFICATES_ATTACHED) {
                logger.info("Certificate for user " + request.getEmail() + " with order number "
                        + data.getOrderNumber() + " was collected.");

                if (collector.getCertificate() == null) {
                    throw new CAException("Certificate is null");
                }

                KeyPair keyPair = request.getKeyPair(encryptor);

                if (keyPair == null) {
                    throw new CAException("keyPair is null");
                }

                keyAndCertificate = new KeyAndCertificateImpl(keyPair.getPrivate(), collector.getCertificate());

                data.setState(ComodoRequestState.FINISHED);
            } else if (collector.getErrorCode() == CustomClientStatusCode.SUCCESSFUL) {
                /*
                 * CustomClientStatusCode.SUCCESSFUL means "being processed by Comodo" for CCC API. 
                 */
                String message = "certificate for user " + request.getEmail() + " with order number "
                        + data.getOrderNumber() + " is being processed by Comodo.";

                logger.info(message);

                request.setLastMessage(MiscStringUtils.restrictLength(message, 1024));

                /*
                 * It can happen that when the certificate was requested, autoAuthorize was disabled and
                 * then enabled. If autoAuthorize is true and the request was not yet authorized the next 
                 * state should be authorize. 
                 */
                if (settings.isAutoAuthorize() && !data.isAuthorized()) {
                    logger.info("Auto authorize is enabled. The request however, is not yet authorized. "
                            + "Going to auto authorize the request.");

                    data.setState(ComodoRequestState.WAITING_FOR_AUTHORIZATION);
                }
            } else {
                /*
                 * Should not happen
                 */
                String message = "Unexpected state for user " + request.getEmail() + " with order number "
                        + data.getOrderNumber() + ". State: " + collector.getErrorCode();

                logger.info(message);

                request.setLastMessage(MiscStringUtils.restrictLength(message, 1024));
            }
        } else {
            String message = "Error collecting certificate for user " + request.getEmail()
                    + " with order number " + data.getOrderNumber() + ". Message: "
                    + collector.getErrorMessage();

            logger.warn(message);

            request.setLastMessage(MiscStringUtils.restrictLength(message, 1024));
        }

        return keyAndCertificate;
    } catch (HierarchicalPropertiesException e) {
        throw new CAException("Error collecting a certificate", e);
    } catch (CustomClientCertException e) {
        throw new CAException("Error collecting a certificate", e);
    } catch (KeyEncoderException e) {
        throw new CAException("Error decrypting the key pair", e);
    }
}

From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java

/**
 * Initialize the Diffie-Hellman keys. This method is not thread safe
 *///from  ww w .j a va 2s  .  c o  m
public static void initDHKeys(DistributionConfig config) throws Exception {

    dhSKAlgo = config.getSecurityClientDHAlgo();
    dhPrivateKey = null;
    dhPublicKey = null;
    // Initialize the keys when either the host is a client that has
    // non-blank setting for DH symmetric algo, or this is a server
    // that has authenticator defined.
    if ((dhSKAlgo != null && dhSKAlgo.length() > 0) /* || securityService.isClientSecurityRequired() */) {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
        DHParameterSpec dhSpec = new DHParameterSpec(dhP, dhG, dhL);
        keyGen.initialize(dhSpec);
        KeyPair keypair = keyGen.generateKeyPair();

        // Get the generated public and private keys
        dhPrivateKey = keypair.getPrivate();
        dhPublicKey = keypair.getPublic();

        random = new SecureRandom();
        // Force the random generator to seed itself.
        byte[] someBytes = new byte[48];
        random.nextBytes(someBytes);
    }
}

From source file:org.cesecore.authentication.SimpleAuthenticationProviderSessionBean.java

/**
 * This is the pug of authentication; loves everybody.
 *//*from w  w  w. ja  v  a 2  s .  co  m*/
@Override
public AuthenticationToken authenticate(AuthenticationSubject subject) {

    // A small check if we have added a "fail" credential to the subject.
    // If we have we will return null, so we can test authentication failure.
    Set<?> usercredentials = subject.getCredentials();
    if ((usercredentials != null) && (usercredentials.size() > 0)) {
        Object o = usercredentials.iterator().next();
        if (o instanceof String) {
            String str = (String) o;
            if (StringUtils.equals("fail", str)) {
                return null;
            }
        }
    }

    X509Certificate certificate = null;
    // If we have a certificate as input, use that, otherwise generate a self signed certificate
    Set<X509Certificate> credentials = new HashSet<X509Certificate>();
    Set<?> inputcreds = subject.getCredentials();
    if (inputcreds != null) {
        for (Object object : inputcreds) {
            if (object instanceof X509Certificate) {
                certificate = (X509Certificate) object;
            }
        }
    }

    // If there was no certificate input, create a self signed
    if (certificate == null) {
        String dn = "C=SE,O=Test,CN=Test"; // default
        // If we have created a subject with an X500Principal we will use this DN to create the dummy certificate.
        if (subject != null) {
            Set<Principal> principals = subject.getPrincipals();
            if ((principals != null) && (principals.size() > 0)) {
                Principal p = principals.iterator().next();
                if (p instanceof X500Principal) {
                    X500Principal xp = (X500Principal) p;
                    dn = xp.getName();
                }
            }
        }
        KeyPair keys = null;
        try {
            keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
        } catch (NoSuchAlgorithmException e) {
            throw new InvalidAuthenticationTokenException("Could not create authentication token.", e);
        } catch (NoSuchProviderException e) {
            throw new InvalidAuthenticationTokenException("Could not create authentication token.", e);
        } catch (InvalidAlgorithmParameterException e) {
            throw new InvalidAuthenticationTokenException("Could not create authentication token.", e);
        }
        try {
            certificate = CertTools.genSelfCert(dn, 365, null, keys.getPrivate(), keys.getPublic(),
                    AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true);
        } catch (InvalidKeyException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        } catch (CertificateEncodingException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        } catch (NoSuchAlgorithmException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        } catch (SignatureException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        } catch (IllegalStateException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        } catch (NoSuchProviderException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        }
    }
    // Add the credentials and new principal
    credentials.add(certificate);
    Set<X500Principal> principals = new HashSet<X500Principal>();
    principals.add(certificate.getSubjectX500Principal());

    // We cannot use the X509CertificateAuthenticationToken here, since it can only be used internally in a JVM.
    AuthenticationToken result = new TestAuthenticationToken(principals, credentials);
    return result;
}