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:io.getlime.security.powerauth.app.server.service.behavior.ActivationServiceBehavior.java

/**
 * Prepare activation with given parameters
 *
 * @param userId                         User ID
 * @param maxFailedCount                 Maximum failed attempt count (5)
 * @param activationExpireTimestamp      Timestamp after which activation can no longer be completed
 * @param identity                       A string representing the provided identity
 * @param activationOtp                  Activation OTP parameter
 * @param activationNonceBase64          Activation nonce encoded as Base64
 * @param clientEphemeralPublicKeyBase64 Client ephemeral public key encoded as Base64
 * @param cDevicePublicKeyBase64         Encrypted device public key encoded as Base64
 * @param activationName                 Activation name
 * @param extras                         Extra parameter
 * @param applicationKey                 Application key
 * @param applicationSignature           Application signature
 * @param keyConversionUtilities         Utility class for key conversion
 * @return Prepared activation information
 * @throws GenericServiceException      In case invalid data is provided
 * @throws InvalidKeySpecException      If invalid key was provided
 * @throws InvalidKeyException          If invalid key was provided
 * @throws UnsupportedEncodingException If UTF-8 is not supported on the system
 *//*from  w w  w.  j a  va  2  s . c  o m*/
public CreateActivationResponse createActivation(String applicationKey, String userId, Long maxFailedCount,
        Date activationExpireTimestamp, String identity, String activationOtp, String activationNonceBase64,
        String clientEphemeralPublicKeyBase64, String cDevicePublicKeyBase64, String activationName,
        String extras, String applicationSignature, CryptoProviderUtil keyConversionUtilities)
        throws GenericServiceException, InvalidKeySpecException, InvalidKeyException,
        UnsupportedEncodingException {

    // Get current timestamp
    Date timestamp = new Date();

    ApplicationVersionEntity applicationVersion = applicationVersionRepository
            .findByApplicationKey(applicationKey);
    // if there is no such application, exit
    if (applicationVersion == null || applicationVersion.getSupported() == false) {
        throw localizationProvider.buildExceptionForCode(ServiceError.ACTIVATION_EXPIRED);
    }

    ApplicationEntity application = applicationVersion.getApplication();
    // if there is no such application, exit
    if (application == null) {
        throw localizationProvider.buildExceptionForCode(ServiceError.ACTIVATION_EXPIRED);
    }

    // Create an activation record and obtain the activation database record
    InitActivationResponse initActivationResponse = this.initActivation(application.getId(), userId,
            maxFailedCount, activationExpireTimestamp, keyConversionUtilities);
    ActivationRecordEntity activation = powerAuthRepository
            .findFirstByActivationId(initActivationResponse.getActivationId());

    // Get master private key
    String masterPrivateKeyBase64 = activation.getMasterKeyPair().getMasterKeyPrivateBase64();
    byte[] masterPrivateKeyBytes = BaseEncoding.base64().decode(masterPrivateKeyBase64);
    PrivateKey masterPrivateKey = keyConversionUtilities.convertBytesToPrivateKey(masterPrivateKeyBytes);

    // Get client ephemeral public key
    PublicKey clientEphemeralPublicKey = null;
    if (clientEphemeralPublicKeyBase64 != null) { // additional encryption is used
        byte[] clientEphemeralPublicKeyBytes = BaseEncoding.base64().decode(clientEphemeralPublicKeyBase64);
        clientEphemeralPublicKey = keyConversionUtilities
                .convertBytesToPublicKey(clientEphemeralPublicKeyBytes);
    }

    // Decrypt the device public key
    byte[] C_devicePublicKey = BaseEncoding.base64().decode(cDevicePublicKeyBase64);
    byte[] activationNonce = BaseEncoding.base64().decode(activationNonceBase64);
    PublicKey devicePublicKey = powerAuthServerActivation.decryptDevicePublicKey(C_devicePublicKey, identity,
            masterPrivateKey, clientEphemeralPublicKey, activationOtp, activationNonce);

    if (devicePublicKey == null) { // invalid key was sent, return error
        activation.setActivationStatus(
                io.getlime.security.powerauth.app.server.repository.model.ActivationStatus.REMOVED);
        powerAuthRepository.save(activation);
        callbackUrlBehavior.notifyCallbackListeners(activation.getApplication().getId(),
                activation.getActivationId());
        throw localizationProvider.buildExceptionForCode(ServiceError.ACTIVATION_NOT_FOUND);
    }

    byte[] applicationSignatureBytes = BaseEncoding.base64().decode(applicationSignature);

    if (!powerAuthServerActivation.validateApplicationSignature(identity, activationNonce, C_devicePublicKey,
            BaseEncoding.base64().decode(applicationKey),
            BaseEncoding.base64().decode(applicationVersion.getApplicationSecret()),
            applicationSignatureBytes)) {
        throw localizationProvider.buildExceptionForCode(ServiceError.ACTIVATION_EXPIRED);
    }

    // Update and persist the activation record
    activation.setActivationStatus(
            io.getlime.security.powerauth.app.server.repository.model.ActivationStatus.OTP_USED);
    activation.setDevicePublicKeyBase64(
            BaseEncoding.base64().encode(keyConversionUtilities.convertPublicKeyToBytes(devicePublicKey)));
    activation.setActivationName(activationName);
    activation.setExtras(extras);
    powerAuthRepository.save(activation);
    callbackUrlBehavior.notifyCallbackListeners(activation.getApplication().getId(),
            activation.getActivationId());

    // Generate response data
    byte[] activationNonceServer = powerAuthServerActivation.generateActivationNonce();
    String serverPublicKeyBase64 = activation.getServerPublicKeyBase64();
    PublicKey serverPublicKey = keyConversionUtilities
            .convertBytesToPublicKey(BaseEncoding.base64().decode(serverPublicKeyBase64));
    KeyPair ephemeralKeyPair = new KeyGenerator().generateKeyPair();
    PrivateKey ephemeralPrivateKey = ephemeralKeyPair.getPrivate();
    PublicKey ephemeralPublicKey = ephemeralKeyPair.getPublic();
    byte[] ephemeralPublicKeyBytes = keyConversionUtilities.convertPublicKeyToBytes(ephemeralPublicKey);

    // Encrypt the public key
    byte[] C_serverPublicKey = powerAuthServerActivation.encryptServerPublicKey(serverPublicKey,
            devicePublicKey, ephemeralPrivateKey, activationOtp, identity, activationNonceServer);

    // Get encrypted public key signature
    byte[] C_serverPubKeySignature = powerAuthServerActivation
            .computeServerDataSignature(activation.getActivationId(), C_serverPublicKey, masterPrivateKey);
    if (C_serverPubKeySignature == null) { // in case there is a technical error with signing and null is returned, return random bytes
        C_serverPubKeySignature = new KeyGenerator().generateRandomBytes(71);
    }

    // Compute the response
    CreateActivationResponse response = new CreateActivationResponse();
    response.setActivationId(activation.getActivationId());
    response.setActivationNonce(BaseEncoding.base64().encode(activationNonceServer));
    response.setEncryptedServerPublicKey(BaseEncoding.base64().encode(C_serverPublicKey));
    response.setEncryptedServerPublicKeySignature(BaseEncoding.base64().encode(C_serverPubKeySignature));
    response.setEphemeralPublicKey(BaseEncoding.base64().encode(ephemeralPublicKeyBytes));

    return response;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestHopsworksRMAppSecurityActions.java

private PKCS10CertificationRequest generateCSR(String cn) throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
    keyPairGenerator.initialize(1024);/*from w w  w. ja v  a2  s  . c om*/
    KeyPair keyPair = keyPairGenerator.genKeyPair();

    X500NameBuilder x500NameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    x500NameBuilder.addRDN(BCStyle.CN, cn);
    x500NameBuilder.addRDN(BCStyle.O, O);
    x500NameBuilder.addRDN(BCStyle.OU, OU);
    X500Name x500Name = x500NameBuilder.build();

    PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(x500Name,
            keyPair.getPublic());
    return csrBuilder
            .build(new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(keyPair.getPrivate()));
}

