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:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java

public PKCS10CertificationRequest createCSR(X500Name x500Name, KeyPair keyPair) throws Exception {
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();
    PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(x500Name,
            publicKey);//  ww w.j  ava 2s .c o m
    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(ALG_SIG_SHA256_RSA);
    ContentSigner signer = csBuilder.build(privateKey);
    PKCS10CertificationRequest csr = p10Builder.build(signer);

    return csr;
}

From source file:org.apache.sshd.server.kex.AbstractDHGServer.java

public boolean next(Buffer buffer) throws Exception {
    SshConstants.Message cmd = buffer.getCommand();
    if (cmd != SshConstants.Message.SSH_MSG_KEXDH_INIT) {
        throw new SshException(SshConstants.SSH2_DISCONNECT_KEY_EXCHANGE_FAILED,
                "Protocol error: expected packet " + SshConstants.Message.SSH_MSG_KEXDH_INIT + ", got " + cmd);
    }/*from   w ww.j av a 2s  .c  om*/
    log.info("Received SSH_MSG_KEXDH_INIT");
    e = buffer.getMPIntAsBytes();
    dh.setF(e);
    K = dh.getK();

    byte[] K_S;
    KeyPair kp = session.getHostKey();
    String algo = session.getNegociated(SshConstants.PROPOSAL_SERVER_HOST_KEY_ALGS);
    Signature sig = NamedFactory.Utils.create(session.getFactoryManager().getSignatureFactories(), algo);
    sig.init(kp.getPublic(), kp.getPrivate());

    buffer = new Buffer();
    buffer.putRawPublicKey(kp.getPublic());
    K_S = buffer.getCompactData();

    buffer.clear();
    buffer.putString(V_C);
    buffer.putString(V_S);
    buffer.putString(I_C);
    buffer.putString(I_S);
    buffer.putString(K_S);
    buffer.putMPInt(e);
    buffer.putMPInt(f);
    buffer.putMPInt(K);
    sha.update(buffer.array(), 0, buffer.available());
    H = sha.digest();

    byte[] sigH;
    buffer.clear();
    sig.update(H, 0, H.length);
    buffer.putString(algo);
    buffer.putString(sig.sign());
    sigH = buffer.getCompactData();

    if (log.isDebugEnabled()) {
        log.debug("K_S:  " + BufferUtils.printHex(K_S));
        log.debug("f:    " + BufferUtils.printHex(f));
        log.debug("sigH: " + BufferUtils.printHex(sigH));
    }

    // Send response
    log.info("Send SSH_MSG_KEXDH_REPLY");
    buffer.clear();
    buffer.rpos(5);
    buffer.wpos(5);
    buffer.putCommand(SshConstants.Message.SSH_MSG_KEXDH_REPLY_KEX_DH_GEX_GROUP);
    buffer.putString(K_S);
    buffer.putString(f);
    buffer.putString(sigH);
    session.writePacket(buffer);
    return true;
}

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

private X509Certificate createRootCaCert(X500Name idn, KeyPair keyPair) throws Exception {

    PublicKey pubKey = keyPair.getPublic();
    PrivateKey privKey = keyPair.getPrivate();

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

    X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(idn, sno, nb, na, idn, pubKey);

    addSubjectKID(certBuilder, pubKey);//w ww.  j  ava 2s.c  o m
    addAuthorityKID(certBuilder, pubKey);
    addCRLDistributionPoints(certBuilder);
    addAuthorityInfoAccess(certBuilder);
    certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(Boolean.TRUE));

    X509Certificate certificate = signCert(certBuilder, privKey);
    certificate.checkValidity(new Date());
    certificate.verify(pubKey);

    setPKCS9Info(certificate);

    return certificate;
}

From source file:io.kodokojo.endpoint.UserSparkEndpoint.java

