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:it.zero11.acme.Acme.java

@SuppressWarnings("serial")
protected String getHTTP01ChallengeRequest(final KeyPair userKey, final String token, final String nonce) {
    return Jwts.builder().setHeaderParam(NONCE_KEY, nonce)
            .setHeaderParam(JwsHeader.JSON_WEB_KEY, JWKUtils.getWebKey(userKey.getPublic()))
            .setClaims(new TreeMap<String, Object>() {
                {/* w ww  .ja v  a 2s .c om*/
                    put(RESOURCE_KEY, RESOURCE_CHALLENGE);
                    put(CHALLENGE_TYPE_KEY, CHALLENGE_TYPE_HTTP_01);
                    put(CHALLENGE_TLS_KEY, true);
                    put(CHALLENGE_KEY_AUTHORIZATION_KEY, getHTTP01ChallengeContent(userKey, token));
                    put(CHALLENGE_TOKEN_KEY, token);
                }
            }).signWith(getJWSSignatureAlgorithm(), userKey.getPrivate()).compact();
}

From source file:org.keycloak.testsuite.client.OIDCJwksClientRegistrationTest.java

private String getClientSignedJWT(String clientId, KeyPair keyPair, final String kid) {
    String realmInfoUrl = KeycloakUriBuilder.fromUri(getAuthServerRoot())
            .path(ServiceUrlConstants.REALM_INFO_PATH).build(REALM_NAME).toString();

    // Use token-endpoint as audience as OIDC conformance testsuite is using it too.
    JWTClientCredentialsProvider jwtProvider = new JWTClientCredentialsProvider() {

        @Override//from ww  w . j a  va  2  s  .c  o  m
        public String createSignedRequestToken(String clientId, String realmInfoUrl) {
            if (KEEP_GENERATED_KID.equals(kid)) {
                return super.createSignedRequestToken(clientId, realmInfoUrl);
            } else {
                JsonWebToken jwt = createRequestToken(clientId, realmInfoUrl);
                return new JWSBuilder().kid(kid).jsonContent(jwt).rsa256(keyPair.getPrivate());
            }
        }

        @Override
        protected JsonWebToken createRequestToken(String clientId, String realmInfoUrl) {
            JsonWebToken jwt = super.createRequestToken(clientId, realmInfoUrl);
            String tokenEndpointUrl = OIDCLoginProtocolService.tokenUrl(UriBuilder.fromUri(getAuthServerRoot()))
                    .build(REALM_NAME).toString();
            jwt.audience(tokenEndpointUrl);
            return jwt;
        }

    };
    jwtProvider.setupKeyPair(keyPair);
    jwtProvider.setTokenTimeout(10);
    return jwtProvider.createSignedRequestToken(clientId, realmInfoUrl);

}

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

private void createSslConfig() throws Exception {
    File clientKS = new File(getConfDir(), "clientKS.jks");
    String clientKSPassword = "clientKSPassword";
    String clientKeyPassword = "clientKeyPassword";
    File serverKS = new File(getConfDir(), "serverKS.jks");
    String serverKSPassword = "serverKSPassword";
    String serverKeyPassword = "serverKeyPassword";
    File trustKS = new File(getConfDir(), "trustKS.jks");
    String trustPassword = "trustKSPassword";

    Map<String, X509Certificate> certs = new HashMap<String, X509Certificate>();

    KeyPair sKP = generateKeyPair("RSA");
    X509Certificate sCert = generateCertificate("CN=localhost, O=server", sKP, 30, "SHA1withRSA");
    createKeyStore(serverKS, serverKSPassword, serverKeyPassword, "server", sKP.getPrivate(), sCert);
    certs.put("server", sCert);

    KeyPair cKP = generateKeyPair("RSA");
    X509Certificate cCert = generateCertificate("CN=localhost, O=client", cKP, 30, "SHA1withRSA");
    createKeyStore(clientKS, clientKSPassword, clientKeyPassword, "client", cKP.getPrivate(), cCert);
    certs.put("client", cCert);

    createTrustStore(trustKS, trustPassword, certs);
}