From source file:test.integ.be.agiv.security.IPSTSTest.java

@Test
public void testSTS_JAXWS_Client() throws Exception {
    ServletTester servletTester = new ServletTester();
    servletTester.addServlet(MyTestServlet.class, "/");

    Security.addProvider(new BouncyCastleProvider());

    KeyPair keyPair = generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);
    X509Certificate certificate = generateSelfSignedCertificate(keyPair, "CN=localhost", notBefore, notAfter);
    File tmpP12File = File.createTempFile("ssl-", ".p12");
    LOG.debug("p12 file: " + tmpP12File.getAbsolutePath());
    persistKey(tmpP12File, keyPair.getPrivate(), certificate, "secret".toCharArray(), "secret".toCharArray());

    SslSocketConnector sslSocketConnector = new SslSocketConnector();
    sslSocketConnector.setKeystore(tmpP12File.getAbsolutePath());
    sslSocketConnector.setTruststore(tmpP12File.getAbsolutePath());
    sslSocketConnector.setTruststoreType("pkcs12");
    sslSocketConnector.setKeystoreType("pkcs12");
    sslSocketConnector.setPassword("secret");
    sslSocketConnector.setKeyPassword("secret");
    sslSocketConnector.setTrustPassword("secret");
    sslSocketConnector.setMaxIdleTime(30000);
    int sslPort = getFreePort();
    sslSocketConnector.setPort(sslPort);

    servletTester.getContext().getServer().addConnector(sslSocketConnector);
    String sslLocation = "https://localhost:" + sslPort + "/";

    servletTester.start();/*from w  ww .j a va2s  .c o  m*/
    String location = servletTester.createSocketConnector(true);

    SSLContext sslContext = SSLContext.getInstance("TLS");
    TrustManager trustManager = new TestTrustManager(certificate);
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    SSLContext.setDefault(sslContext);

    try {
        LOG.debug("running IP-STS test...");
        IPSTSClient client = new IPSTSClient(sslLocation, AGIVSecurity.BETA_REALM);
        client.getSecurityToken("username", "password");
    } finally {
        servletTester.stop();
    }
}