@Override
public void configure() {
    post(BASE_API + "/user/:id", JSON_CONTENT_TYPE, ((request, response) -> {
        String identifier = request.params(":id");
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Try to create user with id {}", identifier);
        }/*from ww  w. j  av a  2 s . com*/
        if (userStore.identifierExpectedNewUser(identifier)) {
            JsonParser parser = new JsonParser();
            JsonObject json = (JsonObject) parser.parse(request.body());
            String email = json.getAsJsonPrimitive("email").getAsString();

            String username = email.substring(0, email.lastIndexOf("@"));
            User userByUsername = userStore.getUserByUsername(username);
            if (userByUsername != null) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Trying to create user {} from email '{}' who already exist.", username,
                            email);
                }
                halt(409);
                return "";
            }

            String entityName = email;
            if (json.has("entity") && StringUtils.isNotBlank(json.getAsJsonPrimitive("entity").getAsString())) {
                entityName = json.getAsJsonPrimitive("entity").getAsString();
            }

            String password = new BigInteger(130, new SecureRandom()).toString(32);
            KeyPair keyPair = RSAUtils.generateRsaKeyPair();
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

            User user = new User(identifier, username, username, email, password,
                    RSAUtils.encodePublicKey((RSAPublicKey) keyPair.getPublic(), email));

            String entityId = null;
            SimpleCredential credential = extractCredential(request);
            if (credential != null) {
                User userRequester = userAuthenticator.authenticate(credential);
                if (userRequester != null) {
                    entityId = entityStore.getEntityIdOfUserId(userRequester.getIdentifier());
                }
            }
            if (entityId == null) {
                Entity entity = new Entity(entityName, user);
                entityId = entityStore.addEntity(entity);
            }
            entityStore.addUserToEntity(identifier, entityId);

            user = new User(identifier, entityId, username, username, email, password, user.getSshPublicKey());

            if (userStore.addUser(user)) {

                response.status(201);
                StringWriter sw = new StringWriter();
                RSAUtils.writeRsaPrivateKey(privateKey, sw);
                response.header("Location", "/user/" + user.getIdentifier());
                UserCreationDto userCreationDto = new UserCreationDto(user, sw.toString());

                if (emailSender != null) {
                    List<String> cc = null;
                    if (credential != null) {
                        User userRequester = userAuthenticator.authenticate(credential);
                        if (userRequester != null) {
                            cc = Collections.singletonList(userRequester.getEmail());
                        }
                    }
                    String content = "<h1>Welcome on Kodo Kojo</h1>\n"
                            + "<p>You will find all information which is bind to your account '"
                            + userCreationDto.getUsername() + "'.</p>\n" + "\n" + "<p>Password : <b>"
                            + userCreationDto.getPassword() + "</b></p>\n"
                            + "<p>Your SSH private key generated:\n" + "<br />\n"
                            + userCreationDto.getPrivateKey() + "\n" + "</p>\n"
                            + "<p>Your SSH public key generated:\n" + "<br />\n"
                            + userCreationDto.getSshPublicKey() + "\n" + "</p>";
                    emailSender.send(Collections.singletonList(userCreationDto.getEmail()), null, cc,
                            "User creation on Kodo Kojo " + userCreationDto.getName(), content, true);
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Mail with user data send to {}.", userCreationDto.getEmail());
                        if (LOGGER.isTraceEnabled()) {
                            LOGGER.trace("Email to {} content : \n {}", userCreationDto.getEmail(), content);
                        }
                    }
                }

                return userCreationDto;
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("The UserStore not abel to add following user {}.", user.toString());
            }
            halt(428);
            return "";
        } else {
            halt(412);
            return "";
        }
    }), jsonResponseTransformer);

    post(BASE_API + "/user", JSON_CONTENT_TYPE, (request, response) -> {
        String res = userStore.generateId();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Generate id : {}", res);
        }
        return res;
    });

    get(BASE_API + "/user", JSON_CONTENT_TYPE, (request, response) -> {
        SimpleCredential credential = extractCredential(request);
        if (credential != null) {
            User user = userStore.getUserByUsername(credential.getUsername());
            if (user == null) {
                halt(404);
                return "";
            }
            return getUserDto(user);
        }
        halt(401);
        return "";
    }, jsonResponseTransformer);

    get(BASE_API + "/user/:id", JSON_CONTENT_TYPE, (request, response) -> {
        SimpleCredential credential = extractCredential(request);
        String identifier = request.params(":id");
        User requestUser = userStore.getUserByUsername(credential.getUsername());
        User user = userStore.getUserByIdentifier(identifier);
        if (user != null) {
            if (user.getEntityIdentifier().equals(requestUser.getEntityIdentifier())) {
                if (!user.getUsername().equals(credential.getUsername())) {
                    user = new User(user.getIdentifier(), user.getName(), user.getUsername(), user.getEmail(),
                            "", user.getSshPublicKey());
                }
                return getUserDto(user);
            }
            halt(403, "You aren't in same entity.");
            return "";
        }
        halt(404);
        return "";
    }, jsonResponseTransformer);
}

