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:org.umit.icm.mobile.utils.ProfilerRun.java

private static void profileRSAPrivateDecrypt() {
    Profiler profiler = new Profiler();
    profiler.runProfiler(new TaskInterface() {
        public void task() {
            try {
                KeyPair keyPair = RSACrypto.generateKey();
                String cipherText = RSACrypto.encryptPrivate(keyPair.getPrivate(), "This is a test string");
                RSACrypto.decryptPublic(keyPair.getPublic(), cipherText);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();/*from  www .  j  a  v  a  2 s  .  c  o m*/
            }
        }

        public String taskName() {
            return "RSA Private Decryption";
        }
    });
}

From source file:org.artifactory.security.crypto.CryptoHelper.java

/**
 * Creates a master encryption key file. Throws an exception if the key file already exists of on any failure with
 * file or key creation.//ww  w  .  jav a 2 s.c o m
 */
public static void createMasterKeyFile() {
    File keyFile = getMasterKeyFile();
    if (keyFile.exists()) {
        throw new IllegalStateException(
                "Cannot create new master key file if it already exists at " + keyFile.getAbsolutePath());
    }
    log.info("Creating master encryption key at {}", keyFile.getAbsolutePath());
    KeyPair keyPair = generateKeyPair();
    try {
        File securityFolder = keyFile.getParentFile();
        if (!securityFolder.exists()) {
            if (!securityFolder.mkdirs()) {
                throw new RuntimeException("Could not create the folder containing the key file "
                        + securityFolder.getAbsolutePath());
            }
            setPermissionsOnSecurityFolder(securityFolder);
        }

        checkPermissionsOnSecurityFolder(securityFolder);
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(keyFile))) {
            writer.write(convertToString(keyPair.getPrivate().getEncoded(), true));
            writer.newLine();
            writer.write(convertToString(keyPair.getPublic().getEncoded(), true));
            writer.newLine();
        }
    } catch (IOException e) {
        throw new RuntimeException("Could not write the key into " + keyFile.getAbsolutePath(), e);
    }
}

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static void add(File keystore, KeyPair pair, String domain) {
    if (keystore == null) {
        throw new IllegalArgumentException("Key Store file should not be null.");
    }/*from w  w  w  . j av a2s . com*/

    try {
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        if (keystore.exists()) {
            FileInputStream stream = new FileInputStream(keystore);
            ks.load(stream, SECRET);
            IOUtils.closeQuietly(stream);
        } else {
            ks.load(null, SECRET);
        }

        if (!ks.containsAlias(ALIAS)) {
            X509Certificate certificate = generateCertificate(domain, 1, pair);

            ks.setKeyEntry(ALIAS, pair.getPrivate(), SECRET, new Certificate[] { certificate });

            FileOutputStream stream = new FileOutputStream(keystore);
            ks.store(stream, SECRET);
            IOUtils.closeQuietly(stream);
        }
    } catch (Throwable th) {
        logger.error("Failed to initialize key store");
        throw new OpenFlameRuntimeException(th.getMessage(), th);
    }
}

From source file:org.wso2.emm.agent.utils.CommonUtils.java

/**
 * Generates keys, CSR and certificates for the devices.
 * @param context - Application context.
 * @param listener - DeviceCertCreationListener which provide device .
 *///  www  . j  a  v a 2  s.c o  m