From source file:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java

private X509Certificate createMiddleCaCert(X500Name subject, PublicKey pubKey, KeyPair pKeyPair,
        X500Name issuer) throws Exception {

    BigInteger sno = BigInteger.valueOf(3);
    Date nb = new Date(System.currentTimeMillis() - HALF_DAY);
    Date na = new Date(nb.getTime() + TWENTY_YEAR);

    X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, sno, nb, na, subject,
            pubKey);/*w  w  w  .j a va  2  s.  co  m*/

    addSubjectKID(certBuilder, pubKey);
    addAuthorityKID(certBuilder, pKeyPair.getPublic());
    certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(3));
    certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(BASE_EKU));

    X509Certificate certificate = signCert(certBuilder, pKeyPair.getPrivate());
    certificate.checkValidity(new Date());
    certificate.verify(pKeyPair.getPublic());

    setPKCS9Info(certificate);

    return certificate;
}

From source file:io.getlime.security.powerauth.app.server.service.behavior.ActivationServiceBehavior.java

/**
 * Prepare activation with given parameters
 *
 * @param activationIdShort              Short activation ID
 * @param activationNonceBase64          Activation nonce encoded as Base64
 * @param clientEphemeralPublicKeyBase64 Client ephemeral public key encoded as Base64
 * @param cDevicePublicKeyBase64         Encrypted device public key encoded as Base64
 * @param activationName                 Activation name
 * @param extras                         Extra parameter
 * @param applicationKey                 Application key
 * @param applicationSignature           Application signature
 * @param keyConversionUtilities         Utility class for key conversion
 * @return Prepared activation information
 * @throws GenericServiceException      In case invalid data is provided
 * @throws InvalidKeySpecException      If invalid key was provided
 * @throws InvalidKeyException          If invalid key was provided
 * @throws UnsupportedEncodingException If UTF-8 is not supported on the system
 *///www .j a  va  2 s . c o  m
