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:org.ejbca.core.protocol.ws.client.CvcRequestCommand.java

/**
 * Runs the command/*from w  ww . java2s .com*/
 *
 * @throws IllegalAdminCommandException Error in command args
 * @throws ErrorAdminCommandException Error running command
 */
public void execute() throws IllegalAdminCommandException, ErrorAdminCommandException {

    try {
        if (args.length < 9 || args.length > 11) {
            getPrintStream().println("Number of arguments: " + args.length);
            usage();
            System.exit(-1); // NOPMD, this is not a JEE app
        }

        String username = args[ARG_USERNAME];
        String userpassword = args[ARG_PASSWORD];
        String dn = args[ARG_SUBJECTDN];
        String sequence = args[ARG_SEQUENCE];
        String signatureAlg = args[ARG_SIGNALG];
        String keySpec = args[ARG_KEYSPEC];
        boolean genrequest = args[ARG_GENREQ].equalsIgnoreCase("true");
        String basefilename = args[ARG_BASEFILENAME];
        String authSignKeyFile = null;
        if (args.length > (ARG_AUTHSIGNKEY)) {
            authSignKeyFile = args[ARG_AUTHSIGNKEY];
        }
        String authSignCertFile = null;
        if (args.length > (ARG_AUTHSIGNCERT)) {
            authSignCertFile = args[ARG_AUTHSIGNCERT];
        }

        getPrintStream().println("Enrolling user:");
        getPrintStream().println("Username: " + username);
        getPrintStream().println("Subject name: " + dn);
        getPrintStream().println("Sequence: " + sequence);
        getPrintStream().println("Signature algorithm: " + signatureAlg);
        getPrintStream().println("Key spec: " + keySpec);

        try {
            CryptoProviderTools.installBCProvider();

            String cvcreq = null;
            if (genrequest) {
                getPrintStream().println("Generating a new request with base filename: " + basefilename);
                // Generate keys for the request
                String keytype = "RSA";
                if (signatureAlg.contains("ECDSA")) {
                    keytype = "ECDSA";
                }
                KeyPair keyPair = KeyTools.genKeys(keySpec, keytype);
                String country = CertTools.getPartFromDN(dn, "C");
                String mnemonic = CertTools.getPartFromDN(dn, "CN");
                if (sequence.equalsIgnoreCase("null")) {
                    sequence = RandomStringUtils.randomNumeric(5);
                    getPrintStream().println("No sequence given, using random 5 number sequence: " + sequence);
                }
                //CAReferenceField caRef = new CAReferenceField(country,mnemonic,sequence);
                CAReferenceField caRef = null; // Don't create a caRef in the self signed request
                // We are making a self signed request, so holder ref is same as ca ref
                HolderReferenceField holderRef = new HolderReferenceField(country, mnemonic, sequence);
                CVCertificate request = CertificateGenerator.createRequest(keyPair, signatureAlg, caRef,
                        holderRef);
                byte[] der = request.getDEREncoded();
                if (authSignKeyFile != null) {
                    getPrintStream().println("Reading private key from pkcs8 file " + authSignKeyFile
                            + " to create an authenticated request");
                    byte[] keybytes = FileTools.readFiletoBuffer(authSignKeyFile);
                    KeyFactory keyfact = KeyFactory.getInstance(keytype, "BC");
                    PrivateKey privKey = keyfact.generatePrivate(new PKCS8EncodedKeySpec(keybytes));
                    KeyPair authKeyPair = new KeyPair(null, privKey); // We don't need the public key
                    // Default caRef if we do not pass in a certificate to get caRef from
                    CAReferenceField authCaRef = new CAReferenceField(country, mnemonic, sequence);
                    CVCertificate authCert = null;
                    if (authSignCertFile != null) {
                        getPrintStream().println("Reading cert from cvcert file " + authSignCertFile
                                + " to create an authenticated request");
                        CVCObject parsedObject = CvcPrintCommand.getCVCObject(authSignCertFile);
                        authCert = (CVCertificate) parsedObject;
                        String c = authCert.getCertificateBody().getHolderReference().getCountry();
                        String m = authCert.getCertificateBody().getHolderReference().getMnemonic();
                        String s = authCert.getCertificateBody().getHolderReference().getSequence();
                        authCaRef = new CAReferenceField(c, m, s);
                    }
                    CVCAuthenticatedRequest authRequest = CertificateGenerator
                            .createAuthenticatedRequest(request, authKeyPair, signatureAlg, authCaRef);
                    // Test to verify it yourself first
                    if (authCert != null) {
                        getPrintStream().println("Verifying the request before sending it...");
                        PublicKey pk = KeyTools.getECPublicKeyWithParams(
                                authCert.getCertificateBody().getPublicKey(), keySpec);
                        authRequest.verify(pk);
                    }
                    der = authRequest.getDEREncoded();
                }
                cvcreq = new String(Base64.encode(der));
                // Print the generated request to file
                FileOutputStream fos = new FileOutputStream(basefilename + ".cvreq");
                fos.write(der);
                fos.close();
                getPrintStream().println("Wrote binary request to: " + basefilename + ".cvreq");
                fos = new FileOutputStream(basefilename + ".pkcs8");
                fos.write(keyPair.getPrivate().getEncoded());
                fos.close();
                getPrintStream().println("Wrote private key in " + keyPair.getPrivate().getFormat()
                        + " format to to: " + basefilename + ".pkcs8");
            } else {
                // Read request from file
                getPrintStream().println("Reading request from filename: " + basefilename + ".cvreq");
                byte[] der = FileTools.readFiletoBuffer(basefilename + ".cvreq");
                cvcreq = new String(Base64.encode(der));
            }

            // Edit a user, creating it if it does not exist
            // Actually don't do that, leverage the existing commands and force to use the editUser command instead.
            // This also makes this CLI exactly represent the actual WS-API call 
            // getEjbcaRAWS().editUser(userdata);

            getPrintStream().println("Submitting CVC request for user '" + username + "'.");
            getPrintStream().println();
            // Use the request and request a certificate
            List<Certificate> resp = getEjbcaRAWS().cvcRequest(username, userpassword, cvcreq);

            // Handle the response
            Certificate cert = resp.get(0);
            byte[] b64cert = cert.getCertificateData();
            CVCObject parsedObject = CertificateParser.parseCertificate(Base64.decode(b64cert));
            CVCertificate cvcert = (CVCertificate) parsedObject;
            FileOutputStream fos = new FileOutputStream(basefilename + ".cvcert");
            fos.write(cvcert.getDEREncoded());
            fos.close();
            getPrintStream().println("Wrote binary certificate to: " + basefilename + ".cvcert");
            getPrintStream().println("You can look at the certificate with the command cvcwscli.sh cvcprint "
                    + basefilename + ".cvcert");
        } catch (AuthorizationDeniedException_Exception e) {
            getPrintStream().println("Error : " + e.getMessage());
        } catch (UserDoesntFullfillEndEntityProfile_Exception e) {
            getPrintStream()
                    .println("Error : Given userdata doesn't fullfill end entity profile. : " + e.getMessage());
        }

    } catch (Exception e) {
        if (e instanceof EjbcaException_Exception) {
            EjbcaException_Exception e1 = (EjbcaException_Exception) e;
            getPrintStream()
                    .println("Error code is: " + e1.getFaultInfo().getErrorCode().getInternalErrorCode());
        }
        throw new ErrorAdminCommandException(e);
    }
}

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

