Java Code Examples for java.security.KeyFactory#generatePrivate()

The following examples show how to use java.security.KeyFactory#generatePrivate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SecurityTestUtils.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
static void configureJDKTrustStore(Path workDir, SelfSignedCertificate clientCert) throws Exception {
  KeyStore ks = KeyStore.getInstance("JKS");
  ks.load(null, null);

  KeyFactory kf = KeyFactory.getInstance("RSA");
  PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(readPemFile(new File(clientCert.privateKeyPath()).toPath()));
  PrivateKey clientPrivateKey = kf.generatePrivate(keysp);
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  Certificate certificate = cf
      .generateCertificate(
          new ByteArrayInputStream(Files.readAllBytes(new File(clientCert.certificatePath()).toPath())));
  ks.setCertificateEntry("clientCert", certificate);
  ks.setKeyEntry("client", clientPrivateKey, "changeit".toCharArray(), new Certificate[] {certificate});
  Path tempKeystore = Files.createTempFile(workDir, "keystore", ".jks");
  try (FileOutputStream output = new FileOutputStream(tempKeystore.toFile());) {
    ks.store(output, "changeit".toCharArray());
  }
  System.setProperty("javax.net.ssl.trustStore", tempKeystore.toString());
  System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
}
 
Example 2
Source File: AlipayUtil.java    From common-project with Apache License 2.0 6 votes vote down vote up
/**
* RSA签名
* @param content 待签名数据
* @param privateKey 商户私钥
* @param input_charset 编码格式
* @return 签名值
*/
public static String sign(String content, String privateKey, String input_charset) {
	try {
		PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
		KeyFactory keyf = KeyFactory.getInstance("RSA");
		PrivateKey priKey = keyf.generatePrivate(priPKCS8);
		Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
		signature.initSign(priKey);
		signature.update(content.getBytes(input_charset));
		byte[] signed = signature.sign();
		return new String(Base64.getEncoder().encode(signed));
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 3
Source File: AbstractAli.java    From pay-spring-boot with GNU General Public License v3.0 6 votes vote down vote up
public AbstractAli() {
    try{
        /*
            创建商户私钥
         */
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(PayBase64.decode(AliPayConfig.getPrivateKey()));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PRIVATE_KEY = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

        /*
            创建支付宝公钥
         */
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(PayBase64.decode(AliPayConfig.getAliPublicKey()));
        ALI_PUBLIC_KEY = keyFactory.generatePublic(x509EncodedKeySpec);
    }catch(Exception e){
        throw new RuntimeException("创建RSA密钥异常", e);
    }
}
 
Example 4
Source File: RSAEncrypt.java    From SprintNBA with Apache License 2.0 6 votes vote down vote up
/**
 * 用私钥对信息生成数字签名
 *
 * @param data	//加密数据
 * @param privateKey	//私钥
 * @return
 * @throws Exception
 */
public String sign(byte[] data,String privateKey)throws Exception{
    //解密私钥
    byte[] keyBytes = Base64.decode(privateKey, Base64.DEFAULT);
    //构造PKCS8EncodedKeySpec对象
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
    //指定加密算法
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
    //取私钥匙对象
    PrivateKey privateKey2 = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    //用私钥对信息生成数字签名
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initSign(privateKey2);
    signature.update(data);
    byte[] signByte = signature.sign();
    return new String(Base64.encode(signByte, Base64.DEFAULT),"UTF-8");
}
 
Example 5
Source File: TestUtils.java    From orion with Apache License 2.0 6 votes vote down vote up
public static void configureJDKTrustStore(final SelfSignedCertificate clientCert, final Path tempDir)
    throws Exception {
  final KeyStore ks = KeyStore.getInstance("JKS");
  ks.load(null, null);

  final KeyFactory kf = KeyFactory.getInstance("RSA");
  final PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(readPemFile(Paths.get(clientCert.privateKeyPath())));
  final PrivateKey clientPrivateKey = kf.generatePrivate(keysp);
  final CertificateFactory cf = CertificateFactory.getInstance("X.509");
  final Certificate certificate = cf.generateCertificate(
      new ByteArrayInputStream(Files.readAllBytes(new File(clientCert.certificatePath()).toPath())));
  ks.setCertificateEntry("clientCert", certificate);
  ks.setKeyEntry("client", clientPrivateKey, "changeit".toCharArray(), new Certificate[] {certificate});
  final Path tempKeystore = tempDir.resolve("keystore.jks");
  try (final FileOutputStream output = new FileOutputStream(tempKeystore.toFile())) {
    ks.store(output, "changeit".toCharArray());
  }
  System.setProperty("javax.net.ssl.trustStore", tempKeystore.toString());
  System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
}
 
Example 6
Source File: EncryptRSA.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 解密
 * 
 * @param privateKeyArray
 * @param srcBytes
 * @return
 */
public byte[] decrypt(byte[] privateKeyArray, byte[] srcBytes) {
	try {
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyArray);
		KeyFactory kf = KeyFactory.getInstance(algorithm);
		PrivateKey keyPrivate = kf.generatePrivate(keySpec);

		Cipher cipher = Cipher.getInstance(algorithm,
				new org.bouncycastle.jce.provider.BouncyCastleProvider());
		cipher.init(Cipher.DECRYPT_MODE, keyPrivate);

		int blockSize = cipher.getBlockSize();
		ByteArrayOutputStream bout = new ByteArrayOutputStream(blockSize);
		int j = 0;
		while (srcBytes.length - j * blockSize > 0) {
			byte[] temp = cipher.doFinal(srcBytes, j * blockSize, blockSize);
			bout.write(temp);
			j++;
		}
		return bout.toByteArray();
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
}
 
Example 7
Source File: SecurityTestUtils.java    From cava with Apache License 2.0 6 votes vote down vote up
static void configureJDKTrustStore(Path workDir, SelfSignedCertificate clientCert) throws Exception {
  KeyStore ks = KeyStore.getInstance("JKS");
  ks.load(null, null);

  KeyFactory kf = KeyFactory.getInstance("RSA");
  PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(readPemFile(new File(clientCert.privateKeyPath()).toPath()));
  PrivateKey clientPrivateKey = kf.generatePrivate(keysp);
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  Certificate certificate = cf.generateCertificate(
      new ByteArrayInputStream(Files.readAllBytes(new File(clientCert.certificatePath()).toPath())));
  ks.setCertificateEntry("clientCert", certificate);
  ks.setKeyEntry("client", clientPrivateKey, "changeit".toCharArray(), new Certificate[] {certificate});
  Path tempKeystore = Files.createTempFile(workDir, "keystore", ".jks");
  try (FileOutputStream output = new FileOutputStream(tempKeystore.toFile());) {
    ks.store(output, "changeit".toCharArray());
  }
  System.setProperty("javax.net.ssl.trustStore", tempKeystore.toString());
  System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
}
 
Example 8
Source File: PEMManager.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public PrivateKey getPrivateKey()
        throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {
    PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(pem.getContent());
    KeyFactory keyFacotry = KeyFactory.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME);

    return keyFacotry.generatePrivate(encodedKeySpec);
}
 
Example 9
Source File: RSAEncryptCoder.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] dencrypt(byte[] privateKey, byte[] byteContent) {
	PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
	KeyFactory kf;
	PrivateKey keyPrivate;
	try {
		kf = KeyFactory.getInstance(RSA_KEY);
		keyPrivate = kf.generatePrivate(keySpec);
	} catch (Exception e) {
		throw new BaseException("generate private key error: " + e.getMessage() , e);
	}
	
	byte[] result = chunkedCipher(keyPrivate, Cipher.DECRYPT_MODE, dencryptSize, byteContent);
	return result;
}
 