From source file:org.apache.stratos.keystore.mgt.KeyStoreGenerator.java

/**
 * This method generates the keypair and stores it in the keystore
 *
 * @param keyStore A keystore instance// w  w  w  .ja v  a2 s  . co m
 * @return Generated public key for the tenant
 * @throws KeyStoreMgtException Error when generating key pair
 */
private X509Certificate generateKeyPair(KeyStore keyStore) throws KeyStoreMgtException {
    try {
        CryptoUtil.getDefaultCryptoUtil();
        //generate key pair
        KeyPairGenerator keyPairGenerator = null;
        keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // Common Name and alias for the generated certificate
        String commonName = "CN=" + tenantDomain + ", OU=None, O=None L=None, C=None";

        //generate certificates
        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
        v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()));
        v3CertGen.setIssuerDN(new X509Principal(commonName));
        v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
        v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
        v3CertGen.setSubjectDN(new X509Principal(commonName));
        v3CertGen.setPublicKey(keyPair.getPublic());
        v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");
        X509Certificate PKCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());

        //add private key to KS
        keyStore.setKeyEntry(tenantDomain, keyPair.getPrivate(), password.toCharArray(),
                new java.security.cert.Certificate[] { PKCertificate });
        return PKCertificate;
    } catch (Exception ex) {
        String msg = "Error while generating the certificate for tenant :" + tenantDomain + ".";
        log.error(msg, ex);
        throw new KeyStoreMgtException(msg, ex);
    }

}

From source file:it.scoppelletti.security.keypairgen.KeyPairGeneratorBean.java

/**
 * Esegue l&rsquo;operazione./* w w  w . j a  va  2 s . com*/
 */
public void run() {
    Properties props;
    OutputStream publicOut = null;
    OutputStream privateOut = null;
    KeyPair keyPair;
    KeyPairGenerator keyGen;

    if (myConfigFile == null) {
        throw new PropertyNotSetException(toString(), "configFile");
    }
    if (myPublicFile == null) {
        throw new PropertyNotSetException(toString(), "publicFile");
    }
    if (myPrivateFile == null) {
        throw new PropertyNotSetException(toString(), "privateFile");
    }

    try {
        props = loadConfig();
        publicOut = openOutput(myPublicFile);
        if (publicOut == null) {
            return;
        }
        privateOut = openOutput(myPrivateFile);
        if (privateOut == null) {
            return;
        }

        keyGen = CryptoUtils.getKeyPairGenerator(props, myPrefix);
        keyPair = keyGen.generateKeyPair();

        props = CryptoUtils.toProperties(keyPair.getPublic(), myEncoded);
        props.store(publicOut, null);

        props = CryptoUtils.toProperties(keyPair.getPrivate(), myEncoded);
        props.store(privateOut, null);
    } catch (IOException ex) {
        throw new IOOperationException(ex);
    } finally {
        if (publicOut != null) {
            IOUtils.close(publicOut);
            publicOut = null;
        }
        if (privateOut != null) {
            IOUtils.close(privateOut);
            privateOut = null;
        }
    }
}

From source file:it.zero11.acme.Acme.java

@SuppressWarnings("serial")
protected String getAuthorizationRequest(final KeyPair userKey, final String nextNonce, final String domain) {
    return Jwts.builder().setHeaderParam(NONCE_KEY, nextNonce)
            .setHeaderParam(JwsHeader.JSON_WEB_KEY, JWKUtils.getWebKey(userKey.getPublic()))
            .setClaims(new TreeMap<String, Object>() {
                {//w  w w .j a va 2  s.c  o  m
                    put(RESOURCE_KEY, RESOURCE_NEW_AUTHZ);
                    put(IDENTIFIER_KEY, new TreeMap<String, Object>() {
                        {
                            put(IDENTIFIER_TYPE_KEY, IDENTIFIER_TYPE_DNS);
                            put(IDENTIFIER_VALUE_KEY, domain);
                        }
                    });
                }
            }).signWith(getJWSSignatureAlgorithm(), userKey.getPrivate()).compact();
}