/**
 * @see CA#createRequest(Collection, String, Certificate, int)
 *///from   w ww.java2  s .c o m
public byte[] createRequest(Collection<DEREncodable> attributes, String signAlg, Certificate cacert,
        int signatureKeyPurpose) throws CATokenOfflineException {
    if (log.isTraceEnabled()) {
        log.trace(">createRequest: " + signAlg + ", " + CertTools.getSubjectDN(cacert) + ", "
                + signatureKeyPurpose);
    }
    byte[] ret = null;
    // Create a CVC request. 
    // No outer signature on this self signed request
    KeyPair keyPair;
    try {
        CATokenContainer catoken = getCAToken();
        keyPair = new KeyPair(catoken.getPublicKey(signatureKeyPurpose),
                catoken.getPrivateKey(signatureKeyPurpose));
        if (keyPair == null) {
            throw new IllegalArgumentException(
                    "Keys for key purpose " + signatureKeyPurpose + " does not exist.");
        }
        String subject = getCAInfo().getSubjectDN();
        String country = CertTools.getPartFromDN(subject, "C");
        String mnemonic = CertTools.getPartFromDN(subject, "CN");
        String seq = getCAToken().getCATokenInfo().getKeySequence();
        if (signatureKeyPurpose == SecConst.CAKEYPURPOSE_CERTSIGN_NEXT) {
            // See if we have a next sequence to put in the holder reference instead of the current one, 
            // since we are using the next key we should use the next sequence
            String propdata = catoken.getCATokenInfo().getProperties();
            Properties prop = new Properties();
            if (propdata != null) {
                prop.load(new ByteArrayInputStream(propdata.getBytes()));
            }
            String nextSequence = (String) prop.get(ICAToken.NEXT_SEQUENCE_PROPERTY);
            // Only use next sequence if we also use previous key
            if (nextSequence != null) {
                seq = nextSequence;
                log.debug("Using next sequence in holderRef: " + seq);
            } else {
                log.debug(
                        "Using current sequence in holderRef, although we are using the next key...no next sequence was found: "
                                + seq);
            }
        }
        if (seq == null) {
            log.info("No sequence found in ca token info, using random 5 number sequence.");
            seq = RandomStringUtils.randomNumeric(5);
        }
        if (seq.length() > 5) {
            log.info("Sequence " + seq + " is too long, only using first 5.");
            seq = seq.substring(0, 4);
        }
        if (seq.length() < 5) {
            log.info("Sequence " + seq + " is too short, padding with zeroes.");
            for (int i = seq.length(); i < 5; i++) {
                seq = "0" + seq;
            }
        }
        HolderReferenceField holderRef = new HolderReferenceField(country, mnemonic, seq);
        CAReferenceField caRef = null;
        if (cacert != null) {
            if (cacert instanceof CardVerifiableCertificate) {
                CardVerifiableCertificate cvcacert = (CardVerifiableCertificate) cacert;
                try {
                    HolderReferenceField href = cvcacert.getCVCertificate().getCertificateBody()
                            .getHolderReference();
                    caRef = new CAReferenceField(href.getCountry(), href.getMnemonic(), href.getSequence());
                    log.debug("Using caRef from the CA certificate: " + caRef.getConcatenated());
                } catch (NoSuchFieldException e) {
                    log.debug("CA certificate does not contain a Holder reference to use as CARef in request.");
                }
            } else {
                log.debug("CA certificate is not a CardVerifiableCertificate.");
            }
        } else {
            caRef = new CAReferenceField(holderRef.getCountry(), holderRef.getMnemonic(),
                    holderRef.getSequence());
            log.debug("No CA cert, using caRef from the holder itself: " + caRef.getConcatenated());
        }
        log.debug("Creating request with signature alg: " + signAlg + ", using provider "
                + catoken.getProvider());
        CVCertificate request = CertificateGenerator.createRequest(keyPair, signAlg, caRef, holderRef,
                catoken.getProvider());
        ret = request.getDEREncoded();
    } 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);
    }
    log.trace("<createRequest");
    return ret;
}

