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

The following examples show how to use java.security.KeyFactory#getInstance() . 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: SimpleTokenUtils.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Decode a JWK(S) encoded public key string to an RSA PublicKey
 * @param jwksValue - JWKS string value
 * @return RSAPublicKey from RSAPublicKeySpec
 */
public static RSAPublicKey decodeJWKSPublicKey(String jwksValue) throws Exception {
    JsonObject jwks = Json.createReader(new StringReader(jwksValue)).readObject();
    JsonArray keys = jwks.getJsonArray("keys");
    JsonObject jwk;
    if(keys != null) {
        jwk = keys.getJsonObject(0);
    }
    else {
        jwk = jwks;
    }
    String e = jwk.getString("e");
    String n = jwk.getString("n");

    byte[] ebytes = Base64.getUrlDecoder().decode(e);
    BigInteger publicExponent = new BigInteger(1, ebytes);
    byte[] nbytes = Base64.getUrlDecoder().decode(n);
    BigInteger modulus = new BigInteger(1, nbytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, publicExponent);
    return (RSAPublicKey)kf.generatePublic(rsaPublicKeySpec);
}
 
Example 2
Source File: RSA.java    From aes-rsa-java with Apache License 2.0 6 votes vote down vote up
public static String sign(String content, String privateKey) {
	String charset = ConfigureEncryptAndDecrypt.CHAR_ENCODING;
	try {
		PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
				Base64.decodeBase64(privateKey.getBytes()));
		KeyFactory keyf = KeyFactory.getInstance("RSA");
		PrivateKey priKey = keyf.generatePrivate(priPKCS8);

		Signature signature = Signature.getInstance("SHA256WithRSA");

		signature.initSign(priKey);
		signature.update(content.getBytes(charset));

		byte[] signed = signature.sign();

		return new String(Base64.encodeBase64(signed));
	} catch (Exception e) {

	}

	return null;
}
 
Example 3
Source File: RSAUtil.java    From RairDemo with Apache License 2.0 6 votes vote down vote up
/**
 * 加密<br>
 * 用公钥加密
 *
 * @param data
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] encryptByPublicKey(byte[] data, String key)
        throws Exception {
    // 对公钥解密
    byte[] keyBytes = Base64Util.decodeToBytes(key);

    // 取得公钥
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    Key publicKey = keyFactory.generatePublic(x509KeySpec);

    // 对数据加密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);

    return cipher.doFinal(data);
}
 
Example 4
Source File: RSAUtils.java    From danyuan-application with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * 公钥解密
 * </p>
 * @param encryptedData 已加密数据
 * @param publicKey 公钥(BASE64编码)
 * @return
 * @throws Exception
 */
public static byte[] decryptByPublicKey(byte[] encryptedData, byte[] publicKey) throws Exception {
	byte[] keyBytes = Base64Utils.decode(publicKey);
	X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
	KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
	Key publicK = keyFactory.generatePublic(x509KeySpec);
	Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
	cipher.init(Cipher.DECRYPT_MODE, publicK);
	int inputLen = encryptedData.length;
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	int offSet = 0;
	byte[] cache;
	int i = 0;
	// 对数据分段解密
	while (inputLen - offSet > 0) {
		if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
			cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
		} else {
			cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
		}
		out.write(cache, 0, cache.length);
		i++;
		offSet = i * MAX_DECRYPT_BLOCK;
	}
	byte[] decryptedData = out.toByteArray();
	out.close();
	return decryptedData;
}
 
Example 5
Source File: RsaImpl.java    From tephra with MIT License 5 votes vote down vote up
private Key getKey(KeyType type, byte[] key) throws NoSuchAlgorithmException, InvalidKeySpecException {
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    if (type == KeyType.Private)
        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(key));

    return keyFactory.generatePublic(new X509EncodedKeySpec(key));
}
 