From source file:br.com.ufjf.labredes.crypto.Cryptography.java

public static void geraChave() {
    try {//from  w  ww.j a v  a 2  s  . c  o m

        final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM_ASYM);
        keyGen.initialize(1024);
        final KeyPair key = keyGen.generateKeyPair();

        File chavePrivadaFileServer = new File(path, PATH_CHAVE_PRIVADA_SERVER);
        File chavePublicaFileServer = new File(path, PATH_CHAVE_PUBLICA_SERVER);

        // Cria os arquivos para armazenar a chave Privada e a chave Publica            
        if (chavePrivadaFileServer.getParentFile() != null) {
            chavePrivadaFileServer.getParentFile().mkdirs();
        }

        chavePrivadaFileServer.createNewFile();

        if (chavePublicaFileServer.getParentFile() != null) {
            chavePublicaFileServer.getParentFile().mkdirs();
        }

        chavePublicaFileServer.createNewFile();

        // Salva a Chave Pblica do servidor no arquivo
        ObjectOutputStream chavePublicaOSS = new ObjectOutputStream(
                new FileOutputStream(chavePublicaFileServer));
        chavePublicaOSS.writeObject(key.getPublic());
        chavePublicaOSS.close();

        // Salva a Chave Privada do servidor no arquivo
        ObjectOutputStream chavePrivadaOSS = new ObjectOutputStream(
                new FileOutputStream(chavePrivadaFileServer));
        chavePrivadaOSS.writeObject(key.getPrivate());
        chavePrivadaOSS.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.vmware.certificate.Client.java

private String getPEMEncodedKey(KeyPair Keys) {
    byte[] privBytes = Keys.getPrivate().getEncoded();
    String encoded = new String(Base64.encodeBase64(privBytes));
    StringBuffer pemencode = new StringBuffer();
    for (int x = 0; x < encoded.length(); x++) {

        if ((x > 0) && (x % 64 == 0)) {
            pemencode.append("\n");
            pemencode.append(encoded.charAt(x));
        } else {/*from   www  . jav a2  s  .  c  o  m*/
            pemencode.append(encoded.charAt(x));

        }
    }
    return "-----BEGIN PRIVATE KEY-----\n" + pemencode.toString() + "\n" + "-----END PRIVATE KEY-----";
}

From source file:com.jonbanjo.cupsprint.CertificateActivity.java

public void doimport(View view) {
    try {/*from w  w w  .j  a  v a2 s  . c  om*/
        String url = "https://" + host.getText().toString() + ":" + port.getText().toString();
        importButton.setEnabled(false);
        new importer().execute(url).get(3000, TimeUnit.MILLISECONDS);
    } catch (Exception e) {

    } finally {
        importButton.setEnabled(true);
    }
    if (certChain == null) {
        return;
    }

    for (X509Certificate cert : certChain) {
        try {
            cert.checkValidity();
        } catch (Exception e) {
            showToast(e.toString());
            return;
        }

    }
    String certString = certChain[0].toString();
    final String alias = certChain[0].getSubjectX500Principal().getName();
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Add Certificate?").setMessage(certString)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    try {
                        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
                        keyPairGenerator.initialize(1024);
                        KeyPair keyPair = keyPairGenerator.generateKeyPair();
                        PrivateKey privateKey = keyPair.getPrivate();
                        trustStore.setKeyEntry(alias, privateKey, JfSSLScheme.password.toCharArray(),
                                certChain);
                        FileOutputStream outputStream = openFileOutput(JfSSLScheme.trustfile, MODE_PRIVATE);
                        trustStore.store(outputStream, JfSSLScheme.password.toCharArray());
                        outputStream.flush();
                        outputStream.close();
                        certListAdaptor.add(alias);
                    } catch (Exception e) {
                        System.out.println(e.toString());
                        return;
                    }
                }
            }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });
    AlertDialog dialog = builder.create();
    dialog.show();

}

