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:edu.ucsb.eucalyptus.keys.AbstractKeyStore.java

public KeyPair getKeyPair(String alias, String password) throws GeneralSecurityException {
    Certificate cert = this.keyStore.getCertificate(alias);
    PrivateKey privateKey = (PrivateKey) this.keyStore.getKey(alias, password.toCharArray());
    KeyPair kp = new KeyPair(cert.getPublicKey(), privateKey);
    return kp;// w ww.  ja v a  2  s.c  om
}

From source file:net.padlocksoftware.padlock.KeyManager.java

/**
 * Import a Padlock 2.x (DSA based) KeyPair from an InputStream.  The stream is
 * assumed to have been previously exported in a supported format using the
 * exportKeyPair methods./*w w w.ja  v  a 2s.  com*/
 * @param stream The KeyPair stream to import.
 * @return The DSA KeyPair contained in the specified file.
 * @throws java.io.IOException If file is missing or contain invalid data.
 * @since 2.0
 */
public static KeyPair importKeyPair(InputStream stream) throws IOException {
    if (stream == null)
        throw new IllegalArgumentException("Stream cannot be null");

    KeyPair pair = null;
    Properties p = new Properties();
    p.load(stream);
    stream.close();
    String pri = p.getProperty("private");
    String pub = p.getProperty("public");

    if (pri == null || pub == null) {
        throw new IOException("Stream data is invalid");
    }

    // Load the keys
    try {

        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Hex.decodeHex(pri.toCharArray()));
        KeyFactory keyFactory = KeyFactory.getInstance("DSA");
        PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

        X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(Hex.decodeHex(pub.toCharArray()));
        PublicKey publicKey = keyFactory.generatePublic(pubSpec);

        pair = new KeyPair(publicKey, privateKey);
    } catch (Exception e) {
        throw new RuntimeException("Invalid stream: " + e.getMessage());
    }

    return pair;
}

From source file:be.e_contract.mycarenet.common.SessionKey.java

/**
 * Loader constructor. Loads an existing MyCareNet session key.
 * //  w w  w. j a va2 s.com
 * @param encodedPrivateKey
 * @param encodedPublicKey
 * @param encodedCertificate
 * @param notBefore
 * @param notAfter
 */
public SessionKey(byte[] encodedPrivateKey, byte[] encodedPublicKey, byte[] encodedCertificate, Date notBefore,
        Date notAfter) {
    this.notBefore = notBefore;
    this.notAfter = notAfter;

    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    KeyFactory keyFactory;
    try {
        keyFactory = KeyFactory.getInstance("RSA");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("RSA", e);
    }
    PublicKey publicKey;
    try {
        publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException("invalid public key: " + e.getMessage(), e);
    }

    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey;
    try {
        privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException("invalid private key: " + e.getMessage(), e);
    }

    this.keyPair = new KeyPair(publicKey, privateKey);

    CertificateFactory certificateFactory;
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    }
    try {
        this.certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    } catch (CertificateException e) {
        throw new RuntimeException("certificate decoding error: " + e.getMessage(), e);
    }
}

From source file:mamo.vanillaVotifier.JsonConfig.java