public PrepareActivationResponse prepareActivation(String activationIdShort, String activationNonceBase64,
        String clientEphemeralPublicKeyBase64, String cDevicePublicKeyBase64, String activationName,
        String extras, String applicationKey, String applicationSignature,
        CryptoProviderUtil keyConversionUtilities) throws GenericServiceException, InvalidKeySpecException,
        InvalidKeyException, UnsupportedEncodingException {

    // Get current timestamp
    Date timestamp = new Date();

    ApplicationVersionEntity applicationVersion = applicationVersionRepository
            .findByApplicationKey(applicationKey);
    // if there is no such application, exit
    if (applicationVersion == null || applicationVersion.getSupported() == false) {
        throw localizationProvider.buildExceptionForCode(ServiceError.ACTIVATION_EXPIRED);
    }

    ApplicationEntity application = applicationVersion.getApplication();
    // if there is no such application, exit
    if (application == null) {
        throw localizationProvider.buildExceptionForCode(ServiceError.ACTIVATION_EXPIRED);
    }

    // Fetch the current activation by short activation ID
    Set<io.getlime.security.powerauth.app.server.repository.model.ActivationStatus> states = ImmutableSet
            .of(io.getlime.security.powerauth.app.server.repository.model.ActivationStatus.CREATED);
    ActivationRecordEntity activation = powerAuthRepository
            .findFirstByApplicationIdAndActivationIdShortAndActivationStatusInAndTimestampActivationExpireAfter(
                    application.getId(), activationIdShort, states, timestamp);

    // Make sure to deactivate the activation if it is expired
    if (activation != null) {
        deactivatePendingActivation(timestamp, activation);
    }

    // if there is no such activation or application does not match the activation application, exit
    if (activation == null
            || !io.getlime.security.powerauth.app.server.repository.model.ActivationStatus.CREATED
                    .equals(activation.getActivationStatus())
            || activation.getApplication().getId() != application.getId()) {
        throw localizationProvider.buildExceptionForCode(ServiceError.ACTIVATION_EXPIRED);
    }

    // Get master private key
    String masterPrivateKeyBase64 = activation.getMasterKeyPair().getMasterKeyPrivateBase64();
    byte[] masterPrivateKeyBytes = BaseEncoding.base64().decode(masterPrivateKeyBase64);
    PrivateKey masterPrivateKey = keyConversionUtilities.convertBytesToPrivateKey(masterPrivateKeyBytes);

    // Get client ephemeral public key
    PublicKey clientEphemeralPublicKey = null;
    if (clientEphemeralPublicKeyBase64 != null) { // additional encryption is used
        byte[] clientEphemeralPublicKeyBytes = BaseEncoding.base64().decode(clientEphemeralPublicKeyBase64);
        clientEphemeralPublicKey = keyConversionUtilities
                .convertBytesToPublicKey(clientEphemeralPublicKeyBytes);
    }

    // Decrypt the device public key
    byte[] C_devicePublicKey = BaseEncoding.base64().decode(cDevicePublicKeyBase64);
    byte[] activationNonce = BaseEncoding.base64().decode(activationNonceBase64);
    PublicKey devicePublicKey = powerAuthServerActivation.decryptDevicePublicKey(C_devicePublicKey,
            activationIdShort, masterPrivateKey, clientEphemeralPublicKey, activation.getActivationOTP(),
            activationNonce);

    if (devicePublicKey == null) { // invalid key was sent, return error
        activation.setActivationStatus(
                io.getlime.security.powerauth.app.server.repository.model.ActivationStatus.REMOVED);
        powerAuthRepository.save(activation);
        callbackUrlBehavior.notifyCallbackListeners(activation.getApplication().getId(),
                activation.getActivationId());
        throw localizationProvider.buildExceptionForCode(ServiceError.ACTIVATION_NOT_FOUND);
    }

    byte[] applicationSignatureBytes = BaseEncoding.base64().decode(applicationSignature);

    if (!powerAuthServerActivation.validateApplicationSignature(activationIdShort, activationNonce,
            C_devicePublicKey, BaseEncoding.base64().decode(applicationKey),
            BaseEncoding.base64().decode(applicationVersion.getApplicationSecret()),
            applicationSignatureBytes)) {
        throw localizationProvider.buildExceptionForCode(ServiceError.ACTIVATION_EXPIRED);
    }

    // Update and persist the activation record
    activation.setActivationStatus(
            io.getlime.security.powerauth.app.server.repository.model.ActivationStatus.OTP_USED);
    activation.setDevicePublicKeyBase64(
            BaseEncoding.base64().encode(keyConversionUtilities.convertPublicKeyToBytes(devicePublicKey)));
    activation.setActivationName(activationName);
    activation.setExtras(extras);
    powerAuthRepository.save(activation);
    callbackUrlBehavior.notifyCallbackListeners(activation.getApplication().getId(),
            activation.getActivationId());

    // Generate response data
    byte[] activationNonceServer = powerAuthServerActivation.generateActivationNonce();
    String serverPublicKeyBase64 = activation.getServerPublicKeyBase64();
    PublicKey serverPublicKey = keyConversionUtilities
            .convertBytesToPublicKey(BaseEncoding.base64().decode(serverPublicKeyBase64));
    KeyPair ephemeralKeyPair = new KeyGenerator().generateKeyPair();
    PrivateKey ephemeralPrivateKey = ephemeralKeyPair.getPrivate();
    PublicKey ephemeralPublicKey = ephemeralKeyPair.getPublic();
    byte[] ephemeralPublicKeyBytes = keyConversionUtilities.convertPublicKeyToBytes(ephemeralPublicKey);
    String activationOtp = activation.getActivationOTP();

    // Encrypt the public key
    byte[] C_serverPublicKey = powerAuthServerActivation.encryptServerPublicKey(serverPublicKey,
            devicePublicKey, ephemeralPrivateKey, activationOtp, activationIdShort, activationNonceServer);

    // Get encrypted public key signature
    byte[] C_serverPubKeySignature = powerAuthServerActivation
            .computeServerDataSignature(activation.getActivationId(), C_serverPublicKey, masterPrivateKey);
    if (C_serverPubKeySignature == null) { // in case there is a technical error with signing and null is returned, return random bytes
        C_serverPubKeySignature = new KeyGenerator().generateRandomBytes(71);
    }

    // Compute the response
    PrepareActivationResponse response = new PrepareActivationResponse();
    response.setActivationId(activation.getActivationId());
    response.setActivationNonce(BaseEncoding.base64().encode(activationNonceServer));
    response.setEncryptedServerPublicKey(BaseEncoding.base64().encode(C_serverPublicKey));
    response.setEncryptedServerPublicKeySignature(BaseEncoding.base64().encode(C_serverPubKeySignature));
    response.setEphemeralPublicKey(BaseEncoding.base64().encode(ephemeralPublicKeyBytes));

    return response;
}