From source file:it.zero11.acme.Acme.java

@SuppressWarnings("serial")
protected String getRegistrationRequest(final KeyPair userKey, final String nonce, final String agreement,
        final String[] contacts) {
    return Jwts.builder().setHeaderParam(NONCE_KEY, nonce)
            .setHeaderParam(JwsHeader.JSON_WEB_KEY, JWKUtils.getWebKey(userKey.getPublic()))
            .setClaims(new TreeMap<String, Object>() {
                {//from  w  w  w  . ja v a  2 s . c  o  m
                    put(RESOURCE_KEY, RESOURCE_NEW_REG);
                    if (contacts != null && contacts.length > 0) {
                        put(CONTACT_KEY, contacts);
                    }
                    if (agreement != null) {
                        put(AGREEMENT_KEY, agreement);
                    }
                }
            }).signWith(getJWSSignatureAlgorithm(), userKey.getPrivate()).compact();
}

From source file:com.cws.esolutions.security.dao.keymgmt.impl.FileKeyManager.java

/**
 * @see com.cws.esolutions.security.dao.keymgmt.interfaces.KeyManager#createKeys(java.lang.String)
 */// w  ww  .j  a  va  2 s  . c  o m
public synchronized boolean createKeys(final String guid) throws KeyManagementException {
    final String methodName = FileKeyManager.CNAME
            + "#createKeys(final String guid) throws KeyManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", guid);
    }

    boolean isComplete = false;
    OutputStream publicStream = null;
    OutputStream privateStream = null;

    final File keyDirectory = FileUtils.getFile(keyConfig.getKeyDirectory() + "/" + guid);

    try {
        if (!(keyDirectory.exists())) {
            if (!(keyDirectory.mkdirs())) {
                throw new KeyManagementException(
                        "Configured key directory does not exist and unable to create it");
            }
        }

        keyDirectory.setExecutable(true, true);

        SecureRandom random = new SecureRandom();
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(keyConfig.getKeyAlgorithm());
        keyGenerator.initialize(keyConfig.getKeySize(), random);
        KeyPair keyPair = keyGenerator.generateKeyPair();

        if (keyPair != null) {
            File privateFile = FileUtils
                    .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PRIVATEKEY_FILE_EXT);
            File publicFile = FileUtils
                    .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PUBLICKEY_FILE_EXT);

            if (!(privateFile.createNewFile())) {
                throw new IOException("Failed to store private key file");
            }

            if (!(publicFile.createNewFile())) {
                throw new IOException("Failed to store public key file");
            }

            privateFile.setWritable(true, true);
            publicFile.setWritable(true, true);

            privateStream = new FileOutputStream(privateFile);
            publicStream = new FileOutputStream(publicFile);

            IOUtils.write(keyPair.getPrivate().getEncoded(), privateStream);
            IOUtils.write(keyPair.getPublic().getEncoded(), publicStream);

            // assume success, as we'll get an IOException if the write failed
            isComplete = true;
        } else {
            throw new KeyManagementException("Failed to generate keypair. Cannot continue.");
        }
    } catch (FileNotFoundException fnfx) {
        throw new KeyManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new KeyManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new KeyManagementException(nsax.getMessage(), nsax);
    } finally {
        if (publicStream != null) {
            IOUtils.closeQuietly(publicStream);
        }

        if (privateStream != null) {
            IOUtils.closeQuietly(privateStream);
        }
    }

    return isComplete;
}

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

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

    try {/*www.j  ava 2  s  .  c o m*/
        ComodoSettings settings = settingsProvider.getSettings();

        assertEnabled(settings);

        KeyPair keyPair = request.getKeyPair(encryptor);

        if (keyPair == null) {
            keyPair = generateKeyPair(request.getKeyLength());
        }

        /* 
         * We must store the generated keypair.
         */
        request.setKeyPair(keyPair, encryptor);

        PKCS10CertificationRequestBuilder requestBuilder = new PKCS10CertificationRequestBuilder(
                X500PrincipalUtils.toX500Name(request.getSubject()),
                SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

        PKCS10CertificationRequest pkcs10 = requestBuilder
                .build(getContentSigner("SHA1WithRSA", keyPair.getPrivate()));

        String base64PKCS10 = MiscStringUtils.toAsciiString(Base64.encodeBase64(pkcs10.getEncoded()));

        ApplyCustomClientCert applier = new ApplyCustomClientCert(connectionSettings);

        applier.setAP(settings.getAP());
        applier.setCACertificateID(settings.getCACertificateID());
        applier.setDays(request.getValidity());
        applier.setPkcs10(base64PKCS10);

        boolean success = applier.apply();

        if (success) {
            logger.info("Certificate request for user " + request.getEmail() + " was sent. Order number: "
                    + applier.getOrderNumber());

            data.setOrderNumber(applier.getOrderNumber());

            data.setState(settings.isAutoAuthorize() ? ComodoRequestState.WAITING_FOR_AUTHORIZATION
                    : ComodoRequestState.WAITING_FOR_RETRIEVAL);

            request.setInfo("Order number: " + applier.getOrderNumber());
        } else {
            String errorMessage = "Error requesting certificate. Message: " + applier.getErrorMessage();

            logger.warn(errorMessage);

            request.setLastMessage(MiscStringUtils.restrictLength(errorMessage, 1024));
        }
    } catch (OperatorCreationException e) {
        throw new CAException("Error requesting a certificate", e);
    } catch (NoSuchAlgorithmException e) {
        throw new CAException("Error requesting a certificate", e);
    } catch (NoSuchProviderException e) {
        throw new CAException("Error requesting a certificate", e);
    } catch (KeyEncoderException e) {
        throw new CAException("Error encrypting the key pair", e);
    } catch (CustomClientCertException e) {
        throw new CAException("Error requesting a certificate", e);
    } catch (IOException e) {
        throw new CAException("Error requesting a certificate", e);
    }
}