@Override
public synchronized void load() throws IOException, InvalidKeySpecException {
    if (!configFile.exists()) {
        BufferedInputStream in = new BufferedInputStream(JsonConfig.class.getResourceAsStream("config.json"));
        StringBuilder stringBuilder = new StringBuilder();
        int i;/* w w w. j  a  va 2  s .  c om*/
        while ((i = in.read()) != -1) {
            stringBuilder.append((char) i);
        }
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(configFile));
        for (char c : stringBuilder.toString()
                .replaceAll("\\u000D\\u000A|[\\u000A\\u000B\\u000C\\u000D\\u0085\\u2028\\u2029]",
                        System.getProperty("line.separator"))
                .toCharArray()) {
            out.write((int) c);
        }
        out.flush();
        out.close();
    }
    BufferedInputStream in = new BufferedInputStream(JsonConfig.class.getResourceAsStream("config.json"));
    JSONObject defaultConfig = new JSONObject(new JSONTokener(in));
    in.close();
    JSONObject config = new JSONObject(
            new JSONTokener(new BufferedInputStream(new FileInputStream(configFile))));
    boolean save = JsonUtils.merge(defaultConfig, config);
    configVersion = config.getInt("config-version");
    if (configVersion == 2) {
        v2ToV3(config);
        configVersion = 3;
        save = true;
    }
    logFile = new File(config.getString("log-file"));
    inetSocketAddress = new InetSocketAddress(config.getString("ip"), config.getInt("port"));
    publicKeyFile = new File(config.getJSONObject("key-pair-files").getString("public"));
    privateKeyFile = new File(config.getJSONObject("key-pair-files").getString("private"));
    if (!publicKeyFile.exists() && !privateKeyFile.exists()) {
        KeyPair keyPair = RsaUtils.genKeyPair();
        PemWriter publicPemWriter = new PemWriter(new BufferedWriter(new FileWriter(publicKeyFile)));
        publicPemWriter.writeObject(new PemObject("PUBLIC KEY", keyPair.getPublic().getEncoded()));
        publicPemWriter.flush();
        publicPemWriter.close();
        PemWriter privatePemWriter = new PemWriter(new BufferedWriter(new FileWriter(privateKeyFile)));
        privatePemWriter.writeObject(new PemObject("RSA PRIVATE KEY", keyPair.getPrivate().getEncoded()));
        privatePemWriter.flush();
        privatePemWriter.close();
    }
    if (!publicKeyFile.exists()) {
        throw new PublicKeyFileNotFoundException();
    }
    if (!privateKeyFile.exists()) {
        throw new PrivateKeyFileNotFoundException();
    }
    PemReader publicKeyPemReader = new PemReader(new BufferedReader(new FileReader(publicKeyFile)));
    PemReader privateKeyPemReader = new PemReader(new BufferedReader(new FileReader(privateKeyFile)));
    PemObject publicPemObject = publicKeyPemReader.readPemObject();
    if (publicPemObject == null) {
        throw new InvalidPublicKeyFileException();
    }
    PemObject privatePemObject = privateKeyPemReader.readPemObject();
    if (privatePemObject == null) {
        throw new InvalidPrivateKeyFileException();
    }
    keyPair = new KeyPair(RsaUtils.bytesToPublicKey(publicPemObject.getContent()),
            RsaUtils.bytesToPrivateKey(privatePemObject.getContent()));
    publicKeyPemReader.close();
    privateKeyPemReader.close();
    rconConfigs = new ArrayList<RconConfig>();
    for (int i = 0; i < config.getJSONArray("rcon-list").length(); i++) {
        JSONObject jsonObject = config.getJSONArray("rcon-list").getJSONObject(i);
        RconConfig rconConfig = new RconConfig(
                new InetSocketAddress(jsonObject.getString("ip"), jsonObject.getInt("port")),
                jsonObject.getString("password"));
        for (int j = 0; j < jsonObject.getJSONArray("commands").length(); j++) {
            rconConfig.getCommands().add(jsonObject.getJSONArray("commands").getString(j));
        }
        rconConfigs.add(rconConfig);
    }
    loaded = true;
    if (save) {
        save();
    }
}

From source file:com.atlassian.jira.security.auth.trustedapps.DefaultCurrentApplicationStore.java

@Override
public void setCurrentApplication(String applicationId, String publicKey, String privateKey) {
    Assertions.notBlank("applicationId cannot be blank.", applicationId);
    Assertions.notNull("publicKey cannot be null.", publicKey);
    Assertions.notNull("privateKey cannot be null.", privateKey);

    PublicKey publicKeyObj = KeyFactory.getPublicKey(publicKey);
    if (publicKeyObj instanceof KeyFactory.InvalidPublicKey) {
        throw new IllegalArgumentException("publicKey is not a valid public key.",
                ((KeyFactory.InvalidKey) publicKeyObj).getCause());
    }/*from w w  w.j  a  v a 2 s  . c  o  m*/

    PrivateKey privateKeyObj = KeyFactory.getPrivateKey(privateKey);
    if (privateKeyObj instanceof KeyFactory.InvalidPrivateKey) {
        throw new IllegalArgumentException("privateKey is not a valid private key.",
                ((KeyFactory.InvalidKey) privateKeyObj).getCause());
    }

    setCurrentApplication(applicationId, new KeyPair(publicKeyObj, privateKeyObj));
}