Example 10
Source File: TokenUtils.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Decode a PEM encoded private key string to an RSA PrivateKey
 * 
 * @param pemEncoded - PEM string for private key
 * @return PrivateKey
 * @throws Exception on decode failure
 */
public static PrivateKey decodePrivateKey(final String pemEncoded) throws Exception {
    byte[] encodedBytes = toEncodedBytes(pemEncoded);

    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePrivate(keySpec);
}
 
Example 11
Source File: RsaOaep.java    From java-telegram-bot-api with Apache License 2.0 5 votes vote down vote up
static byte[] decrypt(String privateKey, byte[] secret) throws Exception {
    String pkcs8Pem = privateKey;
    pkcs8Pem = pkcs8Pem.replace("-----BEGIN RSA PRIVATE KEY-----", "");
    pkcs8Pem = pkcs8Pem.replace("-----END RSA PRIVATE KEY-----", "");
    pkcs8Pem = pkcs8Pem.replaceAll("\\s+", "");
    byte[] pkcs8EncodedBytes = Base64.decode(pkcs8Pem, 0);

    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey privKey = kf.generatePrivate(getRSAKeySpec(pkcs8EncodedBytes));

    Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
    cipher.init(Cipher.DECRYPT_MODE, privKey);
    return cipher.doFinal(secret);
}
 