From source file:jenkins.bouncycastle.api.PEMEncodable.java

/**
 * Creates a {@link PEMEncodable} by decoding PEM formated data from a {@link String}
 * //from  www  .  j av a  2  s.  com
 * @param pem {@link String} with the PEM data
 * @param passphrase passphrase for the encrypted PEM data. null if PEM data is not passphrase protected. The caller
 * is responsible for zeroing out the char[] after use to ensure the password does not stay in memory, e.g. with
 * <code>Arrays.fill(passphrase, (char)0)</code>
 * @return {@link PEMEncodable} object
 * @throws IOException launched if a problem exists reading the PEM information
 * @throws UnrecoverableKeyException in case PEM is passphrase protected and none or wrong is provided
 */
@Nonnull
public static PEMEncodable decode(@Nonnull String pem, @Nullable final char[] passphrase)
        throws IOException, UnrecoverableKeyException {

    try (PEMParser parser = new PEMParser(new StringReader(pem));) {

        Object object = parser.readObject();

        JcaPEMKeyConverter kConv = new JcaPEMKeyConverter().setProvider("BC");

        // handle supported PEM formats.
        if (object instanceof PEMEncryptedKeyPair) {
            if (passphrase != null) {
                PEMDecryptorProvider dp = new JcePEMDecryptorProviderBuilder().build(passphrase);
                PEMEncryptedKeyPair ekp = (PEMEncryptedKeyPair) object;
                return new PEMEncodable(kConv.getKeyPair(ekp.decryptKeyPair(dp)));
            } else {
                throw new UnrecoverableKeyException();
            }
        } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
            if (passphrase != null) {
                InputDecryptorProvider dp = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passphrase);
                PKCS8EncryptedPrivateKeyInfo epk = (PKCS8EncryptedPrivateKeyInfo) object;
                return new PEMEncodable(kConv.getPrivateKey(epk.decryptPrivateKeyInfo(dp)));
            } else {
                throw new UnrecoverableKeyException();
            }
        } else if (object instanceof PEMKeyPair) {
            return new PEMEncodable(kConv.getKeyPair((PEMKeyPair) object));
        } else if (object instanceof PrivateKeyInfo) {
            PrivateKey pk = kConv.getPrivateKey((PrivateKeyInfo) object);

            // JENKINS-35661 in this case we know how to get the public key too
            if (pk instanceof RSAPrivateCrtKey) {
                // obtain public key spec from the private key
                RSAPrivateCrtKey rsaPK = (RSAPrivateCrtKey) pk;
                RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(rsaPK.getModulus(),
                        rsaPK.getPublicExponent());
                KeyFactory kf = KeyFactory.getInstance("RSA");
                return new PEMEncodable(new KeyPair(kf.generatePublic(pubKeySpec), rsaPK));
            }

            return new PEMEncodable(pk);
        } else if (object instanceof SubjectPublicKeyInfo) {
            return new PEMEncodable(kConv.getPublicKey((SubjectPublicKeyInfo) object));
        } else if (object instanceof X509CertificateHolder) {
            JcaX509CertificateConverter cConv = new JcaX509CertificateConverter().setProvider("BC");
            return new PEMEncodable(cConv.getCertificate((X509CertificateHolder) object));
        } else {
            throw new IOException(
                    "Could not parse PEM, only key pairs, private keys, public keys and certificates are supported. Received "
                            + object.getClass().getName());
        }
    } catch (OperatorCreationException e) {
        throw new IOException(e.getMessage(), e);
    } catch (PKCSException | InvalidKeySpecException e) {
        LOGGER.log(Level.WARNING, "Could not read PEM encrypted information", e);
        throw new UnrecoverableKeyException();
    } catch (CertificateException e) {
        throw new IOException("Could not read certificate", e);
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(
                "RSA algorithm support is mandated by Java Language Specification. See https://docs.oracle.com/javase/7/docs/api/java/security/KeyFactory.html");
    }
}