From source file:com.quest.keycloak.protocol.wsfed.WSFedLoginProtocol.java

@Override
public Response authenticated(UserSessionModel userSession, ClientSessionCode accessCode) {
    ClientSessionModel clientSession = accessCode.getClientSession();
    ClientModel client = clientSession.getClient();
    String context = clientSession.getNote(WSFedConstants.WSFED_CONTEXT);
    userSession.setNote(WSFedConstants.WSFED_REALM, client.getClientId());

    try {/*from ww w. ja  v a 2  s.  c o  m*/
        RequestSecurityTokenResponseBuilder builder = new RequestSecurityTokenResponseBuilder();
        KeyManager keyManager = session.keys();
        KeyManager.ActiveRsaKey activeKey = keyManager.getActiveRsaKey(realm);

        builder.setRealm(clientSession.getClient().getClientId()).setAction(WSFedConstants.WSFED_SIGNIN_ACTION)
                .setDestination(clientSession.getRedirectUri()).setContext(context)
                .setTokenExpiration(realm.getAccessTokenLifespan())
                .setRequestIssuer(clientSession.getClient().getClientId())
                .setSigningKeyPair(new KeyPair(activeKey.getPublicKey(), activeKey.getPrivateKey()))
                .setSigningCertificate(activeKey.getCertificate()).setSigningKeyPairId(activeKey.getKid());

        if (useJwt(client)) {
            WSFedOIDCAccessTokenBuilder oidcBuilder = new WSFedOIDCAccessTokenBuilder();
            oidcBuilder.setSession(session).setUserSession(userSession).setAccessCode(accessCode)
                    .setClient(client).setClientSession(clientSession).setRealm(realm)
                    .setX5tIncluded(isX5tIncluded(client));

            String token = oidcBuilder.build();
            builder.setJwt(token);
        } else {
            //if client wants SAML
            WSFedSAML2AssertionTypeBuilder samlBuilder = new WSFedSAML2AssertionTypeBuilder();
            samlBuilder.setRealm(realm).setUriInfo(uriInfo).setAccessCode(accessCode)
                    .setClientSession(clientSession).setUserSession(userSession).setSession(session);

            AssertionType token = samlBuilder.build();
            builder.setSamlToken(token);
        }

        return builder.buildResponse();
    } catch (Exception e) {
        logger.error("failed", e);
        return ErrorPage.error(session, Messages.FAILED_TO_PROCESS_RESPONSE);
    }
}

From source file:org.ejbca.core.model.ca.catoken.BaseCAToken.java

/**
 * @param keyStore/*  w w w. j  a va2s .  co  m*/
 * @param authCode
 * @throws Exception
 */
protected void setKeys(KeyStore keyStore, String authCode) throws Exception {
    this.mKeys = null;
    final String keyAliases[] = this.keyStrings.getAllStrings();
    final Map<String, KeyPair> mTmp = new Hashtable<String, KeyPair>();
    for (int i = 0; i < keyAliases.length; i++) {
        PrivateKey privateK = (PrivateKey) keyStore.getKey(keyAliases[i],
                (authCode != null && authCode.length() > 0) ? authCode.toCharArray() : null);
        if (privateK == null) {
            log.error(intres.getLocalizedMessage("catoken.noprivate", keyAliases[i]));
            if (log.isDebugEnabled()) {
                for (int j = 0; j < keyAliases.length; j++) {
                    log.debug("Existing alias: " + keyAliases[j]);
                }
            }
        } else {
            PublicKey publicK = readPublicKey(keyStore, keyAliases[i]);
            if (publicK != null) {
                KeyPair keyPair = new KeyPair(publicK, privateK);
                mTmp.put(keyAliases[i], keyPair);
            }
        }
    }
    for (int i = 0; i < keyAliases.length; i++) {
        KeyPair pair = mTmp.get(keyAliases[i]);
        if (log.isDebugEnabled()) {
            log.debug("Testing keys with alias " + keyAliases[i]);
        }
        if (pair == null) {
            log.info("No keys with alias " + keyAliases[i] + " exists.");
        } else {
            testKey(pair); // Test signing for the KeyPair (this could theoretically fail if singing is not allowed by the provider for this key)
            if (log.isDebugEnabled()) {
                log.debug("Key with alias " + keyAliases[i] + " tested.");
            }
        }
    }
    this.mKeys = mTmp;
    if (getCATokenStatus() != ICAToken.STATUS_ACTIVE) {
        throw new Exception("Activation test failed");
    }
}