Example 12
Source File: RSASignature.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] encrypt(byte[] source, byte[] key) throws GeneralSecurityException {
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key);
    KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
    PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

    java.security.Signature signature = java.security.Signature.getInstance(signatureAlgorithm);
    signature.initSign(privateKey);
    signature.update(source);
    return signature.sign();
}
 
Example 13
Source File: ServerConfigData.java    From revolution-irc with GNU General Public License v3.0 5 votes vote down vote up
public PrivateKey getAuthPrivateKey() {
    if (authCertPrivKey == null)
        return null;
    try {
        KeyFactory factory = KeyFactory.getInstance(authCertPrivKeyType);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(authCertPrivKey);
        return factory.generatePrivate(keySpec);
    } catch (GeneralSecurityException e) {
        Log.w("ServerConfigData", "Failed to load private key");
        e.printStackTrace();
    }
    return null;
}
 
Example 14
Source File: JsonWebKey.java    From swim with Apache License 2.0 5 votes vote down vote up
public ECPrivateKey ecPrivateKey() {
  final ECParameterSpec params = ecParameterSpec(this.value.get("crv").stringValue());
  final BigInteger d = parseBase64UrlUInt(this.value.get("d").stringValue());
  try {
    final ECPrivateKeySpec keySpec = new ECPrivateKeySpec(d, params);
    final KeyFactory keyFactory = KeyFactory.getInstance("EC");
    return (ECPrivateKey) keyFactory.generatePrivate(keySpec);
  } catch (GeneralSecurityException cause) {
    throw new RuntimeException(cause);
  }
}
 
Example 15
Source File: XMLHelpersTest.java    From SAMLRaider with MIT License 4 votes vote down vote up
public PrivateKey loadTestKey() throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
	PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(Files.readAllBytes(Paths.get("src/test/resources/samlwin_pkcs8.key")));
	KeyFactory kf = KeyFactory.getInstance("RSA");
	return kf.generatePrivate(ks);
}
 
Example 16
Source File: MD2InTrustAnchor.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private static SSLContext generateSSLContext(String trustedCertStr,
        String keyCertStr, String keySpecStr) throws Exception {

    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trused cert
    Certificate trusedCert = null;
    ByteArrayInputStream is = null;
    if (trustedCertStr != null) {
        is = new ByteArrayInputStream(trustedCertStr.getBytes());
        trusedCert = cf.generateCertificate(is);
        is.close();

        ks.setCertificateEntry("RSA Export Signer", trusedCert);
    }

    if (keyCertStr != null) {
        // generate the private key.
        PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
                            Base64.getMimeDecoder().decode(keySpecStr));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey =
                (RSAPrivateKey)kf.generatePrivate(priKeySpec);

        // generate certificate chain
        is = new ByteArrayInputStream(keyCertStr.getBytes());
        Certificate keyCert = cf.generateCertificate(is);
        is.close();

        // It's not allowed to send MD2 signed certificate to peer,
        // even it may be a trusted certificate. Then we will not
        // place the trusted certficate in the chain.
        Certificate[] chain = new Certificate[1];
        chain[0] = keyCert;

        // import the key entry.
        ks.setKeyEntry("Whatever", priKey, passphrase, chain);
    }

    // create SSL context
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm);
    tmf.init(ks);

    SSLContext ctx = SSLContext.getInstance(tlsProtocol);
    if (keyCertStr != null && !keyCertStr.isEmpty()) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
        kmf.init(ks, passphrase);

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        ks = null;
    } else {
        ctx.init(null, tmf.getTrustManagers(), null);
    }

    return ctx;
}
 