From source file:net.firejack.platform.model.config.GatewayLoader.java

/**
 * @param lookup/*from  w w w. j a  v  a  2 s .  co  m*/
 * @param port
 * @return
 */
public Environments getConfig(String lookup, Integer port) {
    processSiteMinderConfigs();
    try {
        File keystore = InstallUtils.getKeyStore();

        String url = Env.FIREJACK_URL.getValue();

        logger.info("Load config from: " + url);

        KeyPair keyPair = KeyUtils.generate(keystore);

        if (keyPair == null) {
            throw new IllegalStateException("Key not found");
        }

        String name = InetAddress.getLocalHost().getHostName();
        X509Certificate certificate = KeyUtils.generateCertificate(url, 1, keyPair);

        String cert = new String(Base64.encode(certificate.getEncoded()));
        OPFEngine.init(url, lookup, name, cert);

        ServerNodeConfig config = new ServerNodeConfig();
        config.setServerName(name);
        config.setHost(InetAddress.getLocalHost().getHostAddress());
        config.setPort(port);
        config.setNodeType(ServerNodeType.GATEWAY);
        config.setLookup(lookup);
        config.setCert(certificate.getEncoded());

        InputStream stream = OPFEngine.RegistryService.registerSlaveNode(config);

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        IOUtils.copy(stream, output);
        byte[] decrypted = KeyUtils.decrypt(keyPair.getPrivate(), output.toByteArray());

        return InstallUtils.deserialize(new ByteArrayInputStream(decrypted));
    } catch (Exception e) {
        logger.error(e);
        return null;
    }
}