Example 6
Source File: RSAUtils.java    From Rocko-Android-Demos with Apache License 2.0 5 votes vote down vote up
/**
 * 使用N、e值还原公钥
 * 
 * @param modulus
 * @param publicExponent
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static PublicKey getPublicKey(String modulus, String publicExponent)
		throws NoSuchAlgorithmException, InvalidKeySpecException
{
	BigInteger bigIntModulus = new BigInteger(modulus);
	BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);
	RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
	KeyFactory keyFactory = KeyFactory.getInstance(KEY_PAIR);
	PublicKey publicKey = keyFactory.generatePublic(keySpec);
	return publicKey;
}
 
Example 7
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 8
Source File: RSAEncryptionMaterialsProvider.java    From emr-sample-apps with Apache License 2.0 5 votes vote down vote up
private PublicKey getRSAPublicKey(InputStream publicKeyInputStream)
    throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
  byte[] publicKeyBytes = IOUtils.toByteArray(publicKeyInputStream);
  X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes);
  KeyFactory keyFactory = KeyFactory.getInstance(RSA);
  return keyFactory.generatePublic(spec);
}
 
Example 9
Source File: ErrorHandlerPermissions.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
    Document doc = dbf.newDocumentBuilder().parse(new File(SIGNATURE));
    NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS,
            "Signature");
    if (nl.getLength() == 0) {
        throw new RuntimeException("Couldn't find 'Signature' element");
    }
    Element element = (Element) nl.item(0);

    byte[] keyBytes = Base64.getDecoder().decode(validationKey);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey key = kf.generatePublic(spec);
    KeySelector ks = KeySelector.singletonKeySelector(key);

    DOMValidateContext vc = new DOMValidateContext(ks, element);

    // disable secure validation mode
    vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

    // set a dummy dereferencer to be able to get content by references
    vc.setURIDereferencer(dereferencer);

    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    XMLSignature signature = factory.unmarshalXMLSignature(vc);

    // run validation
    signature.validate(vc);
}
 
Example 10
Source File: RSAUtils.java    From danyuan-application with Apache License 2.0 5 votes vote down vote up
/**
 * <P>
 * 私钥解密
 * </p>
 * @param encryptedData 已加密数据
 * @param privateKey 私钥(BASE64编码)
 * @return
 * @throws Exception
 */
public static byte[] decryptByPrivateKey(byte[] encryptedData, byte[] privateKey) throws Exception {
	byte[] keyBytes = Base64Utils.decode(privateKey);
	PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
	KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
	Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
	Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
	cipher.init(Cipher.DECRYPT_MODE, privateK);
	int inputLen = encryptedData.length;
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	int offSet = 0;
	byte[] cache;
	int i = 0;
	// 对数据分段解密
	while (inputLen - offSet > 0) {
		if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
			cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
		} else {
			cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
		}
		out.write(cache, 0, cache.length);
		i++;
		offSet = i * MAX_DECRYPT_BLOCK;
	}
	byte[] decryptedData = out.toByteArray();
	out.close();
	return decryptedData;
}
 
Example 11
Source File: Basic.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static int copy(int testnum) throws Exception {

        if (ks == null) {
            ks = KeyStore.getInstance(KS_TYPE, provider);
            ks.load(null, tokenPwd);
        }

        KeyFactory kf = KeyFactory.getInstance("RSA", provider);
        PrivateKey pkSession = (PrivateKey)kf.translateKey(pk3);
        System.out.println("pkSession = " + pkSession);
        ks.setKeyEntry("pkSession", pkSession, null, chain3);

        KeyStore.PrivateKeyEntry pke =
                (KeyStore.PrivateKeyEntry)ks.getEntry("pkSession", null);
        System.out.println("pkSession = " + pke.getPrivateKey());
        Certificate[] chain = pke.getCertificateChain();
        if (chain.length != chain3.length) {
            throw new SecurityException("received chain not correct length");
        }
        for (int i = 0; i < chain.length; i++) {
            if (!chain[i].equals(chain3[i])) {
                throw new SecurityException("received chain not equal");
            }
        }

        System.out.println("test " + testnum++ + " passed");

        return testnum;
    }
 
Example 12
Source File: JsonWebKey.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
/**
 * Get the RSA private key value.
 *
 * @param provider
 *            the Java security provider.
 * @return the RSA private key value
 */
private PrivateKey getRSAPrivateKey(Provider provider) {

    try {
        RSAPrivateKeySpec privateKeySpec = getRSAPrivateKeySpec();
        KeyFactory factory = provider != null ? KeyFactory.getInstance("RSA", provider)
                : KeyFactory.getInstance("RSA");

        return factory.generatePrivate(privateKeySpec);
    } catch (GeneralSecurityException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 13
Source File: RSACoder.java    From wecube-platform with Apache License 2.0 4 votes vote down vote up
private byte[] doDecryptByPublicKey(byte[] data, byte[] key)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        IllegalBlockSizeException, BadPaddingException {
    initProvider();
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);

    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

    PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);

    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

    cipher.init(Cipher.DECRYPT_MODE, publicKey);

    return cipher.doFinal(data);
}
 