Example 17
Source File: ShortRSAKey512.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
private static SSLContext generateSSLContext(String trustedCertStr,
        String keyCertStr, String keySpecStr) throws Exception {

    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trused cert
    Certificate trusedCert = null;
    ByteArrayInputStream is = null;
    if (trustedCertStr != null) {
        is = new ByteArrayInputStream(trustedCertStr.getBytes());
        trusedCert = cf.generateCertificate(is);
        is.close();

        ks.setCertificateEntry("RSA Export Signer", trusedCert);
    }

    if (keyCertStr != null) {
        // generate the private key.
        PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
                            Base64.getMimeDecoder().decode(keySpecStr));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey =
                (RSAPrivateKey)kf.generatePrivate(priKeySpec);

        // generate certificate chain
        is = new ByteArrayInputStream(keyCertStr.getBytes());
        Certificate keyCert = cf.generateCertificate(is);
        is.close();

        Certificate[] chain = null;
        if (trusedCert != null) {
            chain = new Certificate[2];
            chain[0] = keyCert;
            chain[1] = trusedCert;
        } else {
            chain = new Certificate[1];
            chain[0] = keyCert;
        }

        // import the key entry.
        ks.setKeyEntry("Whatever", priKey, passphrase, chain);
    }

    // create SSL context
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm);
    tmf.init(ks);

    SSLContext ctx = SSLContext.getInstance("TLS");
    if (keyCertStr != null && !keyCertStr.isEmpty()) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
        kmf.init(ks, passphrase);

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        ks = null;
    } else {
        ctx.init(null, tmf.getTrustManagers(), null);
    }

    return ctx;
}
 
Example 18
Source File: RSATest.java    From java_security with MIT License 4 votes vote down vote up
public static void jdkRSA()
{		
	try 
	{
		// 1.初始化发送方密钥
		KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
		keyPairGenerator.initialize(512);
		KeyPair keyPair = keyPairGenerator.generateKeyPair();
		RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
		RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
		System.out.println("Public Key:" + Base64.encodeBase64String(rsaPublicKey.getEncoded()));
		System.out.println("Private Key:" + Base64.encodeBase64String(rsaPrivateKey.getEncoded()));
		
		// 2.私钥加密、公钥解密 ---- 加密
		PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.ENCRYPT_MODE, privateKey);
		byte[] result = cipher.doFinal(src.getBytes());
		System.out.println("私钥加密、公钥解密 ---- 加密:" + Base64.encodeBase64String(result));
		
		// 3.私钥加密、公钥解密 ---- 解密
		X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
		keyFactory = KeyFactory.getInstance("RSA");
		PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
		cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, publicKey);
		result = cipher.doFinal(result);
		System.out.println("私钥加密、公钥解密 ---- 解密:" + new String(result));
		
		
		
		// 4.公钥加密、私钥解密 ---- 加密
		X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
		KeyFactory keyFactory2 = KeyFactory.getInstance("RSA");
		PublicKey publicKey2 = keyFactory2.generatePublic(x509EncodedKeySpec2);
		Cipher cipher2 = Cipher.getInstance("RSA");
		cipher2.init(Cipher.ENCRYPT_MODE, publicKey2);
		byte[] result2 = cipher2.doFinal(src.getBytes());
		System.out.println("公钥加密、私钥解密 ---- 加密:" + Base64.encodeBase64String(result2));
		
		// 5.私钥解密、公钥加密 ---- 解密
		PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
		KeyFactory keyFactory5 = KeyFactory.getInstance("RSA");
		PrivateKey privateKey5 = keyFactory5.generatePrivate(pkcs8EncodedKeySpec5);
		Cipher cipher5 = Cipher.getInstance("RSA");
		cipher5.init(Cipher.DECRYPT_MODE, privateKey5);
		byte[] result5 = cipher5.doFinal(result2);
		System.out.println("公钥加密、私钥解密 ---- 解密:" + new String(result5));
		
	} catch (Exception e) {
		
		e.printStackTrace();
	}
	
}
 