From source file:org.gluu.com.ox_push2.u2f.v2.cert.KeyPairGeneratorImpl.java

public KeyPair keyPairFromJson(String keyPairJson) throws U2FException {
    BigInteger x = null;//from w  w w  .j a v  a  2s  .co  m
    BigInteger y = null;
    BigInteger d = null;

    try {
        JSONObject jsonKeyPair = (JSONObject) new JSONTokener(keyPairJson).nextValue();

        JSONObject jsonPrivateKey = jsonKeyPair.getJSONObject("privateKey");
        d = new BigInteger(Utils.decodeHexString(jsonPrivateKey.getString("d")));

        JSONObject jsonPublicKey = jsonKeyPair.getJSONObject("publicKey");
        x = new BigInteger(Utils.decodeHexString(jsonPublicKey.getString("x")));
        y = new BigInteger(Utils.decodeHexString(jsonPublicKey.getString("y")));
    } catch (JSONException ex) {
        throw new U2FException("Failed to deserialize key pair from JSON", ex);
    } catch (DecoderException ex) {
        throw new U2FException("Failed to deserialize key pair from JSON", ex);
    }

    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256r1");

    ECCurve curve = ecSpec.getCurve();
    ECPoint validatePoint = curve.validatePoint(x, y);

    ECPublicKeySpec publicKeySpec = new ECPublicKeySpec(validatePoint, ecSpec);
    ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(d, ecSpec);

    KeyFactory keyFactory = null;
    try {
        keyFactory = KeyFactory.getInstance("ECDSA", BOUNCY_CASTLE_PROVIDER);
        PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

        return new KeyPair(publicKey, privateKey);
    } catch (NoSuchAlgorithmException ex) {
        throw new U2FException("Failed to deserialize key pair from JSON", ex);
    } catch (InvalidKeySpecException ex) {
        throw new U2FException("Failed to deserialize key pair from JSON", ex);
    }
}