From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java

/**
 * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#createCertificateRequest(List, String, int, int)
 *///  w  ww.jav a  2  s .  c  o  m
public synchronized File createCertificateRequest(final List<String> subjectData, final String storePassword,
        final int validityPeriod, final int keySize) throws CertificateManagementException {
    final String methodName = ICertificateManager.CNAME
            + "#createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", subjectData);
        DEBUGGER.debug("Value: {}", validityPeriod);
        DEBUGGER.debug("Value: {}", keySize);
    }

    final File rootDirectory = certConfig.getRootDirectory();
    final String signatureAlgorithm = certConfig.getSignatureAlgorithm();
    final String certificateAlgorithm = certConfig.getCertificateAlgorithm();
    final File privateKeyDirectory = FileUtils
            .getFile(certConfig.getPrivateKeyDirectory() + "/" + subjectData.get(0));
    final File publicKeyDirectory = FileUtils
            .getFile(certConfig.getPublicKeyDirectory() + "/" + subjectData.get(0));
    final File csrDirectory = FileUtils.getFile(certConfig.getCsrDirectory() + "/" + subjectData.get(0));
    final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + subjectData.get(0));
    final X500Name x500Name = new X500Name("CN=" + subjectData.get(0) + ",OU=" + subjectData.get(1) + ",O="
            + subjectData.get(2) + ",L=" + subjectData.get(3) + ",ST=" + subjectData.get(4) + ",C="
            + subjectData.get(5) + ",E=" + subjectData.get(6));

    if (DEBUG) {
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("signatureAlgorithm: {}", signatureAlgorithm);
        DEBUGGER.debug("certificateAlgorithm: {}", certificateAlgorithm);
        DEBUGGER.debug("privateKeyDirectory: {}", privateKeyDirectory);
        DEBUGGER.debug("publicKeyDirectory: {}", publicKeyDirectory);
        DEBUGGER.debug("csrDirectory: {}", csrDirectory);
        DEBUGGER.debug("storeDirectory: {}", storeDirectory);
        DEBUGGER.debug("x500Name: {}", x500Name);
    }

    File csrFile = null;
    JcaPEMWriter csrPemWriter = null;
    JcaPEMWriter publicKeyWriter = null;
    JcaPEMWriter privateKeyWriter = null;
    FileOutputStream csrFileStream = null;
    FileOutputStream keyStoreStream = null;
    FileOutputStream publicKeyFileStream = null;
    FileOutputStream privateKeyFileStream = null;
    OutputStreamWriter csrFileStreamWriter = null;
    OutputStreamWriter privateKeyStreamWriter = null;
    OutputStreamWriter publicKeyStreamWriter = null;

    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, storePassword.toCharArray());

        if (DEBUG) {
            DEBUGGER.debug("KeyStore: {}", keyStore);
        }

        SecureRandom random = new SecureRandom();
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(certificateAlgorithm);
        keyGenerator.initialize(keySize, random);

        if (DEBUG) {
            DEBUGGER.debug("KeyGenerator: {}", keyGenerator);
        }

        KeyPair keyPair = keyGenerator.generateKeyPair();

        if (DEBUG) {
            DEBUGGER.debug("KeyPair: {}", keyPair);
        }

        if (keyPair != null) {
            final Signature sig = Signature.getInstance(signatureAlgorithm);
            final PrivateKey privateKey = keyPair.getPrivate();
            final PublicKey publicKey = keyPair.getPublic();

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", sig);
                DEBUGGER.debug("PrivateKey: {}", privateKey);
                DEBUGGER.debug("PublicKey: {}", publicKey);
            }

            sig.initSign(privateKey, random);
            ContentSigner signGen = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey);

            if (DEBUG) {
                DEBUGGER.debug("ContentSigner: {}", signGen);
            }

            Calendar expiry = Calendar.getInstance();
            expiry.add(Calendar.DAY_OF_YEAR, validityPeriod);

            if (DEBUG) {
                DEBUGGER.debug("Calendar: {}", expiry);
            }

            CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType());

            if (DEBUG) {
                DEBUGGER.debug("CertificateFactory: {}", certFactory);
            }

            X509Certificate[] issuerCert = new X509Certificate[] { (X509Certificate) certFactory
                    .generateCertificate(new FileInputStream(certConfig.getIntermediateCertificateFile())) };

            if (DEBUG) {
                DEBUGGER.debug("X509Certificate[]: {}", (Object) issuerCert);
            }

            keyStore.setCertificateEntry(certConfig.getRootCertificateName(), certFactory.generateCertificate(
                    new FileInputStream(FileUtils.getFile(certConfig.getRootCertificateFile()))));
            keyStore.setCertificateEntry(certConfig.getIntermediateCertificateName(),
                    certFactory.generateCertificate(new FileInputStream(
                            FileUtils.getFile(certConfig.getIntermediateCertificateFile()))));

            PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name,
                    publicKey);

            if (DEBUG) {
                DEBUGGER.debug("PKCS10CertificationRequestBuilder: {}", builder);
            }

            PKCS10CertificationRequest csr = builder.build(signGen);

            if (DEBUG) {
                DEBUGGER.debug("PKCS10CertificationRequest: {}", csr);
            }

            // write private key
            File privateKeyFile = FileUtils.getFile(privateKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PRIVATEKEY_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("privateKeyFile: {}", privateKeyFile);
            }

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

            privateKeyFileStream = new FileOutputStream(privateKeyFile);
            privateKeyStreamWriter = new OutputStreamWriter(privateKeyFileStream);

            if (DEBUG) {
                DEBUGGER.debug("privateKeyFileStream: {}", privateKeyFileStream);
                DEBUGGER.debug("privateKeyStreamWriter: {}", privateKeyStreamWriter);
            }

            privateKeyWriter = new JcaPEMWriter(privateKeyStreamWriter);
            privateKeyWriter.writeObject(privateKey);
            privateKeyWriter.flush();
            privateKeyStreamWriter.flush();
            privateKeyFileStream.flush();

            // write public key
            File publicKeyFile = FileUtils.getFile(publicKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PUBLICKEY_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFile: {}", publicKeyFile);
            }

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

            publicKeyFileStream = new FileOutputStream(publicKeyFile);
            publicKeyStreamWriter = new OutputStreamWriter(publicKeyFileStream);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream);
                DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter);
            }

            publicKeyWriter = new JcaPEMWriter(publicKeyStreamWriter);
            publicKeyWriter.writeObject(publicKey);
            publicKeyWriter.flush();
            publicKeyStreamWriter.flush();
            publicKeyFileStream.flush();

            // write csr
            csrFile = FileUtils
                    .getFile(csrDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.CSR_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("csrFile: {}", csrFile);
            }

            if (!(csrFile.createNewFile())) {
                throw new IOException("Failed to store CSR file");
            }

            csrFileStream = new FileOutputStream(csrFile);
            csrFileStreamWriter = new OutputStreamWriter(csrFileStream);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream);
                DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter);
            }

            csrPemWriter = new JcaPEMWriter(csrFileStreamWriter);
            csrPemWriter.writeObject(csr);
            csrPemWriter.flush();
            csrFileStreamWriter.flush();
            csrFileStream.flush();

            File keyStoreFile = FileUtils
                    .getFile(storeDirectory + "/" + subjectData.get(0) + "." + KeyStore.getDefaultType());

            if (DEBUG) {
                DEBUGGER.debug("keyStoreFile: {}", keyStoreFile);
            }

            keyStoreStream = FileUtils.openOutputStream(keyStoreFile);

            if (DEBUG) {
                DEBUGGER.debug("keyStoreStream: {}", keyStoreStream);
            }

            keyStore.setKeyEntry(subjectData.get(0), (Key) keyPair.getPrivate(), storePassword.toCharArray(),
                    issuerCert);
            keyStore.store(keyStoreStream, storePassword.toCharArray());
            keyStoreStream.flush();

            if (DEBUG) {
                DEBUGGER.debug("KeyStore: {}", keyStore);
            }
        } else {
            throw new CertificateManagementException("Failed to generate keypair. Cannot continue.");
        }
    } catch (FileNotFoundException fnfx) {
        throw new CertificateManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new CertificateManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new CertificateManagementException(nsax.getMessage(), nsax);
    } catch (IllegalStateException isx) {
        throw new CertificateManagementException(isx.getMessage(), isx);
    } catch (InvalidKeyException ikx) {
        throw new CertificateManagementException(ikx.getMessage(), ikx);
    } catch (OperatorCreationException ocx) {
        throw new CertificateManagementException(ocx.getMessage(), ocx);
    } catch (KeyStoreException ksx) {
        throw new CertificateManagementException(ksx.getMessage(), ksx);
    } catch (CertificateException cx) {
        throw new CertificateManagementException(cx.getMessage(), cx);
    } finally {
        if (csrFileStreamWriter != null) {
            IOUtils.closeQuietly(csrFileStreamWriter);
        }

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

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

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

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

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

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

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

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

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

    return csrFile;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.X509SecurityHandler.java

private PKCS10CertificationRequest createCSR(X500Name subject, KeyPair keyPair)
        throws OperatorCreationException {
    PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(subject,
            keyPair.getPublic());//w  w w. ja v  a 2s.  co m
    return csrBuilder.build(new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(SECURITY_PROVIDER)
            .build(keyPair.getPrivate()));
}

From source file:test.integ.be.agiv.security.IPSTSTest.java

@Test
public void testRSTS_JAXWS_Client() throws Exception {
    ServletTester servletTester = new ServletTester();
    servletTester.addServlet(MyTestServlet.class, "/");

    Security.addProvider(new BouncyCastleProvider());

    KeyPair keyPair = generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);
    X509Certificate certificate = generateSelfSignedCertificate(keyPair, "CN=localhost", notBefore, notAfter);
    File tmpP12File = File.createTempFile("ssl-", ".p12");
    LOG.debug("p12 file: " + tmpP12File.getAbsolutePath());
    persistKey(tmpP12File, keyPair.getPrivate(), certificate, "secret".toCharArray(), "secret".toCharArray());

    SslSocketConnector sslSocketConnector = new SslSocketConnector();
    sslSocketConnector.setKeystore(tmpP12File.getAbsolutePath());
    sslSocketConnector.setTruststore(tmpP12File.getAbsolutePath());
    sslSocketConnector.setTruststoreType("pkcs12");
    sslSocketConnector.setKeystoreType("pkcs12");
    sslSocketConnector.setPassword("secret");
    sslSocketConnector.setKeyPassword("secret");
    sslSocketConnector.setTrustPassword("secret");
    sslSocketConnector.setMaxIdleTime(30000);
    int sslPort = getFreePort();
    sslSocketConnector.setPort(sslPort);

    servletTester.getContext().getServer().addConnector(sslSocketConnector);
    String sslLocation = "https://localhost:" + sslPort + "/";

    servletTester.start();/*from  ww w  . ja v  a 2 s.  c  om*/
    String location = servletTester.createSocketConnector(true);

    SSLContext sslContext = SSLContext.getInstance("TLS");
    TrustManager trustManager = new TestTrustManager(certificate);
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    SSLContext.setDefault(sslContext);

    try {
        LOG.debug("running R-STS test...");
        RSTSClient client = new RSTSClient(sslLocation);
        SecurityToken inputSecurityToken = new SecurityToken();
        byte[] key = new byte[256 / 8];
        SecureRandom random = new SecureRandom();
        random.nextBytes(key);
        inputSecurityToken.setKey(key);
        inputSecurityToken.setAttachedReference("_" + UUID.randomUUID().toString());
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        Element tokenElement = document.createElement("Token");
        tokenElement.setTextContent("hello world");
        inputSecurityToken.setToken(tokenElement);

        client.getSecurityToken(inputSecurityToken, "https://auth.beta.agiv.be/ClaimsAwareService/Service.svc");
    } finally {
        servletTester.stop();
    }
}