From source file:org.apache.nifi.toolkit.tls.standalone.TlsToolkitStandalone.java

public void createNifiKeystoresAndTrustStores(StandaloneConfig standaloneConfig)
        throws GeneralSecurityException, IOException {
    File baseDir = standaloneConfig.getBaseDir();
    if (!baseDir.exists() && !baseDir.mkdirs()) {
        throw new IOException(baseDir + " doesn't exist and unable to create it.");
    }/*from www. j  a va2 s.c o  m*/

    if (!baseDir.isDirectory()) {
        throw new IOException("Expected directory to output to");
    }

    String signingAlgorithm = standaloneConfig.getSigningAlgorithm();
    int days = standaloneConfig.getDays();
    String keyPairAlgorithm = standaloneConfig.getKeyPairAlgorithm();
    int keySize = standaloneConfig.getKeySize();

    File nifiCert = new File(baseDir, NIFI_CERT + ".pem");
    File nifiKey = new File(baseDir, NIFI_KEY + ".key");

    X509Certificate certificate;
    KeyPair caKeyPair;

    if (logger.isInfoEnabled()) {
        logger.info("Running standalone certificate generation with output directory " + baseDir);
    }
    if (nifiCert.exists()) {
        if (!nifiKey.exists()) {
            throw new IOException(nifiCert + " exists already, but " + nifiKey
                    + " does not, we need both certificate and key to continue with an existing CA.");
        }
        try (FileReader pemEncodedCertificate = new FileReader(nifiCert)) {
            certificate = TlsHelper.parseCertificate(pemEncodedCertificate);
        }
        try (FileReader pemEncodedKeyPair = new FileReader(nifiKey)) {
            caKeyPair = TlsHelper.parseKeyPair(pemEncodedKeyPair);
        }

        certificate.verify(caKeyPair.getPublic());
        if (!caKeyPair.getPublic().equals(certificate.getPublicKey())) {
            throw new IOException("Expected " + nifiKey + " to correspond to CA certificate at " + nifiCert);
        }

        if (logger.isInfoEnabled()) {
            logger.info("Using existing CA certificate " + nifiCert + " and key " + nifiKey);
        }
    } else if (nifiKey.exists()) {
        throw new IOException(nifiKey + " exists already, but " + nifiCert
                + " does not, we need both certificate and key to continue with an existing CA.");
    } else {
        TlsCertificateAuthorityManager tlsCertificateAuthorityManager = new TlsCertificateAuthorityManager(
                standaloneConfig);
        KeyStore.PrivateKeyEntry privateKeyEntry = tlsCertificateAuthorityManager
                .getOrGenerateCertificateAuthority();
        certificate = (X509Certificate) privateKeyEntry.getCertificateChain()[0];
        caKeyPair = new KeyPair(certificate.getPublicKey(), privateKeyEntry.getPrivateKey());

        try (PemWriter pemWriter = new PemWriter(
                new OutputStreamWriter(outputStreamFactory.create(nifiCert)))) {
            pemWriter.writeObject(new JcaMiscPEMGenerator(certificate));
        }

        try (PemWriter pemWriter = new PemWriter(new OutputStreamWriter(outputStreamFactory.create(nifiKey)))) {
            pemWriter.writeObject(new JcaMiscPEMGenerator(caKeyPair));
        }

        if (logger.isInfoEnabled()) {
            logger.info("Generated new CA certificate " + nifiCert + " and key " + nifiKey);
        }
    }

    NiFiPropertiesWriterFactory niFiPropertiesWriterFactory = standaloneConfig.getNiFiPropertiesWriterFactory();
    boolean overwrite = standaloneConfig.isOverwrite();

    List<InstanceDefinition> instanceDefinitions = standaloneConfig.getInstanceDefinitions();
    if (instanceDefinitions.isEmpty() && logger.isInfoEnabled()) {
        logger.info("No " + TlsToolkitStandaloneCommandLine.HOSTNAMES_ARG
                + " specified, not generating any host certificates or configuration.");
    }
    for (InstanceDefinition instanceDefinition : instanceDefinitions) {
        String hostname = instanceDefinition.getHostname();
        File hostDir;
        int hostIdentifierNumber = instanceDefinition.getInstanceIdentifier().getNumber();
        if (hostIdentifierNumber == 1) {
            hostDir = new File(baseDir, hostname);
        } else {
            hostDir = new File(baseDir, hostname + "_" + hostIdentifierNumber);
        }

        TlsClientConfig tlsClientConfig = new TlsClientConfig(standaloneConfig);
        File keystore = new File(hostDir, "keystore." + tlsClientConfig.getKeyStoreType().toLowerCase());
        File truststore = new File(hostDir, "truststore." + tlsClientConfig.getTrustStoreType().toLowerCase());

        if (hostDir.exists()) {
            if (!hostDir.isDirectory()) {
                throw new IOException(hostDir + " exists but is not a directory.");
            } else if (overwrite) {
                if (logger.isInfoEnabled()) {
                    logger.info("Overwriting any existing ssl configuration in " + hostDir);
                }
                keystore.delete();
                if (keystore.exists()) {
                    throw new IOException("Keystore " + keystore + " already exists and couldn't be deleted.");
                }
                truststore.delete();
                if (truststore.exists()) {
                    throw new IOException(
                            "Truststore " + truststore + " already exists and couldn't be deleted.");
                }
            } else {
                throw new IOException(hostDir + " exists and overwrite is not set.");
            }
        } else if (!hostDir.mkdirs()) {
            throw new IOException("Unable to make directory: " + hostDir.getAbsolutePath());
        } else if (logger.isInfoEnabled()) {
            logger.info("Writing new ssl configuration to " + hostDir);
        }

        tlsClientConfig.setKeyStore(keystore.getAbsolutePath());
        tlsClientConfig.setKeyStorePassword(instanceDefinition.getKeyStorePassword());
        tlsClientConfig.setKeyPassword(instanceDefinition.getKeyPassword());
        tlsClientConfig.setTrustStore(truststore.getAbsolutePath());
        tlsClientConfig.setTrustStorePassword(instanceDefinition.getTrustStorePassword());
        TlsClientManager tlsClientManager = new TlsClientManager(tlsClientConfig);
        KeyPair keyPair = TlsHelper.generateKeyPair(keyPairAlgorithm, keySize);
        Extensions sanDnsExtensions = StringUtils.isBlank(tlsClientConfig.getDomainAlternativeNames()) ? null
                : TlsHelper.createDomainAlternativeNamesExtensions(tlsClientConfig.getDomainAlternativeNames());
        tlsClientManager.addPrivateKeyToKeyStore(keyPair, NIFI_KEY,
                CertificateUtils.generateIssuedCertificate(tlsClientConfig.calcDefaultDn(hostname),
                        keyPair.getPublic(), sanDnsExtensions, certificate, caKeyPair, signingAlgorithm, days),
                certificate);
        tlsClientManager.setCertificateEntry(NIFI_CERT, certificate);
        tlsClientManager.addClientConfigurationWriter(
                new NifiPropertiesTlsClientConfigWriter(niFiPropertiesWriterFactory,
                        new File(hostDir, "nifi.properties"), hostname, instanceDefinition.getNumber()));
        tlsClientManager.write(outputStreamFactory);
        if (logger.isInfoEnabled()) {
            logger.info("Successfully generated TLS configuration for " + hostname + " " + hostIdentifierNumber
                    + " in " + hostDir);
        }
    }

    List<String> clientDns = standaloneConfig.getClientDns();
    if (standaloneConfig.getClientDns().isEmpty() && logger.isInfoEnabled()) {
        logger.info("No " + TlsToolkitStandaloneCommandLine.CLIENT_CERT_DN_ARG
                + " specified, not generating any client certificates.");
    }

    List<String> clientPasswords = standaloneConfig.getClientPasswords();
    for (int i = 0; i < clientDns.size(); i++) {
        String reorderedDn = CertificateUtils.reorderDn(clientDns.get(i));
        String clientDnFile = getClientDnFile(reorderedDn);
        File clientCertFile = new File(baseDir, clientDnFile + ".p12");

        if (clientCertFile.exists()) {
            if (overwrite) {
                if (logger.isInfoEnabled()) {
                    logger.info("Overwriting existing client cert " + clientCertFile);
                }
            } else {
                throw new IOException(clientCertFile + " exists and overwrite is not set.");
            }
        } else if (logger.isInfoEnabled()) {
            logger.info("Generating new client certificate " + clientCertFile);
        }
        KeyPair keyPair = TlsHelper.generateKeyPair(keyPairAlgorithm, keySize);
        X509Certificate clientCert = CertificateUtils.generateIssuedCertificate(reorderedDn,
                keyPair.getPublic(), null, certificate, caKeyPair, signingAlgorithm, days);
        KeyStore keyStore = KeyStoreUtils.getKeyStore(KeystoreType.PKCS12.toString());
        keyStore.load(null, null);
        keyStore.setKeyEntry(NIFI_KEY, keyPair.getPrivate(), null,
                new Certificate[] { clientCert, certificate });
        String password = TlsHelper.writeKeyStore(keyStore, outputStreamFactory, clientCertFile,
                clientPasswords.get(i), standaloneConfig.isClientPasswordsGenerated());

        try (FileWriter fileWriter = new FileWriter(new File(baseDir, clientDnFile + ".password"))) {
            fileWriter.write(password);
        }

        if (logger.isInfoEnabled()) {
            logger.info("Successfully generated client certificate " + clientCertFile);
        }
    }

    if (logger.isInfoEnabled()) {
        logger.info("tls-toolkit standalone completed successfully");
    }
}