From source file:com.aqnote.shared.encrypt.cert.gen.BCCertGenerator.java

public X509Certificate createClass1EndCert(X500Name sdn, PublicKey pubKey, KeyPair pKeyPair) throws Exception {

    PublicKey pPubKey = pKeyPair.getPublic();
    PrivateKey pPrivKey = pKeyPair.getPrivate();

    X500Name issuer = X500NameUtil.createClass1RootPrincipal();
    BigInteger sno = BigInteger.valueOf(System.currentTimeMillis());
    Date nb = new Date(System.currentTimeMillis() - HALF_DAY);
    Date na = new Date(nb.getTime() + FIVE_YEAR);

    X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, sno, nb, na, sdn, pubKey);

    addSubjectKID(certBuilder, pubKey);//from  ww  w  . j  a v a2  s. c o  m
    addAuthorityKID(certBuilder, pPubKey);
    certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(BASE_EKU));
    certBuilder.addExtension(Extension.keyUsage, false, new KeyUsage(END_KEY_USAGE));

    X509Certificate certificate = signCert(certBuilder, pPrivKey);
    certificate.checkValidity(new Date());
    certificate.verify(pPubKey);

    setPKCS9Info(certificate);

    return certificate;
}

From source file:com.aqnote.shared.encrypt.cert.gen.BCCertGenerator.java

public X509Certificate createRootCaCert(final KeyPair keyPair) throws Exception {

    PublicKey pubKey = keyPair.getPublic();
    PrivateKey privKey = keyPair.getPrivate();

    X500Name idn = X500NameUtil.createRootPrincipal();
    BigInteger sno = BigInteger.valueOf(1);
    Date nb = new Date(System.currentTimeMillis() - ONE_DAY);
    Date na = new Date(nb.getTime() + TWENTY_YEAR);

    X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(idn, sno, nb, na, idn, pubKey);

    addSubjectKID(certBuilder, pubKey);//w w  w .ja  v  a  2  s  . com
    addAuthorityKID(certBuilder, pubKey);
    addCRLDistributionPoints(certBuilder);
    addAuthorityInfoAccess(certBuilder);
    certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(Boolean.TRUE));

    X509Certificate certificate = signCert(certBuilder, privKey);
    certificate.checkValidity(new Date());
    certificate.verify(pubKey);

    setPKCS9Info(certificate);

    return certificate;
}

From source file:com.streamsets.pipeline.lib.remote.FTPAndSSHDUnitTest.java

protected File generateCertificateKeystore(KeyStoreType keystoreType) throws Exception {
    KeyPair keyPair = generateKeyPair();
    X509Certificate cert = generateCertificate(keyPair);

    KeyStore keyStore = KeyStore.getInstance(keystoreType.getJavaValue());
    keyStore.load(null, KEYSTORE_PASSWORD.toCharArray());
    keyStore.setKeyEntry("foo", keyPair.getPrivate(), KEYSTORE_PASSWORD.toCharArray(),
            new Certificate[] { cert });
    File keystoreFile = keystoreFolder.newFile("keystore " + System.currentTimeMillis() + ".jks");
    try (FileOutputStream fos = new FileOutputStream(keystoreFile)) {
        keyStore.store(fos, KEYSTORE_PASSWORD.toCharArray());
    }//ww  w .  j  ava  2s . c  o  m
    return keystoreFile;
}