From source file:org.gluu.oxpush2.u2f.v2.device.U2FKeyImpl.java

@Override
public AuthenticateResponse authenticate(AuthenticateRequest authenticateRequest) throws U2FException {
    if (BuildConfig.DEBUG)
        Log.d(TAG, ">> authenticate");

    byte control = authenticateRequest.getControl();
    String application = authenticateRequest.getApplication();
    String challenge = authenticateRequest.getChallenge();
    byte[] keyHandle = authenticateRequest.getKeyHandle();

    if (BuildConfig.DEBUG)
        Log.d(TAG, "-- Inputs --");
    if (BuildConfig.DEBUG)
        Log.d(TAG, "control: " + control);
    if (BuildConfig.DEBUG)
        Log.d(TAG, "application: " + application);
    if (BuildConfig.DEBUG)
        Log.d(TAG, "challenge: " + challenge);
    if (BuildConfig.DEBUG)
        Log.d(TAG, "keyHandle: " + Utils.base64UrlEncode(keyHandle));

    TokenEntry tokenEntry = dataStore.getTokenEntry(keyHandle);

    if (tokenEntry == null) {
        Log.e(TAG, "There is no keyPair for keyHandle: " + Utils.base64UrlEncode(keyHandle));
        return null;
    }/*from www .  ja  v  a2s.  c om*/

    if (!StringUtils.equals(application, tokenEntry.getApplication())) {
        throw new U2FException("KeyHandle " + Utils.base64UrlEncode(keyHandle)
                + " is associated with application: " + tokenEntry.getApplication());
    }

    String keyPairJson = tokenEntry.getKeyPair();
    if (keyPairJson == null) {
        Log.e(TAG, "There is no keyPair for keyHandle: " + Utils.base64UrlEncode(keyHandle));
        return null;
    }

    KeyPair keyPair;
    try {
        keyPair = keyPairGenerator.keyPairFromJson(keyPairJson);
    } catch (U2FException ex) {
        Log.e(TAG, "There is no keyPair for keyHandle: " + Utils.base64UrlEncode(keyHandle));
        return null;
    }

    int counter = dataStore.incrementCounter(keyHandle);
    byte userPresence = userPresenceVerifier.verifyUserPresence();
    byte[] applicationSha256 = DigestUtils.sha256(application);
    byte[] challengeSha256 = DigestUtils.sha256(challenge);
    byte[] signedData = rawMessageCodec.encodeAuthenticateSignedBytes(applicationSha256, userPresence, counter,
            challengeSha256);

    if (BuildConfig.DEBUG)
        Log.d(TAG, "Signing bytes " + Utils.encodeHexString(signedData));

    byte[] signature = keyPairGenerator.sign(signedData, keyPair.getPrivate());

    if (BuildConfig.DEBUG)
        Log.d(TAG, "-- Outputs --");
    if (BuildConfig.DEBUG)
        Log.d(TAG, "userPresence: " + userPresence);
    if (BuildConfig.DEBUG)
        Log.d(TAG, "counter: " + counter);
    if (BuildConfig.DEBUG)
        Log.d(TAG, "signature: " + Utils.encodeHexString(signature));

    if (BuildConfig.DEBUG)
        Log.d(TAG, "<< authenticate");

    return new AuthenticateResponse(userPresence, counter, signature);
}