public static void generateDeviceCertificate(final Context context, final DeviceCertCreationListener listener)
        throws AndroidAgentException {

    if (context.getFileStreamPath(Constants.DEVICE_CERTIFCATE_NAME).exists()) {
        try {
            listener.onDeviceCertCreated(
                    new BufferedInputStream(context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
    } else {

        try {
            ServerConfig utils = new ServerConfig();
            final KeyPair deviceKeyPair = KeyPairGenerator.getInstance(Constants.DEVICE_KEY_TYPE)
                    .generateKeyPair();
            X500Principal subject = new X500Principal(Constants.DEVICE_CSR_INFO);
            PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Constants.DEVICE_KEY_ALGO, subject,
                    deviceKeyPair.getPublic(), null, deviceKeyPair.getPrivate());

            EndPointInfo endPointInfo = new EndPointInfo();
            endPointInfo.setHttpMethod(org.wso2.emm.agent.proxy.utils.Constants.HTTP_METHODS.POST);
            endPointInfo.setEndPoint(utils.getAPIServerURL(context) + Constants.SCEP_ENDPOINT);
            endPointInfo.setRequestParams(Base64.encodeToString(csr.getEncoded(), Base64.DEFAULT));

            new APIController().invokeAPI(endPointInfo, new APIResultCallBack() {
                @Override
                public void onReceiveAPIResult(Map<String, String> result, int requestCode) {
                    try {
                        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                        InputStream in = new ByteArrayInputStream(
                                Base64.decode(result.get("response"), Base64.DEFAULT));
                        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        KeyStore keyStore = KeyStore.getInstance("PKCS12");
                        keyStore.load(null);
                        keyStore.setKeyEntry(Constants.DEVICE_CERTIFCATE_ALIAS,
                                (Key) deviceKeyPair.getPrivate(),
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray(),
                                new java.security.cert.Certificate[] { cert });
                        keyStore.store(byteArrayOutputStream,
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray());
                        FileOutputStream outputStream = context.openFileOutput(Constants.DEVICE_CERTIFCATE_NAME,
                                Context.MODE_PRIVATE);
                        outputStream.write(byteArrayOutputStream.toByteArray());
                        byteArrayOutputStream.close();
                        outputStream.close();
                        try {
                            listener.onDeviceCertCreated(new BufferedInputStream(
                                    context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
                        } catch (FileNotFoundException e) {
                            Log.e(TAG, e.getMessage());
                        }
                    } catch (CertificateException e) {
                        Log.e(TAG, e.getMessage());
                    } catch (KeyStoreException e) {
                        e.printStackTrace();
                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }, Constants.SCEP_REQUEST_CODE, context, true);

        } catch (NoSuchAlgorithmException e) {
            throw new AndroidAgentException("No algorithm for key generation", e);
        } catch (SignatureException e) {
            throw new AndroidAgentException("Invalid Signature", e);
        } catch (NoSuchProviderException e) {
            throw new AndroidAgentException("Invalid provider", e);
        } catch (InvalidKeyException e) {
            throw new AndroidAgentException("Invalid key", e);
        }

    }

}

From source file:net.nicholaswilliams.java.licensing.TestLicenseManager.java

@BeforeClass
public static void setUpClass() throws Exception {
    TestLicenseManager.control = EasyMock.createStrictControl();

    TestLicenseManager.licenseProvider = TestLicenseManager.control.createMock(LicenseProvider.class);
    TestLicenseManager.publicKeyPasswordProvider = TestLicenseManager.control
            .createMock(PasswordProvider.class);
    TestLicenseManager.licensePasswordProvider = TestLicenseManager.control.createMock(PasswordProvider.class);
    TestLicenseManager.keyDataProvider = TestLicenseManager.control.createMock(PublicKeyDataProvider.class);
    TestLicenseManager.licenseValidator = TestLicenseManager.control.createMock(LicenseValidator.class);

    try {/*from   w w  w .jav  a2s  . co m*/
        LicenseManager.getInstance();
        fail("Expected java.lang.IllegalArgumentException, got no exception.");
    } catch (IllegalArgumentException ignore) {
    }

    LicenseManagerProperties.setLicenseProvider(TestLicenseManager.licenseProvider);

    try {
        LicenseManager.getInstance();
        fail("Expected java.lang.IllegalArgumentException, got no exception.");
    } catch (IllegalArgumentException ignore) {
    }

    LicenseManagerProperties.setPublicKeyDataProvider(TestLicenseManager.keyDataProvider);

    try {
        LicenseManager.getInstance();
        fail("Expected java.lang.IllegalArgumentException, got no exception.");
    } catch (IllegalArgumentException ignore) {
    }

    LicenseManagerProperties.setPublicKeyPasswordProvider(TestLicenseManager.publicKeyPasswordProvider);
    LicenseManagerProperties.setLicensePasswordProvider(TestLicenseManager.licensePasswordProvider);
    LicenseManagerProperties.setLicenseValidator(TestLicenseManager.licenseValidator);
    LicenseManagerProperties.setCacheTimeInMinutes(0);

    LicenseManager.getInstance();

    KeyPair keyPair = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair();

    TestLicenseManager.privateKey = keyPair.getPrivate();

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyPair.getPublic().getEncoded());
    IOUtils.write(Encryptor.encryptRaw(x509EncodedKeySpec.getEncoded(), TestLicenseManager.keyPassword),
            outputStream);
    TestLicenseManager.encryptedPublicKey = outputStream.toByteArray();
}

From source file:org.umit.icm.mobile.utils.ProfilerRun.java

private static void profileRSADecrypt() {
    Profiler profiler = new Profiler();
    profiler.runProfiler(new TaskInterface() {
        public void task() {
            try {
                KeyPair keyPair = RSACrypto.generateKey();
                String cipherText = RSACrypto.encryptPublic(keyPair.getPublic(), "This is a test string");
                RSACrypto.decryptPrivate(keyPair.getPrivate(), cipherText);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();//  w  ww.  j a va2 s .c  o m
            }
        }

        public String taskName() {
            return "RSA Public Decryption";
        }
    });
}

From source file:com.kixeye.chassis.transport.shared.JettyConnectorRegistry.java

/**
 * Register to listen to HTTPS.//from   w  w  w.  j a  v a 2 s.c  o  m
 * 
 * @param server
 * @param address
 * @throws Exception 
 */
public static void registerHttpsConnector(Server server, InetSocketAddress address, boolean selfSigned,
        boolean mutualSsl, String keyStorePath, String keyStoreData, String keyStorePassword,
        String keyManagerPassword, String trustStorePath, String trustStoreData, String trustStorePassword,
        String[] excludedCipherSuites) throws Exception {
    // SSL Context Factory
    SslContextFactory sslContextFactory = new SslContextFactory();

    if (selfSigned) {
        char[] passwordChars = UUID.randomUUID().toString().toCharArray();

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

        keyStore.load(null, passwordChars);

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

        v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()).abs());
        v3CertGen.setIssuerDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));
        v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
        v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
        v3CertGen.setSubjectDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));

        v3CertGen.setPublicKey(keyPair.getPublic());
        v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");

        X509Certificate privateKeyCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());

        keyStore.setKeyEntry("selfSigned", keyPair.getPrivate(), passwordChars,
                new java.security.cert.Certificate[] { privateKeyCertificate });

        ByteArrayOutputStream keyStoreBaos = new ByteArrayOutputStream();
        keyStore.store(keyStoreBaos, passwordChars);

        keyStoreData = new String(Hex.encode(keyStoreBaos.toByteArray()), Charsets.UTF_8);
        keyStorePassword = new String(passwordChars);
        keyManagerPassword = keyStorePassword;

        sslContextFactory.setTrustAll(true);
    }

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

    if (StringUtils.isNotBlank(keyStoreData)) {
        keyStore.load(new ByteArrayInputStream(Hex.decode(keyStoreData)), keyStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(keyStorePath)) {
        try (InputStream inputStream = new DefaultResourceLoader().getResource(keyStorePath).getInputStream()) {
            keyStore.load(inputStream, keyStorePassword.toCharArray());
        }
    }

    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyStorePassword(keyStorePassword);
    if (StringUtils.isBlank(keyManagerPassword)) {
        keyManagerPassword = keyStorePassword;
    }
    sslContextFactory.setKeyManagerPassword(keyManagerPassword);
    KeyStore trustStore = null;
    if (StringUtils.isNotBlank(trustStoreData)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(new ByteArrayInputStream(Hex.decode(trustStoreData)), trustStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(trustStorePath)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream inputStream = new DefaultResourceLoader().getResource(trustStorePath)
                .getInputStream()) {
            trustStore.load(inputStream, trustStorePassword.toCharArray());
        }
    }
    if (trustStore != null) {
        sslContextFactory.setTrustStore(trustStore);
        sslContextFactory.setTrustStorePassword(trustStorePassword);
    }
    sslContextFactory.setNeedClientAuth(mutualSsl);
    sslContextFactory.setExcludeCipherSuites(excludedCipherSuites);

    // SSL Connector
    ServerConnector connector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.toString()),
            new HttpConnectionFactory());
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());

    server.addConnector(connector);
}

