Example usage for java.security KeyPair KeyPair

List of usage examples for java.security KeyPair KeyPair

Introduction

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

Prototype

public KeyPair(PublicKey publicKey, PrivateKey privateKey) 

Source Link

Document

Constructs a key pair from the given public key and private key.

Usage

From source file:com.thoughtworks.go.server.util.HttpTestUtil.java

private KeyPair generateKeyPair() {
    try {/*  w w w.  j  av  a  2s.  com*/
        KeyPair seed = KeyPairGenerator.getInstance("RSA", "BC").generateKeyPair();
        RSAPrivateKey privateSeed = (RSAPrivateKey) seed.getPrivate();
        RSAPublicKey publicSeed = (RSAPublicKey) seed.getPublic();
        KeyFactory fact = KeyFactory.getInstance("RSA", "BC");
        RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(privateSeed.getModulus(),
                privateSeed.getPrivateExponent());
        RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(publicSeed.getModulus(),
                publicSeed.getPublicExponent());
        return new KeyPair(fact.generatePublic(publicKeySpec), fact.generatePrivate(privateKeySpec));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.candlepin.splice.SpliceEntitlementFactoryTest.java

private KeyPair createKeyPair() {
    PublicKey pk = mock(PublicKey.class);
    PrivateKey ppk = mock(PrivateKey.class);
    return new KeyPair(pk, ppk);
}

From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java

@Override
public KeyPair getKeyPair(KeyStore ks, String keyAlias, String certAlias, String keyPassword)
        throws CertException {
    KeyPair keyPair = null;/*from   ww  w  .  ja v  a2  s .c  o  m*/
    try {
        if (!ks.containsAlias(keyAlias)) {
            throw new CertException("Missing keystore key entry for key alias:" + keyAlias);
        }
        if (!ks.containsAlias(certAlias)) {
            throw new CertException("Missing keystore certificate entry for :" + certAlias);
        }
        PrivateKey privateKey = (PrivateKey) ks.getKey(keyAlias, keyPassword.toCharArray());
        X509Certificate cert = (X509Certificate) ks.getCertificate(certAlias);
        PublicKey publicKey = cert.getPublicKey();
        keyPair = new KeyPair(publicKey, privateKey);
    } catch (UnrecoverableKeyException e) {
        throw new CertException(e);
    } catch (KeyStoreException e) {
        throw new CertException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertException(e);
    }
    return keyPair;
}

From source file:com.aaasec.sigserv.cssigapp.KeyStoreFactory.java

KeyPair getKeyPair(SigAlgorithms reqSigAlgo, String requestID) {
    KeyPair kp;/*from   w w w . j  a  v  a 2  s.c  o  m*/
    switch (reqSigAlgo) {
    case ECDSA:
        try {
            kp = generateECDSAKeyPair();
            // Save ECDSA key pair
            TestData.storeEcdsaKeyPair(requestID, kp);
            TestData.storeAlgo(requestID, "ECDSA");

            return kp;
        } catch (Exception ex) {
            Logger.getLogger(KeyStoreFactory.class.getName()).warning(ex.getMessage());
        }
        break;
    case RSA:
        KeyStoreObjects kso = getKeyStoreObjects(requestID);
        kp = new KeyPair(kso.getCert().getPublicKey(), kso.getPk());

        // Save key pair in test data
        TestData.storeRSAKeyPair(requestID, kp);
        TestData.storeAlgo(requestID, "RSA");

        return kp;
    }
    return null;
}

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

private KeyPair getKeyPairFromKeystore(KeyStore keystore, String keyAlias, String keyPassword) {
    try {//  w  ww  .  j  av a  2  s . c  om
        PasswordProtection passwordProtected = new PasswordProtection(keyPassword.toCharArray());
        Entry keyEntry = keystore.getEntry(keyAlias, passwordProtected);

        if (!(keyEntry instanceof PrivateKeyEntry)) {
            // Invalid key entry
            return null;
        }
        PrivateKeyEntry pkEntry = (PrivateKeyEntry) keyEntry;
        return new KeyPair(pkEntry.getCertificate().getPublicKey(), pkEntry.getPrivateKey());

    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableEntryException e) {
        // Problem occurred
        e.printStackTrace();
        return null;
    }
}

From source file:org.gluu.oxtrust.action.ManageCertificateAction.java

private KeyPair getKeyPair(String fileName) {
    KeyPair pair = null;/*w w w.  j  ava  2  s . c  o m*/
    JCERSAPrivateCrtKey privateKey = null;
    PEMReader r = null;
    FileReader fileReader = null;

    File keyFile = new File(getTempCertDir() + fileName.replace("crt", "key"));
    if (keyFile.isFile()) {
        try {
            fileReader = new FileReader(keyFile);
            r = new PEMReader(fileReader, new PasswordFinder() {
                public char[] getPassword() {
                    // Since keys are stored without a password this
                    // function should not be called.
                    return null;
                }
            });

            Object keys = r.readObject();
            if (keys == null) {
                log.error(" Unable to read keys from: " + keyFile.getAbsolutePath());
                return null;
            }

            if (keys instanceof KeyPair) {
                pair = (KeyPair) keys;
                log.debug(keyFile.getAbsolutePath() + "contains KeyPair");
            } else if (keys instanceof JCERSAPrivateCrtKey) {

                privateKey = (JCERSAPrivateCrtKey) keys;
                log.debug(keyFile.getAbsolutePath() + "contains JCERSAPrivateCrtKey");
                BigInteger exponent = privateKey.getPublicExponent();
                BigInteger modulus = privateKey.getModulus();

                RSAPublicKeySpec publicKeySpec = new java.security.spec.RSAPublicKeySpec(modulus, exponent);
                PublicKey publicKey = null;
                try {
                    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

                    publicKey = keyFactory.generatePublic(publicKeySpec);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                pair = new KeyPair(publicKey, privateKey);
            } else {
                log.error(keyFile.getAbsolutePath() + " Contains unsupported key type: "
                        + keys.getClass().getName());
                return null;
            }

        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            try {
                r.close();
                fileReader.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return null;
            }
        }
    } else {
        log.error("Key file does not exist : " + keyFile.getAbsolutePath());
    }
    log.debug("KeyPair successfully extracted from: " + keyFile.getAbsolutePath());
    return pair;
}

From source file:org.nuxeo.ecm.core.storage.sql.S3BinaryManager.java

@Override
protected void setupCloudClient() throws IOException {
    // Get settings from the configuration
    bucketName = getProperty(BUCKET_NAME_PROPERTY);
    bucketNamePrefix = MoreObjects.firstNonNull(getProperty(BUCKET_PREFIX_PROPERTY), StringUtils.EMPTY);
    String bucketRegion = getProperty(BUCKET_REGION_PROPERTY);
    if (isBlank(bucketRegion)) {
        bucketRegion = DEFAULT_BUCKET_REGION;
    }//w  ww  .  ja  v a  2 s  . c  o  m
    String awsID = getProperty(AWS_ID_PROPERTY);
    String awsSecret = getProperty(AWS_SECRET_PROPERTY);

    String proxyHost = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_HOST);
    String proxyPort = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PORT);
    String proxyLogin = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_LOGIN);
    String proxyPassword = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PASSWORD);

    int maxConnections = getIntProperty(CONNECTION_MAX_PROPERTY);
    int maxErrorRetry = getIntProperty(CONNECTION_RETRY_PROPERTY);
    int connectionTimeout = getIntProperty(CONNECTION_TIMEOUT_PROPERTY);
    int socketTimeout = getIntProperty(SOCKET_TIMEOUT_PROPERTY);

    String keystoreFile = getProperty(KEYSTORE_FILE_PROPERTY);
    String keystorePass = getProperty(KEYSTORE_PASS_PROPERTY);
    String privkeyAlias = getProperty(PRIVKEY_ALIAS_PROPERTY);
    String privkeyPass = getProperty(PRIVKEY_PASS_PROPERTY);
    String endpoint = getProperty(ENDPOINT_PROPERTY);
    String sseprop = getProperty(SERVERSIDE_ENCRYPTION_PROPERTY);
    if (isNotBlank(sseprop)) {
        userServerSideEncryption = Boolean.parseBoolean(sseprop);
    }

    // Fallback on default env keys for ID and secret
    if (isBlank(awsID)) {
        awsID = System.getenv(AWS_ID_ENV);
    }
    if (isBlank(awsSecret)) {
        awsSecret = System.getenv(AWS_SECRET_ENV);
    }

    if (isBlank(bucketName)) {
        throw new RuntimeException("Missing conf: " + BUCKET_NAME_PROPERTY);
    }

    if (!isBlank(bucketNamePrefix) && !bucketNamePrefix.endsWith("/")) {
        log.warn(String.format("%s %s S3 bucket prefix should end by '/' " + ": added automatically.",
                BUCKET_PREFIX_PROPERTY, bucketNamePrefix));
        bucketNamePrefix += "/";
    }
    // set up credentials
    if (isBlank(awsID) || isBlank(awsSecret)) {
        awsCredentialsProvider = new InstanceProfileCredentialsProvider();
        try {
            awsCredentialsProvider.getCredentials();
        } catch (AmazonClientException e) {
            throw new RuntimeException("Missing AWS credentials and no instance role found");
        }
    } else {
        awsCredentialsProvider = new BasicAWSCredentialsProvider(awsID, awsSecret);
    }

    // set up client configuration
    clientConfiguration = new ClientConfiguration();
    if (isNotBlank(proxyHost)) {
        clientConfiguration.setProxyHost(proxyHost);
    }
    if (isNotBlank(proxyPort)) {
        clientConfiguration.setProxyPort(Integer.parseInt(proxyPort));
    }
    if (isNotBlank(proxyLogin)) {
        clientConfiguration.setProxyUsername(proxyLogin);
    }
    if (proxyPassword != null) { // could be blank
        clientConfiguration.setProxyPassword(proxyPassword);
    }
    if (maxConnections > 0) {
        clientConfiguration.setMaxConnections(maxConnections);
    }
    if (maxErrorRetry >= 0) { // 0 is allowed
        clientConfiguration.setMaxErrorRetry(maxErrorRetry);
    }
    if (connectionTimeout >= 0) { // 0 is allowed
        clientConfiguration.setConnectionTimeout(connectionTimeout);
    }
    if (socketTimeout >= 0) { // 0 is allowed
        clientConfiguration.setSocketTimeout(socketTimeout);
    }

    // set up encryption
    encryptionMaterials = null;
    if (isNotBlank(keystoreFile)) {
        boolean confok = true;
        if (keystorePass == null) { // could be blank
            log.error("Keystore password missing");
            confok = false;
        }
        if (isBlank(privkeyAlias)) {
            log.error("Key alias missing");
            confok = false;
        }
        if (privkeyPass == null) { // could be blank
            log.error("Key password missing");
            confok = false;
        }
        if (!confok) {
            throw new RuntimeException("S3 Crypto configuration incomplete");
        }
        try {
            // Open keystore
            File ksFile = new File(keystoreFile);
            FileInputStream ksStream = new FileInputStream(ksFile);
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(ksStream, keystorePass.toCharArray());
            ksStream.close();
            // Get keypair for alias
            if (!keystore.isKeyEntry(privkeyAlias)) {
                throw new RuntimeException("Alias " + privkeyAlias + " is missing or not a key alias");
            }
            PrivateKey privKey = (PrivateKey) keystore.getKey(privkeyAlias, privkeyPass.toCharArray());
            Certificate cert = keystore.getCertificate(privkeyAlias);
            PublicKey pubKey = cert.getPublicKey();
            KeyPair keypair = new KeyPair(pubKey, privKey);
            // Get encryptionMaterials from keypair
            encryptionMaterials = new EncryptionMaterials(keypair);
            cryptoConfiguration = new CryptoConfiguration();
        } catch (IOException | GeneralSecurityException e) {
            throw new RuntimeException("Could not read keystore: " + keystoreFile + ", alias: " + privkeyAlias,
                    e);
        }
    }
    isEncrypted = encryptionMaterials != null;

    // Try to create bucket if it doesn't exist
    if (!isEncrypted) {
        amazonS3 = new AmazonS3Client(awsCredentialsProvider, clientConfiguration);
    } else {
        amazonS3 = new AmazonS3EncryptionClient(awsCredentialsProvider,
                new StaticEncryptionMaterialsProvider(encryptionMaterials), clientConfiguration,
                cryptoConfiguration);
    }
    if (isNotBlank(endpoint)) {
        amazonS3.setEndpoint(endpoint);
    }

    // Set region explicitely for regions that reguire Version 4 signature
    ArrayList<String> V4_ONLY_REGIONS = new ArrayList<String>();
    V4_ONLY_REGIONS.add("eu-central-1");
    V4_ONLY_REGIONS.add("ap-northeast-2");
    if (V4_ONLY_REGIONS.contains(bucketRegion)) {
        amazonS3.setRegion(Region.getRegion(Regions.fromName(bucketRegion)));
    }

    try {
        if (!amazonS3.doesBucketExist(bucketName)) {
            amazonS3.createBucket(bucketName, bucketRegion);
            amazonS3.setBucketAcl(bucketName, CannedAccessControlList.Private);
        }
    } catch (AmazonClientException e) {
        throw new IOException(e);
    }

    // compat for NXP-17895, using "downloadfroms3", to be removed
    // these two fields have already been initialized by the base class initialize()
    // using standard property "directdownload"
    String dd = getProperty(DIRECTDOWNLOAD_PROPERTY_COMPAT);
    if (dd != null) {
        directDownload = Boolean.parseBoolean(dd);
    }
    int dde = getIntProperty(DIRECTDOWNLOAD_EXPIRE_PROPERTY_COMPAT);
    if (dde >= 0) {
        directDownloadExpire = dde;
    }

    transferManager = new TransferManager(amazonS3);
    abortOldUploads();
}