Example 14
Source File: PKIXExtendedTM.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private static SSLContext getSSLContext(String trusedCertStr,
        String keyCertStr, byte[] modulus,
        byte[] privateExponent, char[] passphrase) throws Exception {

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

    ByteArrayInputStream is =
                new ByteArrayInputStream(trusedCertStr.getBytes());
    Certificate trusedCert = cf.generateCertificate(is);
    is.close();

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

    // import the trused cert
    ks.setCertificateEntry("RSA Export Signer", trusedCert);

    if (keyCertStr != null) {
        // generate the private key.
        RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(
                                        new BigInteger(modulus),
                                        new BigInteger(privateExponent));
        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 = new Certificate[2];
        chain[0] = keyCert;
        chain[1] = trusedCert;

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

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

    TrustManager tms[] = tmf.getTrustManagers();
    if (tms == null || tms.length == 0) {
        throw new Exception("unexpected trust manager implementation");
    } else {
       if (!(tms[0] instanceof X509ExtendedTrustManager)) {
           throw new Exception("unexpected trust manager implementation: "
                            + tms[0].getClass().getCanonicalName());
       }
    }


    SSLContext ctx = SSLContext.getInstance("TLS");

    if (keyCertStr != null) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passphrase);

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

    return ctx;
}
 
Example 15
Source File: Identities.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static SSLContext getSSLContext(String trusedCertStr,
        String keyCertStr, byte[] modulus,
        byte[] privateExponent, char[] passphrase) throws Exception {

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

    ByteArrayInputStream is =
                new ByteArrayInputStream(trusedCertStr.getBytes());
    Certificate trusedCert = cf.generateCertificate(is);
    is.close();

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

    // import the trused cert
    ks.setCertificateEntry("RSA Export Signer", trusedCert);

    if (keyCertStr != null) {
        // generate the private key.
        RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(
                                        new BigInteger(modulus),
                                        new BigInteger(privateExponent));
        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 = new Certificate[2];
        chain[0] = keyCert;
        chain[1] = trusedCert;

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

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

    SSLContext ctx = SSLContext.getInstance("TLS");

    if (keyCertStr != null) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passphrase);

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

    return ctx;
}
 
Example 16
Source File: SSLSocketSNISensitive.java    From hottub 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 17
Source File: BasicConstraints.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
private static SSLContext getSSLContext(boolean isServer) 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(trusedCertStr.getBytes());
        Certificate trusedCert = cf.generateCertificate(is);
        is.close();

        ks.setCertificateEntry("SunJSSE Test Serivce", trusedCert);

        // import the certificate chain and key
        Certificate[] chain = new Certificate[3];

        is = new ByteArrayInputStream(caSignerStr.getBytes());
        Certificate caSignerCert = cf.generateCertificate(is);
        is.close();
        chain[2] = caSignerCert;

        is = new ByteArrayInputStream(certIssuerStr.getBytes());
        Certificate certIssuerCert = cf.generateCertificate(is);
        is.close();
        chain[1] = certIssuerCert;

        PKCS8EncodedKeySpec priKeySpec = null;
        if (isServer) {
            priKeySpec = new PKCS8EncodedKeySpec(
                            Base64.getMimeDecoder().decode(serverPrivateKey));
            is = new ByteArrayInputStream(serverCertStr.getBytes());
        } else {
            priKeySpec = new PKCS8EncodedKeySpec(
                            Base64.getMimeDecoder().decode(clientPrivateKey));
            is = new ByteArrayInputStream(clientCertStr.getBytes());
        }
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey = (RSAPrivateKey)kf.generatePrivate(priKeySpec);
        Certificate keyCert = cf.generateCertificate(is);
        is.close();
        chain[0] = keyCert;

        ks.setKeyEntry("End Entity", priKey, passphrase, chain);

        // check the certification path
        PKIXParameters paras = new PKIXParameters(ks);
        paras.setRevocationEnabled(false);
        CertPath path = cf.generateCertPath(Arrays.asList(chain));
        CertPathValidator cv = CertPathValidator.getInstance("PKIX");
        cv.validate(path, paras);

        // 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 18
Source File: DisabledShortRSAKeys.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();

        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 19
Source File: ShortRSAKeyGCM.java    From jdk8u-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(
                            new BASE64Decoder().decodeBuffer(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 20
Source File: X509CredentialImpl.java    From micro-integrator with Apache License 2.0 3 votes vote down vote up
/**
 * The key is constructed form modulus and exponent.
 *
 * @param modulus
 * @param publicExponent
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public X509CredentialImpl(BigInteger modulus, BigInteger publicExponent)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, publicExponent);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    publicKey = keyFactory.generatePublic(spec);
}