From source file:bftsmart.tom.util.RSAKeyPairGenerator.java

/**
 * Generate the key pair for the process with id = <id> and put it on the
 * files config/keys/publickey<id> and config/keys/privatekey<id>
 *
 * @param id the id of the process to generate key
 * @throws Exception something goes wrong when writing the files
 *//*  ww w.  ja  v  a2  s.  co m*/
public void run(int id, int size) throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(size);
    KeyPair kp = keyGen.generateKeyPair();
    PublicKey puk = kp.getPublic();
    PrivateKey prk = kp.getPrivate();
    saveToFile(id, puk, prk);
}

From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java

/**
 * Creates a new self-signed X509 certificate
 *
 * @param pair the public/private keypair- the pubkey will be added to the cert and the private
 * key will be used to sign the certificate
 * @param subject the distinguished name of the subject
 * @param isAuthority true to make the cert a CA cert, false otherwise
 * @return/*from  w ww  .  jav  a2  s. com*/
 */
public static X509Certificate newSelfSignedCertificate(KeyPair pair, X500Name subject, boolean isAuthority) {
    X509v3CertificateBuilder b = new JcaX509v3CertificateBuilder(subject,
            BigInteger.probablePrime(128, new SecureRandom()), Date.from(Instant.now().minusSeconds(1)),
            Date.from(LocalDateTime.now().plusYears(3).toInstant(ZoneOffset.UTC)), subject, pair.getPublic());
    try {
        b.addExtension(Extension.basicConstraints, true, new BasicConstraints(isAuthority));
    } catch (CertIOException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        X509CertificateHolder bcCert = b.build(
                new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider("BC").build(pair.getPrivate()));
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(bcCert);
    } catch (CertificateException | OperatorCreationException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

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

@Test
public void testSignature() {
    final byte[] message = "?????????????".getBytes();
    final KeyPair keyPair = SecurityHelper.generateKeyPair();
    final byte[] signature = SecurityHelper.signature(keyPair.getPrivate(), message);
    assertThat(SecurityHelper.verify(keyPair.getPublic(), signature, message), is(true));
}