Example 19
Source File: SSLSocketSNISensitive.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private static SSLContext generateSSLContext(boolean isClient)
        throws Exception {

    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trused cert
    ByteArrayInputStream is =
                new ByteArrayInputStream(trustedCertStr.getBytes());
    Certificate trusedCert = cf.generateCertificate(is);
    is.close();

    ks.setCertificateEntry("RSA Export Signer", trusedCert);

    String[] certStrs = null;
    String[] keyStrs = null;
    if (isClient) {
        certStrs = clientCerts;
        keyStrs = clientKeys;
    } else {
        certStrs = serverCerts;
        keyStrs = serverKeys;
    }

    for (int i = 0; i < certStrs.length; i++) {
        // generate the private key.
        String keySpecStr = keyStrs[i];
        PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
                            Base64.getMimeDecoder().decode(keySpecStr));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey =
                (RSAPrivateKey)kf.generatePrivate(priKeySpec);

        // generate certificate chain
        String keyCertStr = certStrs[i];
        is = new ByteArrayInputStream(keyCertStr.getBytes());
        Certificate keyCert = cf.generateCertificate(is);
        is.close();

        Certificate[] chain = new Certificate[2];
        chain[0] = keyCert;
        chain[1] = trusedCert;

        // import the key entry.
        ks.setKeyEntry("key-entry-" + i, priKey, passphrase, chain);
    }

    // create SSL context
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm);
    tmf.init(ks);

    SSLContext ctx = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
    kmf.init(ks, passphrase);

    ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    ks = null;

    return ctx;
}
 
Example 20
Source File: MD2InTrustAnchor.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
private static SSLContext generateSSLContext(String trustedCertStr,
        String keyCertStr, String keySpecStr) throws Exception {

    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trused cert
    Certificate trusedCert = null;
    ByteArrayInputStream is = null;
    if (trustedCertStr != null) {
        is = new ByteArrayInputStream(trustedCertStr.getBytes());
        trusedCert = cf.generateCertificate(is);
        is.close();

        ks.setCertificateEntry("RSA Export Signer", trusedCert);
    }

    if (keyCertStr != null) {
        // generate the private key.
        PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
                            Base64.getMimeDecoder().decode(keySpecStr));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey =
                (RSAPrivateKey)kf.generatePrivate(priKeySpec);

        // generate certificate chain
        is = new ByteArrayInputStream(keyCertStr.getBytes());
        Certificate keyCert = cf.generateCertificate(is);
        is.close();

        // It's not allowed to send MD2 signed certificate to peer,
        // even it may be a trusted certificate. Then we will not
        // place the trusted certficate in the chain.
        Certificate[] chain = new Certificate[1];
        chain[0] = keyCert;

        // import the key entry.
        ks.setKeyEntry("Whatever", priKey, passphrase, chain);
    }

    // create SSL context
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm);
    tmf.init(ks);

    SSLContext ctx = SSLContext.getInstance(tlsProtocol);
    if (keyCertStr != null && !keyCertStr.isEmpty()) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
        kmf.init(ks, passphrase);

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        ks = null;
    } else {
        ctx.init(null, tmf.getTrustManagers(), null);
    }

    return ctx;
}