From source file:org.ejbca.core.model.ca.caadmin.CVCCA.java

/** If the request is a CVC request, this method adds an outer signature to the request.
 * If this request is a CVCA certificate and this is the same CVCA, this method creates a CVCA link certificate.
 * If not creating a link certificate this means that an authenticated request, CVCAuthenticatedRequest is created.
 * /*from  w  w  w.  ja v a  2 s.  c  om*/
 * @see CA#signRequest(byte[], boolean, boolean)
 */
public byte[] signRequest(byte[] request, boolean usepreviouskey, boolean createlinkcert)
        throws CATokenOfflineException {
    if (log.isTraceEnabled()) {
        log.trace(">signRequest: usepreviouskey=" + usepreviouskey + ", createlinkcert=" + createlinkcert);
    }
    byte[] ret = request;
    try {
        CardVerifiableCertificate cacert = (CardVerifiableCertificate) getCACertificate();
        if (cacert == null) {
            // if we don't have a CA certificate, we can't sign any request, just return it
            return request;
        }
        CATokenContainer catoken = getCAToken();
        // Get either the current or the previous signing key for signing this request
        int key = SecConst.CAKEYPURPOSE_CERTSIGN;
        if (usepreviouskey) {
            log.debug("Using previous CertSign key to sign request");
            key = SecConst.CAKEYPURPOSE_CERTSIGN_PREVIOUS;
        } else {
            log.debug("Using current CertSign key to sign request");
        }
        KeyPair keyPair = new KeyPair(catoken.getPublicKey(key), catoken.getPrivateKey(key));
        String signAlg = getCAToken().getCATokenInfo().getSignatureAlgorithm();
        // Create the CA reference, should be from signing certificates holder field
        HolderReferenceField caHolder = cacert.getCVCertificate().getCertificateBody().getHolderReference();
        String sequence = caHolder.getSequence();
        // See if we have a previous sequence to put in the CA reference instead of the same as we have from the request
        String propdata = catoken.getCATokenInfo().getProperties();
        Properties prop = new Properties();
        if (propdata != null) {
            prop.load(new ByteArrayInputStream(propdata.getBytes()));
        }
        String previousSequence = (String) prop.get(ICAToken.PREVIOUS_SEQUENCE_PROPERTY);
        // Only use previous sequence if we also use previous key
        if ((previousSequence != null) && (usepreviouskey)) {
            sequence = previousSequence;
            log.debug("Using previous sequence in caRef: " + sequence);
        } else {
            log.debug("Using current sequence in caRef: " + sequence);
        }
        // Set the CA reference field for the authentication signature
        CAReferenceField caRef = new CAReferenceField(caHolder.getCountry(), caHolder.getMnemonic(), sequence);

        CVCertificate cvcert = null;
        try {
            byte[] binbytes = request;
            try {
                // We don't know if this is a PEM or binary certificate or request request so we first try to 
                // decode it as a PEM certificate, and if it's not we try it as a PEM request and finally as a binary request 
                Collection<Certificate> col = CertTools.getCertsFromPEM(new ByteArrayInputStream(request));
                Certificate cert = col.iterator().next();
                if (cert != null) {
                    binbytes = cert.getEncoded();
                }
            } catch (Exception e) {
                log.debug("This is not a PEM certificate?: " + e.getMessage());
                try {
                    binbytes = RequestMessageUtils.getRequestBytes(request);
                } catch (Exception e2) {
                    log.debug("This is not a PEM request?: " + e2.getMessage());
                }
            }
            // This can be either a CV certificate, a CV certificate request, or an authenticated request that we should re-sign
            CVCObject parsedObject;
            parsedObject = CertificateParser.parseCVCObject(binbytes);
            if (parsedObject instanceof CVCertificate) {
                cvcert = (CVCertificate) parsedObject;
                log.debug("This is a reqular CV request, or cert.");
            } else if (parsedObject instanceof CVCAuthenticatedRequest) {
                CVCAuthenticatedRequest authreq = (CVCAuthenticatedRequest) parsedObject;
                cvcert = authreq.getRequest();
                log.debug(
                        "This is an authenticated CV request, we will overwrite the old authentication with a new.");
            }
        } catch (ParseException e) {
            String msg = intres.getLocalizedMessage("cvc.error.notcvcrequest");
            log.info(msg, e);
            return request;
        } catch (ClassCastException e) {
            String msg = intres.getLocalizedMessage("cvc.error.notcvcrequest");
            log.info(msg, e);
            return request;
        }
        // Check if the input was a CVCA certificate, which is the same CVCA as this. If all is true we should create a CVCA link certificate
        // instead of an authenticated request
        CardVerifiableCertificate cvccert = new CardVerifiableCertificate(cvcert);
        HolderReferenceField cvccertholder = cvccert.getCVCertificate().getCertificateBody()
                .getHolderReference();
        AuthorizationRoleEnum authRole = null;
        AccessRightEnum rights = null;
        try {
            authRole = cvccert.getCVCertificate().getCertificateBody().getAuthorizationTemplate()
                    .getAuthorizationField().getRole();
            rights = cvccert.getCVCertificate().getCertificateBody().getAuthorizationTemplate()
                    .getAuthorizationField().getAccessRight();
        } catch (NoSuchFieldException e) {
            log.debug(
                    "No AuthorizationRoleEnum or AccessRightEnum, this is not a CV certificate so we can't make a link certificate: "
                            + e.getMessage());

        }
        if (createlinkcert && (authRole != null) && (rights != null)) {
            log.debug("We will create a link certificate.");
            String msg = intres.getLocalizedMessage("cvc.info.createlinkcert", cvccertholder.getConcatenated(),
                    caRef.getConcatenated());
            log.info(msg);
            PublicKey pk = cvccert.getPublicKey();
            Date validFrom = cvccert.getCVCertificate().getCertificateBody().getValidFrom();
            Date validTo = cvccert.getCVCertificate().getCertificateBody().getValidTo();
            // Generate a new certificate with the same contents as the passed in certificate, but with new caRef and signature
            CVCertificate retcert = CertificateGenerator.createCertificate(pk, keyPair.getPrivate(), signAlg,
                    caRef, cvccertholder, authRole, rights, validFrom, validTo, catoken.getProvider());
            ret = retcert.getDEREncoded();
            log.debug("Signed a CardVerifiableCertificate CardVerifiableCertificate.");
        } else {
            log.debug("Creating authenticated request with signature alg: " + signAlg + ", using provider "
                    + catoken.getProvider());
            CVCAuthenticatedRequest authreq = CertificateGenerator.createAuthenticatedRequest(cvcert, keyPair,
                    signAlg, caRef, catoken.getProvider());
            ret = authreq.getDEREncoded();
            log.debug("Signed a CardVerifiableCertificate request and returned a CVCAuthenticatedRequest.");
        }
    } catch (IllegalKeyStoreException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (NoSuchProviderException e) {
        throw new RuntimeException(e);
    } catch (SignatureException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ConstructionException e) {
        throw new RuntimeException(e);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<signRequest");
    }
    return ret;
}

From source file:org.panbox.core.crypto.CryptCore.java

/**
 * Converts a given RSA PrivateKey instance to a KeyPair instance. The
 * PublicKey will be extracted from PrivateKey instance.
 * //  w  ww  . j  a v a  2s  . com
 * @param pKey
 *            The RSA PrivateKey used to generate the KeyPair
 * @return KeyPair instance including the private and public key.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static KeyPair privateKeyToKeyPair(PrivateKey pKey)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    KeyFactory keyFactory = KeyFactory.getInstance(KeyConstants.KEY_FACTORY, new BouncyCastleProvider());
    RSAPrivateCrtKey rsaPKey = (RSAPrivateCrtKey) pKey;
    RSAPublicKeySpec publicKeySpec = new java.security.spec.RSAPublicKeySpec(rsaPKey.getModulus(),
            rsaPKey.getPublicExponent());
    return new KeyPair(keyFactory.generatePublic(publicKeySpec), pKey);
}

From source file:com.adito.boot.KeyStoreManager.java

/**
 * Get a key pair from this key store//from www. j  ava  2s . co  m
 * 
 * @param alias alias under which the pair is stored
 * @param password password protecting the keys if any
 * @return key pair
 */
public KeyPair getKeyPair(String alias, char[] password) {
    try {
        checkKeyStore();
        if (isKeyStoreExists() && !isKeyStoreEmpty()) {
            Key key = keyStore.getKey(alias, password);
            if (key instanceof PrivateKey) {
                Certificate cert = keyStore.getCertificate(alias);
                PublicKey publicKey = cert.getPublicKey();
                return new KeyPair(publicKey, (PrivateKey) key);
            }
        }
    } catch (Exception e) {
        log.error("Could not get key pair with alias " + alias + ".", e);
    }
    return null;
}