From source file:org.apache.cloudstack.saml.SAML2AuthManagerImpl.java

protected boolean initSP() {
    KeystoreVO keyStoreVO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_KEYPAIR);
    if (keyStoreVO == null) {
        try {/*from w  ww  . j  ava2  s  .c  o m*/
            KeyPair keyPair = SAMLUtils.generateRandomKeyPair();
            _ksDao.save(SAMLPluginConstants.SAMLSP_KEYPAIR, SAMLUtils.savePrivateKey(keyPair.getPrivate()),
                    SAMLUtils.savePublicKey(keyPair.getPublic()), "samlsp-keypair");
            keyStoreVO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_KEYPAIR);
            s_logger.info("No SAML keystore found, created and saved a new Service Provider keypair");
        } catch (NoSuchProviderException | NoSuchAlgorithmException e) {
            s_logger.error("Unable to create and save SAML keypair: " + e.toString());
        }
    }

    String spId = SAMLServiceProviderID.value();
    String spSsoUrl = SAMLServiceProviderSingleSignOnURL.value();
    String spSloUrl = SAMLServiceProviderSingleLogOutURL.value();
    String spOrgName = SAMLServiceProviderOrgName.value();
    String spOrgUrl = SAMLServiceProviderOrgUrl.value();
    String spContactPersonName = SAMLServiceProviderContactPersonName.value();
    String spContactPersonEmail = SAMLServiceProviderContactEmail.value();
    KeyPair spKeyPair = null;
    X509Certificate spX509Key = null;
    if (keyStoreVO != null) {
        PrivateKey privateKey = SAMLUtils.loadPrivateKey(keyStoreVO.getCertificate());
        PublicKey publicKey = SAMLUtils.loadPublicKey(keyStoreVO.getKey());
        if (privateKey != null && publicKey != null) {
            spKeyPair = new KeyPair(publicKey, privateKey);
            KeystoreVO x509VO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_X509CERT);
            if (x509VO == null) {
                try {
                    spX509Key = SAMLUtils.generateRandomX509Certificate(spKeyPair);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    ObjectOutput out = new ObjectOutputStream(bos);
                    out.writeObject(spX509Key);
                    out.flush();
                    _ksDao.save(SAMLPluginConstants.SAMLSP_X509CERT,
                            Base64.encodeBase64String(bos.toByteArray()), "", "samlsp-x509cert");
                    bos.close();
                } catch (NoSuchAlgorithmException | NoSuchProviderException | CertificateEncodingException
                        | SignatureException | InvalidKeyException | IOException e) {
                    s_logger.error("SAML Plugin won't be able to use X509 signed authentication");
                }
            } else {
                try {
                    ByteArrayInputStream bi = new ByteArrayInputStream(
                            Base64.decodeBase64(x509VO.getCertificate()));
                    ObjectInputStream si = new ObjectInputStream(bi);
                    spX509Key = (X509Certificate) si.readObject();
                    bi.close();
                } catch (IOException | ClassNotFoundException ignored) {
                    s_logger.error(
                            "SAML Plugin won't be able to use X509 signed authentication. Failed to load X509 Certificate from Database.");
                }
            }
        }
    }
    if (spKeyPair != null && spX509Key != null && spId != null && spSsoUrl != null && spSloUrl != null
            && spOrgName != null && spOrgUrl != null && spContactPersonName != null
            && spContactPersonEmail != null) {
        _spMetadata.setEntityId(spId);
        _spMetadata.setOrganizationName(spOrgName);
        _spMetadata.setOrganizationUrl(spOrgUrl);
        _spMetadata.setContactPersonName(spContactPersonName);
        _spMetadata.setContactPersonEmail(spContactPersonEmail);
        _spMetadata.setSsoUrl(spSsoUrl);
        _spMetadata.setSloUrl(spSloUrl);
        _spMetadata.setKeyPair(spKeyPair);
        _spMetadata.setSigningCertificate(spX509Key);
        _spMetadata.setEncryptionCertificate(spX509Key);
        return true;
    }
    return false;
}