From source file:com.kuzumeji.platform.standard.SecurityService.java

/**
 * RSA??/*from   ww w . j a  va2 s  .  c o  m*/
 * <dl>
 * <dt>?
 * <dd>RSA??
 * </dl>
 * @param name RSA???
 * @return RSA?
 */
public KeyPair loadKeyPair(final String name) {
    try {
        final Properties property = new PropertyService(PROPERTY_NAME).getProperty();
        final KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGO_NAME);
        final RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(new X509EncodedKeySpec(
                Hex.decodeHex(property.getProperty(String.format(KEY_PUBLIC_ENCODED, name)).toCharArray())));
        final RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(
                Hex.decodeHex(property.getProperty(String.format(KEY_PRIVATE_ENCODED, name)).toCharArray())));
        return new KeyPair(publicKey, privateKey);
    } catch (final IOException | DecoderException | InvalidKeySpecException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.atlassian.jira.security.auth.trustedapps.DefaultCurrentApplicationStore.java

private Pair<KeyPair, CurrentApplication> getOrCreateCurrentApplication() {
    accessLock.lock();/*from ww w.  j  a v a2 s  .c  om*/
    final KeyPair keyPair;
    String uid;
    try {
        final String privateKeyData = applicationProperties.getText(Keys.PRIVATE_KEY_DATA);
        final String publicKeyData = applicationProperties.getText(Keys.PUBLIC_KEY_DATA);

        if (isBlank(privateKeyData)) {
            keyPair = generateNewKeyPair();
            applicationProperties.setText(Keys.PRIVATE_KEY_DATA, KeyFactory.encode(keyPair.getPrivate()));
            applicationProperties.setText(Keys.PUBLIC_KEY_DATA, KeyFactory.encode(keyPair.getPublic()));
        } else {
            PrivateKey privateKey = KeyFactory.getPrivateKey(privateKeyData);
            PublicKey publicKey = KeyFactory.getPublicKey(publicKeyData);

            keyPair = new KeyPair(publicKey, privateKey);
        }

        uid = applicationProperties.getString(Keys.UID);
        if (isBlank(uid)) {
            uid = new UIDGenerator().generateUID(licenseService);
            applicationProperties.setString(Keys.UID, uid);
        }
    } finally {
        accessLock.unlock();
    }
    CurrentApplication application = new DefaultCurrentApplication(keyPair.getPublic(), keyPair.getPrivate(),
            uid);
    return Pair.of(keyPair, application);
}