From source file:org.apache.hadoop.security.ssl.TestCRLValidator.java

@Test
public void testValidator() throws Exception {
    Path caTruststore = Paths.get(BASE_DIR, "ca.truststore.jks");
    Path crlPath = Paths.get(BASE_DIR, "crl.pem");

    // Generate CA keypair
    KeyPair cakeyPair = KeyStoreTestUtil.generateKeyPair(keyAlgorithm);
    X509Certificate caCert = KeyStoreTestUtil.generateCertificate("CN=rootCA", cakeyPair, 60,
            signatureAlgorithm);/*w w  w .j  a v  a 2s.  c om*/

    // Generate CA truststore
    KeyStoreTestUtil.createTrustStore(caTruststore.toString(), password, "rootca", caCert);

    // Generate client keypair
    KeyPair clientKeyPair = KeyStoreTestUtil.generateKeyPair(keyAlgorithm);
    X509Certificate clientCert = KeyStoreTestUtil.generateSignedCertificate("CN=client", clientKeyPair, 30,
            signatureAlgorithm, cakeyPair.getPrivate(), caCert);
    /*X509Certificate clientCert = KeyStoreTestUtil.generateCertificate("CN=client", clientKeyPair, 30,
        signatureAlgorithm);*/

    // Verify client certificate is signed by CA
    clientCert.verify(cakeyPair.getPublic());

    // Generate CRL
    X509CRL crl = KeyStoreTestUtil.generateCRL(caCert, cakeyPair.getPrivate(), signatureAlgorithm, null, null);
    writeCRLToFile(crl, crlPath);

    // Validate should pass
    conf.set(FileBasedKeyStoresFactory.resolvePropertyName(SSLFactory.Mode.SERVER,
            FileBasedKeyStoresFactory.SSL_TRUSTSTORE_LOCATION_TPL_KEY), caTruststore.toString());
    conf.set(FileBasedKeyStoresFactory.resolvePropertyName(SSLFactory.Mode.SERVER,
            FileBasedKeyStoresFactory.SSL_TRUSTSTORE_PASSWORD_TPL_KEY), password);
    conf.set(CommonConfigurationKeys.HOPS_CRL_OUTPUT_FILE_KEY, crlPath.toString());

    CRLValidator validator = CRLValidatorFactory.getInstance().getValidator(CRLValidatorFactory.TYPE.TESTING,
            conf, conf);

    Certificate[] chain = new Certificate[2];
    chain[0] = clientCert;
    chain[1] = caCert;

    // At this point the validation should pass
    validator.validate(chain);

    // Revoke client certificate and regenerate CRL
    crl = KeyStoreTestUtil.generateCRL(caCert, cakeyPair.getPrivate(), signatureAlgorithm, crl,
            clientCert.getSerialNumber());
    TimeUnit.SECONDS.sleep(1);
    writeCRLToFile(crl, crlPath);

    TimeUnit.SECONDS.sleep(validator.getReloadInterval() * 2);

    // This time validation should fail
    rule.expect(CertificateException.class);
    validator.validate(chain);
}