From source file:net.adamcin.httpsig.testutil.KeyTestUtil.java

public static KeyPair getKeyPairFromProperties(String parentName, String keyName) {
    InputStream is = null;//from   ww  w.  j av  a2s .  co  m
    try {
        is = KeyTestUtil.class.getResourceAsStream("/" + parentName + "/" + keyName + ".properties");
        Properties props = new Properties();
        props.load(is);
        if (TYPE_RSA.equals(props.getProperty(P_TYPE))) {
            RSAPrivateKeySpec privSpec = null;
            if (props.getProperty(RSA_P) != null && props.getProperty(RSA_Q) != null
                    && props.getProperty(RSA_U) != null) {
                privSpec = new RSAPrivateCrtKeySpec(new BigInteger(props.getProperty(RSA_N)),
                        new BigInteger(props.getProperty(RSA_E)), new BigInteger(props.getProperty(RSA_D)),
                        new BigInteger(props.getProperty(RSA_P)), new BigInteger(props.getProperty(RSA_Q)),
                        new BigInteger(props.getProperty(RSA_PE)), new BigInteger(props.getProperty(RSA_QE)),
                        new BigInteger(props.getProperty(RSA_U)));
            } else {
                privSpec = new RSAPrivateKeySpec(new BigInteger(props.getProperty(RSA_N)),
                        new BigInteger(props.getProperty(RSA_D)));
            }
            RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(new BigInteger(props.getProperty(RSA_N)),
                    new BigInteger(props.getProperty(RSA_E)));

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return new KeyPair(keyFactory.generatePublic(pubSpec), keyFactory.generatePrivate(privSpec));
        } else if (TYPE_DSA.equals(props.getProperty(P_TYPE))) {
            DSAPrivateKeySpec privSpec = new DSAPrivateKeySpec(new BigInteger(props.getProperty(DSA_X)),
                    new BigInteger(props.getProperty(DSA_P)), new BigInteger(props.getProperty(DSA_Q)),
                    new BigInteger(props.getProperty(DSA_G)));
            DSAPublicKeySpec pubSpec = new DSAPublicKeySpec(new BigInteger(props.getProperty(DSA_Y)),
                    new BigInteger(props.getProperty(DSA_P)), new BigInteger(props.getProperty(DSA_Q)),
                    new BigInteger(props.getProperty(DSA_G)));
            KeyFactory keyFactory = KeyFactory.getInstance("DSA");
            return new KeyPair(keyFactory.generatePublic(pubSpec), keyFactory.generatePrivate(privSpec));
        }
    } catch (Exception e) {
        LOGGER.error("Failed to read properties", e);
    } finally {
        IOUtils.closeQuietly(is);
    }

    return null;
}

