下面列出了javax.net.ssl.KeyManagerFactorySpi#javax.net.ssl.KeyManager 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
protected static KeyManager[] getUser1KeyManagers() throws Exception {
KeyManagerFactory kmf = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmf.init(getKeyStore(CLIENT_JKS), JKS_PASS.toCharArray());
KeyManager[] managers = kmf.getKeyManagers();
KeyManager manager;
for (int i=0; i < managers.length; i++) {
manager = managers[i];
if (manager instanceof X509ExtendedKeyManager) {
managers[i] = new TrackingExtendedKeyManager((X509ExtendedKeyManager)manager);
} else if (manager instanceof X509KeyManager) {
managers[i] = new TrackingKeyManager((X509KeyManager)manager);
}
}
return managers;
}
SSLSocketFactory getSslSocketFactory(@Nullable String clientCertAlias) {
try {
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore androidCAStore = KeyStore.getInstance("AndroidCAStore");
if (androidCAStore == null) {
HyperLog.w(TAG, "Unable to load CA keystore");
return null;
}
androidCAStore.load(null);
trustManagerFactory.init(androidCAStore);
KeyManager[] keyManagers = null;
if (clientCertAlias != null) {
keyManagers = getClientKeyManagers(clientCertAlias);
}
sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
return sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | CertificateException | IOException e) {
HyperLog.w(TAG, "Unable to get socket factory", e);
return null;
}
}
private static SSLContext createSSLContext(KeyManager[] km, TrustManager[] tm, String provider) throws Exception {
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("TLSv1.2", provider);
} catch (Exception e) {
try {
sslContext = SSLContext.getInstance("TLSv1.1", provider);
} catch (Exception ex) {
try {
sslContext = SSLContext.getInstance("TLSv1.0", provider);
} catch (Exception exx) {
sslContext = SSLContext.getInstance("TLS", provider);
}
}
}
sslContext.init(km, tm, new SecureRandom());
return sslContext;
}
/**
* Creates a SSLContext instance using the given information.
*
* @param truststore the full path to the truststore
* @param truststorePasswd the truststore password
* @param truststoreType the type of truststore (e.g., PKCS12, JKS)
* @param protocol the protocol to use for the SSL connection
*
* @return a SSLContext instance
* @throws java.security.KeyStoreException if any issues accessing the keystore
* @throws java.io.IOException for any problems loading the keystores
* @throws java.security.NoSuchAlgorithmException if an algorithm is found to be used but is unknown
* @throws java.security.cert.CertificateException if there is an issue with the certificate
* @throws java.security.UnrecoverableKeyException if the key is insufficient
* @throws java.security.KeyManagementException if unable to manage the key
*/
public static SSLContext createTrustSslContext(
final String truststore, final char[] truststorePasswd, final String truststoreType, final String protocol)
throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
UnrecoverableKeyException, KeyManagementException {
// prepare the truststore
final KeyStore trustStore = KeyStoreUtils.getTrustStore(truststoreType);
try (final InputStream trustStoreStream = new FileInputStream(truststore)) {
trustStore.load(trustStoreStream, truststorePasswd);
}
final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
// initialize the ssl context
final SSLContext ctx = SSLContext.getInstance(protocol);
ctx.init(new KeyManager[0], trustManagerFactory.getTrustManagers(), new SecureRandom());
return ctx;
}
private SSLContext createServerContext(String commonName,
SubjectAlternativeNameHolder subjectAlternativeNames)
throws GeneralSecurityException, IOException,
OperatorCreationException {
MillisecondsDuration duration = new MillisecondsDuration();
KeyStore ks = CertificateHelper.createServerCertificate(commonName,
subjectAlternativeNames, authority, caCert, caPrivKey);
KeyManager[] keyManagers = CertificateHelper.getKeyManagers(ks,
authority);
SSLContext result = CertificateHelper.newServerContext(keyManagers);
LOG.info("Impersonated {} in {}ms", commonName, duration);
return result;
}
public static SSLSocketFactory DefaultSSLSocketFactory() {
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream keyStoreFile = new FileInputStream(new File(SystemTools.keystore()));
String keyStorePassword = SystemTools.keystorePassword();
keyStore.load(keyStoreFile, keyStorePassword.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, keyStorePassword.toCharArray());
KeyManager[] keyManagers = kmf.getKeyManagers();
SSLContext ctx = SSLContext.getInstance(CommonValues.HttpsProtocal);
ctx.init(keyManagers, null, new SecureRandom());
return ctx.getSocketFactory();
} catch (Exception e) {
logger.debug(e.toString());
return AppVariables.defaultSSLSocketFactory;
}
}
static KeyManager[] fromJksKeyStore(Path keyStoreFile, char[] keyStorePassword)
throws NoSuchAlgorithmException, IOException, KeyStoreException, CertificateException,
UnrecoverableKeyException {
final KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE);
try (InputStream in = Files.newInputStream(keyStoreFile)) {
keyStore.load(in, keyStorePassword);
}
final KeyManagerFactory keyManagerFactory =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, keyStorePassword);
return keyManagerFactory.getKeyManagers();
}
/**
* Creates an SSLSocketFactory that supports only the specified protocols
* and ciphers.
*/
public static SSLSocketFactory getSSLSocketFactory(String protocol,
String[] sslEnabledProtocols,
String[] sslCipherSuites,
SecureRandom random,
TrustManager[] tms,
KeyManager[] kms)
throws NoSuchAlgorithmException, KeyManagementException
{
SSLContext sc = SSLContext.getInstance(protocol);
// System.out.println("Wanted protocol: " + protocol);
// System.out.println("Got protocol: " + sc.getProtocol());
sc.init(kms, tms, random);
SSLSocketFactory sf = sc.getSocketFactory();
if(null != sslEnabledProtocols
|| null != sslCipherSuites)
sf = new CustomSSLSocketFactory(sf,
sslEnabledProtocols,
sslCipherSuites);
return sf;
}
/**
* Retrieve the KeyManagers for the specified KeyStore.
*
* @param keyStore the KeyStore to retrieve KeyManagers from
* @param keyStorePassword the KeyStore password
* @param keyManagerAlgorithm key manager algorithm to use, or null to use the system default
* @param provider JCA provider to use, or null to use the system default
* @return KeyManagers for the specified KeyStore
*/
public static KeyManager[] getKeyManagers(KeyStore keyStore, String keyStorePassword, String keyManagerAlgorithm, String provider) {
if (keyManagerAlgorithm == null) {
keyManagerAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
}
try {
KeyManagerFactory kmf;
if (provider == null) {
kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
} else {
kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm, provider);
}
kmf.init(keyStore, keyStorePassword.toCharArray());
return kmf.getKeyManagers();
} catch (NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException | NoSuchProviderException e) {
throw new KeyStoreAccessException("Unable to get KeyManagers for KeyStore", e);
}
}
JSSEServer(CipherTestUtils cipherTest, int serverPort,
String protocol, String cipherSuite) throws Exception {
super(cipherTest);
this.serverPort = serverPort;
SSLContext serverContext = SSLContext.getInstance("TLS");
serverContext.init(new KeyManager[]{cipherTest.getServerKeyManager()},
new TrustManager[]{cipherTest.getServerTrustManager()},
CipherTestUtils.secureRandom);
SSLServerSocketFactory factory =
(SSLServerSocketFactory)serverContext.getServerSocketFactory();
serverSocket =
(SSLServerSocket) factory.createServerSocket(serverPort);
serverSocket.setEnabledProtocols(protocol.split(","));
serverSocket.setEnabledCipherSuites(cipherSuite.split(","));
CipherTestUtils.printInfo(serverSocket);
}
@Test
public void testCancelledPasswordOnSetCertificate() throws Exception {
assertNull(ApplicationKeyManagerFactory.getKeyStore());
ApplicationKeyManagerFactory instance = ApplicationKeyManagerFactory.getInstance();
KeyManager[] keyManagers = instance.getKeyManagers();
assertEquals(1, keyManagers.length);
assertTrue("", keyManagers[0] instanceof X509ExtendedKeyManager);
X509ExtendedKeyManager keyManager = (X509ExtendedKeyManager) keyManagers[0];
// verify that no certs are installed
assertNull(keyManager.getCertificateChain(ALIAS));
assertNull(keyManager.getClientAliases("RSA", null));
passwordProvider.cancelNextEntry();
ApplicationKeyManagerFactory.setKeyStore(keystoreFile.getAbsolutePath(), false);
// verify that no certs are installed
assertEquals(null, ApplicationKeyManagerFactory.getKeyStore());
assertNull(keyManager.getCertificateChain(ALIAS));
assertNull(keyManager.getClientAliases("RSA", null));
}
JSSEServer(CipherTestUtils cipherTest, int serverPort,
String protocol, String cipherSuite) throws Exception {
super(cipherTest);
this.serverPort = serverPort;
SSLContext serverContext = SSLContext.getInstance("TLS");
serverContext.init(new KeyManager[]{cipherTest.getServerKeyManager()},
new TrustManager[]{cipherTest.getServerTrustManager()},
CipherTestUtils.secureRandom);
SSLServerSocketFactory factory =
(SSLServerSocketFactory)serverContext.getServerSocketFactory();
serverSocket =
(SSLServerSocket) factory.createServerSocket(serverPort);
serverSocket.setEnabledProtocols(protocol.split(","));
serverSocket.setEnabledCipherSuites(cipherSuite.split(","));
CipherTestUtils.printInfo(serverSocket);
}
private SSLContext createServerContext(String commonName,
SubjectAlternativeNameHolder subjectAlternativeNames)
throws GeneralSecurityException, IOException,
OperatorCreationException {
MillisecondsDuration duration = new MillisecondsDuration();
KeyStore ks = CertificateHelper.createServerCertificate(commonName,
subjectAlternativeNames, authority, caCert, caPrivKey);
KeyManager[] keyManagers = CertificateHelper.getKeyManagers(ks,
authority);
SSLContext result = CertificateHelper.newServerContext(keyManagers);
LOG.info("Impersonated {} in {}ms", commonName, duration);
return result;
}
public static SSLParams getSslSocketFactory(InputStream[] certificates, InputStream bksFile, String password) {
SSLParams sslParams = new SSLParams();
try {
TrustManager[] trustManagers = prepareTrustManager(certificates);
KeyManager[] keyManagers = prepareKeyManager(bksFile, password);
SSLContext sslContext = SSLContext.getInstance("TLS");
X509TrustManager trustManager = null;
if (trustManagers != null) {
trustManager = new MyTrustManager(chooseTrustManager(trustManagers));
} else {
trustManager = new UnSafeTrustManager();
}
sslContext.init(keyManagers, new TrustManager[]{trustManager}, null);
sslParams.sSLSocketFactory = sslContext.getSocketFactory();
sslParams.trustManager = trustManager;
return sslParams;
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
throw new AssertionError(e);
}
}
/**
* @throws Exception if an error occurs
*/
@Before
public void setUp() throws Exception {
final URL url = getClass().getClassLoader().getResource("self-signed-cert.keystore");
final KeyStore keystore = KeyStore.getInstance("jks");
final char[] pwd = "nopassword".toCharArray();
keystore.load(url.openStream(), pwd);
final TrustManagerFactory trustManagerFactory = createTrustManagerFactory();
trustManagerFactory.init(keystore);
final TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
final KeyManagerFactory keyManagerFactory = createKeyManagerFactory();
keyManagerFactory.init(keystore, pwd);
final KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
final SSLContext serverSSLContext = SSLContext.getInstance("TLS");
serverSSLContext.init(keyManagers, trustManagers, null);
localServer_ = new LocalTestServer(serverSSLContext);
localServer_.start();
}
/**
* @throws Exception if an error occurs
*/
@Before
public void setUp() throws Exception {
final URL url = getClass().getClassLoader().getResource("insecureSSL.keystore");
final KeyStore keystore = KeyStore.getInstance("jks");
final char[] pwd = "nopassword".toCharArray();
keystore.load(url.openStream(), pwd);
final TrustManagerFactory trustManagerFactory = createTrustManagerFactory();
trustManagerFactory.init(keystore);
final TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
final KeyManagerFactory keyManagerFactory = createKeyManagerFactory();
keyManagerFactory.init(keystore, pwd);
final KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
final SSLContext serverSSLContext = SSLContext.getInstance("TLS");
serverSSLContext.init(keyManagers, trustManagers, null);
localServer_ = new LocalTestServer(serverSSLContext);
localServer_.start();
}
@Override
public void init(KeyManager[] kms, TrustManager[] tms, SecureRandom sr)
throws KeyManagementException {
this.kms = kms;
this.tms = tms;
context.init(kms, tms, sr);
}
public static KeyManager[] createKeyManagers(
final String file,
final char[] keyStorePasswd,
final char[] keyPasswd,
final String keyStoreType,
final String keyManagerFactoryAlgorithm
)
throws KeyStoreException, IOException, NoSuchAlgorithmException,
CertificateException, UnrecoverableKeyException
{
final KeyStore keyStore = loadStore(file, keyStoreType, keyStorePasswd);
KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance(keyManagerFactoryAlgorithm);
keyMgrFactory.init(keyStore, keyPasswd);
return keyMgrFactory.getKeyManagers();
}
public static KeyManager[] createKeyManagers(final TlsCertificateDefinition certToPresent)
throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
UnrecoverableKeyException {
if (certToPresent == null) {
return null;
}
final String password = certToPresent.getPassword();
final KeyStore clientCertStore = loadP12KeyStore(certToPresent.getPkcs12File(), password);
final KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
kmf.init(clientCertStore, password.toCharArray());
return kmf.getKeyManagers();
}
public SSLHandlerFactory(InboundWebsocketSSLConfiguration sslConfiguration) {
String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
if (algorithm == null) {
algorithm = "SunX509";
}
try {
KeyStore keyStore = getKeyStore(sslConfiguration.getKeyStore(), sslConfiguration.getKeyStorePass());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
keyManagerFactory.init(keyStore, sslConfiguration.getCertPass() != null ?
sslConfiguration.getCertPass().toCharArray() :
sslConfiguration.getKeyStorePass().toCharArray());
KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
TrustManager[] trustManagers = null;
if (sslConfiguration.getTrustStore() != null) {
this.needClientAuth = true;
KeyStore trustStore = getKeyStore(sslConfiguration.getTrustStore(),
sslConfiguration.getTrustStorePass());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(algorithm);
trustManagerFactory.init(trustStore);
trustManagers = trustManagerFactory.getTrustManagers();
}
serverContext = SSLContext.getInstance(protocol);
serverContext.init(keyManagers, trustManagers, null);
cipherSuites = sslConfiguration.getCipherSuites();
sslProtocols = sslConfiguration.getSslProtocols();
} catch (UnrecoverableKeyException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException | IOException ex) {
throw new IllegalArgumentException("Failed to initialize the server side SSLContext", ex);
}
}
public static KeyManager[] getKeyManagers(KeyStore keyStore,
Authority authority) throws NoSuchAlgorithmException,
NoSuchProviderException, UnrecoverableKeyException,
KeyStoreException {
String keyManAlg = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManAlg
/* , PROVIDER_NAME */);
kmf.init(keyStore, authority.password());
return kmf.getKeyManagers();
}
public static SSLContext newServerContext(KeyManager[] keyManagers)
throws NoSuchAlgorithmException, NoSuchProviderException,
KeyManagementException {
SSLContext result = newSSLContext();
SecureRandom random = new SecureRandom();
random.setSeed(System.currentTimeMillis());
result.init(keyManagers, null, random);
return result;
}
private void initializeSSLContext() throws GeneralSecurityException,
IOException {
KeyStore ks = loadKeyStore();
caCert = ks.getCertificate(authority.alias());
caPrivKey = (PrivateKey) ks.getKey(authority.alias(),
authority.password());
TrustManager[] trustManagers;
if (trustAllServers) {
trustManagers = InsecureTrustManagerFactory.INSTANCE
.getTrustManagers();
} else {
trustManagers = new TrustManager[] { new MergeTrustManager(ks) };
}
KeyManager[] keyManagers;
if (sendCerts) {
keyManagers = CertificateHelper.getKeyManagers(ks, authority);
} else {
keyManagers = new KeyManager[0];
}
sslContext = CertificateHelper.newClientContext(keyManagers,
trustManagers);
SSLEngine sslEngine = sslContext.createSSLEngine();
if (!tryHostNameVerificationJava7(sslEngine)) {
LOG.warn("Host Name Verification is not supported, causes insecure HTTPS connection to upstream servers.");
}
}
private SSLContext getCustomSslContext(
final TrustManagerFactory trustManagerFactory,
final Optional<KeyManagerFactory> keyManagerFactory)
throws GeneralSecurityException {
final KeyManager[] km = keyManagerFactory.map(KeyManagerFactory::getKeyManagers).orElse(null);
final TrustManager[] tm = trustManagerFactory.getTrustManagers();
final SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(km, tm, createSecureRandom());
return sslContext;
}
private KeyManager[] buildKeyManagers() throws GeneralSecurityException, IOException, OperatorCreationException {
if (Objects.nonNull(this.keyStore)) {
if (!this.keyStore.toFile().exists()) {
TlsUtils.create()
.generateKeyStoreWithSelfSignedCertificate(this.address, this.keyStore, this.keyStorePassword);
}
return SSLKeyStoreLoader.fromJksKeyStore(this.keyStore, this.keyStorePassword);
} else {
return SSLKeyStoreLoader.fromPemKeyFile(this.key, this.certificate);
}
}
public static SSLSocketFactory getSslSocketFactory(InputStream[] certificates, InputStream bksFile, String password) {
try {
TrustManager[] trustManagers = prepareTrustManager(certificates);
KeyManager[] keyManagers = prepareKeyManager(bksFile, password);
SSLContext sslContext = SSLContext.getInstance(SSL.DEFAULT_PROTOCOL);
sslContext.init(keyManagers, new TrustManager[]{new MyTrustManager(chooseTrustManager(trustManagers))}, new SecureRandom());
return sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
} catch (KeyManagementException e2) {
throw new AssertionError(e2);
} catch (KeyStoreException e3) {
throw new AssertionError(e3);
}
}
/**
* Load for getting KeyManager[] from this model
* @return KeyManager for Client Certificate
* @throws Exception:
* - IOException
* - KeyStoreException
* - CertificateException
* - NoSuchAlgorithmException
* - UnrecoverableKeyException
*/
public KeyManager[] load() throws Exception {
// Load KeyStore
FileInputStream fis = new FileInputStream(path);
KeyStore keyStore = KeyStore.getInstance(type.getText());
keyStore.load(fis, storePassword.toCharArray());
fis.close();
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keyStore, keyPassword.toCharArray());
return kmf.getKeyManagers();
}
/**
* Returns one key manager for each type of key material.
*/
@Override
protected KeyManager[] engineGetKeyManagers() {
if (!isInitialized) {
throw new IllegalStateException(
"KeyManagerFactoryImpl is not initialized");
}
return new KeyManager[] { keyManager };
}
private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
try {
if (bksFile == null || password == null) return null;
KeyStore clientKeyStore = KeyStore.getInstance("BKS");
clientKeyStore.load(bksFile, password.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(clientKeyStore, password.toCharArray());
return kmf.getKeyManagers();
} catch (Exception e) {
Log.e("net","Https#prepareKeyManager error",e);
}
return null;
}
private X509ExtendedKeyManager chooseKeyManager(KeyManager[] kms)
throws KeyManagementException {
for (int i = 0; kms != null && i < kms.length; i++) {
KeyManager km = kms[i];
if (!(km instanceof X509KeyManager)) {
continue;
}
if (OpenJSSE.isFIPS()) {
// In FIPS mode, require that one of OpenJSSE's own keymanagers
// is used. Otherwise, we cannot be sure that only keys from
// the FIPS token are used.
if ((km instanceof X509KeyManagerImpl)
|| (km instanceof SunX509KeyManagerImpl)) {
return (X509ExtendedKeyManager)km;
} else {
// throw exception, we don't want to silently use the
// dummy keymanager without telling the user.
throw new KeyManagementException
("FIPS mode: only OpenJSSE KeyManagers may be used");
}
}
if (km instanceof X509ExtendedKeyManager) {
return (X509ExtendedKeyManager)km;
}
if (SSLLogger.isOn && SSLLogger.isOn("ssl,sslctx")) {
SSLLogger.warning(
"X509KeyManager passed to SSLContext.init(): need an " +
"X509ExtendedKeyManager for SSLEngine use");
}
return new AbstractKeyManagerWrapper((X509KeyManager)km);
}
// nothing found, return a dummy X509ExtendedKeyManager
return DummyX509KeyManager.INSTANCE;
}