From source file:uk.co.develop4.security.utils.decoders.DecoderUtils.java

private static KeyPair getKeyPairFromOpenSslPemFile(String fileName, String passphrase, String providerName)
        throws IOException {
    Reader fRd = null;/*from www . ja va 2s.  c o m*/
    PEMParser pemParser = null;
    KeyPair keypair = null;
    try {
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(providerName);
        PEMDecryptorProvider pemProv = new JcePEMDecryptorProviderBuilder().setProvider(providerName)
                .build(passphrase.toCharArray());
        InputDecryptorProvider pkcs8Prov = new JceOpenSSLPKCS8DecryptorProviderBuilder()
                .build(passphrase.toCharArray());
        //res = this.getClass().getResourceAsStream(fileName);
        File file = DecoderUtils.isFile(fileName);
        FileReader fr = new FileReader(file);
        fRd = new BufferedReader(fr);
        pemParser = new PEMParser(fRd);
        Object obj = pemParser.readObject();

        if (obj instanceof PEMEncryptedKeyPair) {
            keypair = converter.getKeyPair(((PEMEncryptedKeyPair) obj).decryptKeyPair(pemProv));
        } else if (obj instanceof PKCS8EncryptedPrivateKeyInfo) {
            keypair = new KeyPair(null, converter
                    .getPrivateKey(((PKCS8EncryptedPrivateKeyInfo) obj).decryptPrivateKeyInfo(pkcs8Prov)));
        } else if (obj instanceof SubjectPublicKeyInfo) {
            keypair = new KeyPair((PublicKey) converter.getPublicKey((SubjectPublicKeyInfo) obj), null);
        } else if (obj instanceof X509CertificateHolder) {
            SubjectPublicKeyInfo sub = (SubjectPublicKeyInfo) ((X509CertificateHolder) obj)
                    .getSubjectPublicKeyInfo();
            keypair = new KeyPair((PublicKey) converter.getPublicKey((SubjectPublicKeyInfo) sub), null);
        } else {
            keypair = converter.getKeyPair((PEMKeyPair) obj);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        pemParser.close();
    }
    return keypair;
}

From source file:org.limewire.mojito.Context.java

/**
 * Constructor to create a new Context// w  ww . j a v a 2  s.  c o  m
 */
Context(String name, Vendor vendor, Version version, boolean firewalled) {
    this.name = name;

    PublicKey masterKey = null;
    try {
        File file = new File(ContextSettings.MASTER_KEY.get());
        if (file.exists() && file.isFile()) {
            masterKey = CryptoUtils.loadPublicKey(file);
        }
    } catch (InvalidKeyException e) {
        LOG.debug("InvalidKeyException", e);
    } catch (SignatureException e) {
        LOG.debug("SignatureException", e);
    } catch (IOException e) {
        LOG.debug("IOException", e);
    }
    keyPair = new KeyPair(masterKey, null);

    executorService = new DefaultDHTExecutorService(getName());

    MACCalculatorRepositoryManager = new MACCalculatorRepositoryManager();
    tokenProvider = new SecurityToken.AddressSecurityTokenProvider(MACCalculatorRepositoryManager);

    tokenHelper = new SecurityTokenHelper(this);

    setRouteTable(null);
    setDatabase(null, false);

    // Init the Stats
    stats = DHTStatsManager.getInstance(getLocalNodeID());
    networkStats = new NetworkStatisticContainer(getLocalNodeID());
    globalLookupStats = new GlobalLookupStatisticContainer(getLocalNodeID());
    databaseStats = new DatabaseStatisticContainer(getLocalNodeID());

    setMessageDispatcher(null);

    messageHelper = new MessageHelper(this);
    valuePublisher = new StorablePublisher(this);
    databaseCleaner = new DatabaseCleaner(this);

    bucketRefresher = new BucketRefresher(this);

    pingManager = new PingManager(this);
    findNodeManager = new FindNodeManager(this);
    findValueManager = new FindValueManager(this);
    storeManager = new StoreManager(this);
    bootstrapManager = new BootstrapManager(this);
    getValueManager = new GetValueManager(this);

    getLocalNode().setVendor(vendor);
    getLocalNode().setVersion(version);
    getLocalNode().setFirewalled(firewalled);
}

From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java

public KeyStore generateKeyStore() throws CryptoException {
    try {/*from   w  w w.  j a  v a 2 s . c om*/
        logger.debug("Generating a new key store.");

        /* Add BC to the jdk security manager to be able to use it as a provider */
        Security.addProvider(new BouncyCastleProvider());

        /* Create and init an empty key store */
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, null);

        /*
         * Populate all new key stores with the key data of the local resolver, generally this is for metadata
         * purposes to ensure that all systems in the authentication network can correctly validate the signed
         * metadata document
         */
        X509Certificate localCertificate = (X509Certificate) localResolver.getLocalCertificate();
        Calendar before = new GregorianCalendar();
        Calendar expiry = new GregorianCalendar();
        before.setTime(localCertificate.getNotBefore());
        expiry.setTime(localCertificate.getNotAfter());

        addPublicKey(keyStore,
                new KeyPair(this.localResolver.getLocalPublicKey(), this.localResolver.getLocalPrivateKey()),
                this.localResolver.getLocalKeyAlias(), this.certIssuerDN, before, expiry);

        return keyStore;
    } catch (KeyStoreException e) {
        this.logger.error("KeyStoreException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        this.logger.error("NoSuchAlgorithmException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (CertificateException e) {
        this.logger.error("CertificateException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (IOException e) {
        this.logger.error("IOException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    }
}

From source file:org.cloudfoundry.identity.uaa.oauth.SignerProvider.java

static KeyPair parseKeyPair(String pemData) {
    Matcher m = PEM_DATA.matcher(pemData.trim());

    if (!m.matches()) {
        throw new IllegalArgumentException("String is not PEM encoded data");
    }/* w  w w. j  a  va 2 s  .c o m*/

    String type = m.group(1);
    final byte[] content = b64Decode(utf8Encode(m.group(2)));

    PublicKey publicKey;
    PrivateKey privateKey = null;

    try {
        KeyFactory fact = KeyFactory.getInstance("RSA");
        if (type.equals("RSA PRIVATE KEY")) {
            ASN1Sequence seq = ASN1Sequence.getInstance(content);
            if (seq.size() != 9) {
                throw new IllegalArgumentException("Invalid RSA Private Key ASN1 sequence.");
            }
            org.bouncycastle.asn1.pkcs.RSAPrivateKey key = org.bouncycastle.asn1.pkcs.RSAPrivateKey
                    .getInstance(seq);
            RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
            RSAPrivateCrtKeySpec privSpec = new RSAPrivateCrtKeySpec(key.getModulus(), key.getPublicExponent(),
                    key.getPrivateExponent(), key.getPrime1(), key.getPrime2(), key.getExponent1(),
                    key.getExponent2(), key.getCoefficient());
            publicKey = fact.generatePublic(pubSpec);
            privateKey = fact.generatePrivate(privSpec);
        } else if (type.equals("PUBLIC KEY")) {
            KeySpec keySpec = new X509EncodedKeySpec(content);
            publicKey = fact.generatePublic(keySpec);
        } else if (type.equals("RSA PUBLIC KEY")) {
            ASN1Sequence seq = ASN1Sequence.getInstance(content);
            org.bouncycastle.asn1.pkcs.RSAPublicKey key = org.bouncycastle.asn1.pkcs.RSAPublicKey
                    .getInstance(seq);
            RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
            publicKey = fact.generatePublic(pubSpec);
        } else {
            throw new IllegalArgumentException(type + " is not a supported format");
        }

        return new KeyPair(publicKey, privateKey);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    }
}