Java Code Examples for java.security.KeyStore

The following examples show how to use java.security.KeyStore. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: localization_nifi   Source File: TlsHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static String writeKeyStore(KeyStore keyStore, OutputStreamFactory outputStreamFactory, File file, String password, boolean generatedPassword) throws IOException, GeneralSecurityException {
    try (OutputStream fileOutputStream = outputStreamFactory.create(file)) {
        keyStore.store(fileOutputStream, password.toCharArray());
    } catch (IOException e) {
        if (e.getMessage().toLowerCase().contains(ILLEGAL_KEY_SIZE) && !isUnlimitedStrengthCryptographyEnabled()) {
            if (generatedPassword) {
                file.delete();
                String truncatedPassword = password.substring(0, 7);
                try (OutputStream fileOutputStream = outputStreamFactory.create(file)) {
                    keyStore.store(fileOutputStream, truncatedPassword.toCharArray());
                }
                logTruncationWarning(file);
                return truncatedPassword;
            } else {
                throw new GeneralSecurityException("Specified password for " + file + " too long to work without unlimited JCE policy installed."
                        + System.lineSeparator() + "Please see " + JCE_URL);
            }
        } else {
            throw e;
        }
    }
    return password;
}
 
Example 2
Source Project: MiBandDecompiled   Source File: MySSLSocketFactory.java    License: Apache License 2.0 6 votes vote down vote up
public static KeyStore getKeystore()
    {
        KeyStore keystore1 = KeyStore.getInstance(KeyStore.getDefaultType());
        KeyStore keystore = keystore1;
        keystore.load(null, null);
        return keystore;
        Throwable throwable;
        throwable;
        Throwable throwable1;
        keystore = null;
        throwable1 = throwable;
_L2:
        throwable1.printStackTrace();
        return keystore;
        throwable1;
        if (true) goto _L2; else goto _L1
_L1:
    }
 
Example 3
Source Project: nifi   Source File: TlsCertificateAuthorityService.java    License: Apache License 2.0 6 votes vote down vote up
private static Server createServer(Handler handler, int port, KeyStore keyStore, String keyPassword) throws Exception {
    Server server = new Server();

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setIncludeProtocols(CertificateUtils.getHighestCurrentSupportedTlsProtocolVersion());
    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyManagerPassword(keyPassword);

    // Need to set SslContextFactory's endpointIdentificationAlgorithm to null; this is a server,
    // not a client.  Server does not need to perform hostname verification on the client.
    // Previous to Jetty 9.4.15.v20190215, this defaulted to null, and now defaults to "HTTPS".
    sslContextFactory.setEndpointIdentificationAlgorithm(null);

    HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig));
    sslConnector.setPort(port);

    server.addConnector(sslConnector);
    server.setHandler(handler);

    return server;
}
 
Example 4
Source Project: datawave   Source File: DatawaveCertRolesLoginModuleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    callbackHandler = new MockCallbackHandler("Alias: ", "Certificate: ");
    
    HashMap<String,String> sharedState = new HashMap<>();
    HashMap<String,String> options = new HashMap<>();
    options.put("rolesProperties", "roles.properties");
    options.put("principalClass", "datawave.security.authorization.DatawavePrincipal");
    options.put("verifier", MockDatawaveCertVerifier.class.getName());
    
    loginModule = new DatawaveCertRolesLoginModule();
    loginModule.initialize(new Subject(), callbackHandler, sharedState, options);
    
    KeyStore truststore = KeyStore.getInstance("PKCS12");
    truststore.load(getClass().getResourceAsStream("/ca.pkcs12"), "secret".toCharArray());
    KeyStore keystore = KeyStore.getInstance("PKCS12");
    keystore.load(getClass().getResourceAsStream("/testUser.pkcs12"), "secret".toCharArray());
    testUserCert = (X509Certificate) keystore.getCertificate("testuser");
}
 
Example 5
Source Project: CapturePacket   Source File: TrustUtil.java    License: MIT License 6 votes vote down vote up
/**
 * Extracts the {@link KeyStore.TrustedCertificateEntry}s from the specified KeyStore. All other entry
 * types, including private keys, will be ignored.
 *
 * @param trustStore keystore containing trusted certificate entries
 * @return the trusted certificate entries in the specified keystore
 */
public static List<X509Certificate> extractTrustedCertificateEntries(KeyStore trustStore) {
    try {
        Enumeration<String> aliases = trustStore.aliases();
        List<String> keyStoreAliases = Collections.list(aliases);

        List<X509Certificate> trustedCertificates = new ArrayList<>(keyStoreAliases.size());

        for (String alias : keyStoreAliases) {
            if (trustStore.entryInstanceOf(alias, KeyStore.TrustedCertificateEntry.class)) {
                Certificate certificate = trustStore.getCertificate(alias);
                if (!(certificate instanceof X509Certificate)) {
                    log.debug("Skipping non-X509Certificate in KeyStore. Certificate type: {}", certificate.getType());
                    continue;
                }

                trustedCertificates.add((X509Certificate) certificate);
            }
        }

        return trustedCertificates;
    } catch (KeyStoreException e) {
        throw new KeyStoreAccessException("Error occurred while retrieving trusted CAs from KeyStore", e);
    }
}
 
Example 6
Source Project: carbon-device-mgt   Source File: JWTClientUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static KeyStore loadKeyStore(final File keystoreFile, final String password, final String keyStoreType)
		throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
	if (null == keystoreFile) {
		throw new IllegalArgumentException("Keystore url may not be null");
	}
	URI keystoreUri = keystoreFile.toURI();
	URL keystoreUrl = keystoreUri.toURL();
	KeyStore keystore = KeyStore.getInstance(keyStoreType);
	InputStream is = null;
	try {
		is = keystoreUrl.openStream();
		keystore.load(is, null == password ? null : password.toCharArray());
	} finally {
		if (null != is) {
			is.close();
		}
	}
	return keystore;
}
 
Example 7
Source Project: crate   Source File: SslConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
static X509Certificate[] getCertificateChain(KeyStore keyStore) {
    ArrayList<X509Certificate> certs = new ArrayList<>();
    try {
        Enumeration<String> aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            if (keyStore.isKeyEntry(alias)) {
                Certificate[] certificateChain = keyStore.getCertificateChain(alias);
                if (certificateChain != null) {
                    for (Certificate certificate : certificateChain) {
                        certs.add((X509Certificate) certificate);
                    }
                }

            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return certs.toArray(new X509Certificate[0]);
}
 
Example 8
Source Project: protools   Source File: ToolHTTPS.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获得KeyStore
 *
 * @param keyStorePath
 *         密钥库路径
 * @param password
 *         密码
 *
 * @return KeyStore 密钥库
 *
 * @throws Exception
 */
static KeyStore getKeyStore(String keyStorePath, String password) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {

    // 实例化密钥库
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

    // 获得密钥库文件流
    FileInputStream is = new FileInputStream(keyStorePath);

    // 加载密钥库
    ks.load(is, password.toCharArray());

    // 关闭密钥库文件流
    is.close();

    return ks;
}
 
Example 9
Source Project: letv   Source File: PoolingClientConnectionManager.java    License: Apache License 2.0 6 votes vote down vote up
public static HttpClient get() {
    HttpParams httpParams = new BasicHttpParams();
    ConnManagerParams.setTimeout(httpParams, 3000);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(30));
    ConnManagerParams.setMaxTotalConnections(httpParams, 30);
    HttpClientParams.setRedirecting(httpParams, true);
    HttpProtocolParams.setUseExpectContinue(httpParams, true);
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);
    HttpConnectionParams.setSoTimeout(httpParams, 2000);
    HttpConnectionParams.setConnectionTimeout(httpParams, 2000);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme(IDataSource.SCHEME_HTTP_TAG, PlainSocketFactory.getSocketFactory(), 80));
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        schemeRegistry.register(new Scheme(IDataSource.SCHEME_HTTPS_TAG, sf, 443));
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, schemeRegistry), httpParams);
}
 
Example 10
private static KeyManagerFactory createKeyManagerFactory(
	final String clientCertificateFileName, final String clientKeyFileName, final String clientKeyPassword) 
	throws InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException
{
	// Creates a key manager factory
	// Load and create the client certificate
	final X509Certificate clientCertificate = createX509CertificateFromFile(clientCertificateFileName);	
	// Load the private client key
	final PrivateKey privateKey = createPrivateKeyFromPemFile(clientKeyFileName);
	// Client key and certificate are sent to server
	final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
	keyStore.load(null, null);
	keyStore.setCertificateEntry("certificate", clientCertificate);
	keyStore.setKeyEntry("private-key", privateKey, 
		clientKeyPassword.toCharArray(),
		new Certificate[] { clientCertificate });
	final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	keyManagerFactory.init(keyStore, clientKeyPassword.toCharArray());
	
	return keyManagerFactory;
}
 
Example 11
Source Project: java   Source File: OpenIDConnectAuthenticationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testTokenExpiredHasExpired()
    throws InvalidKeySpecException, NoSuchAlgorithmException, Exception {
  OpenIDConnectAuthenticator oidcAuth = new OpenIDConnectAuthenticator();
  Map<String, Object> config = new HashMap<String, Object>();

  KeyStore ks = KeyStore.getInstance("PKCS12");
  ks.load(new FileInputStream(OIDC_KS_PATH), OIDC_KS_PASSWORD);

  String jwt =
      TestUtils.generateJWT(
          "someuser",
          "https://some.domain.nowhere",
          (PrivateKey) ks.getKey("oidc-sig", OIDC_KS_PASSWORD),
          TestUtils.DateOptions.Past);

  config.put(OpenIDConnectAuthenticator.OIDC_ID_TOKEN, jwt);

  assertTrue(oidcAuth.isExpired(config));
}
 
Example 12
Source Project: MaxKey   Source File: KeyStoreKeyFactory.java    License: Apache License 2.0 6 votes vote down vote up
public KeyPair getKeyPair(String alias, char[] password) {
	try {
		synchronized (lock) {
			if (store == null) {
				synchronized (lock) {
					store = KeyStore.getInstance("jks");
					store.load(resource.getInputStream(), this.password);
				}
			}
		}
		RSAPrivateCrtKey key = (RSAPrivateCrtKey) store.getKey(alias, password);
		RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
		PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(spec);
		return new KeyPair(publicKey, key);
	}
	catch (Exception e) {
		throw new IllegalStateException("Cannot load keys from store: " + resource, e);
	}
}
 
Example 13
Source Project: olat   Source File: LDAPLoginModule.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Checks if SSL certification is know and accepted by Java JRE.
 * 
 * @param dayFromNow
 *            Checks expiration
 * @return true Certification accepted, false No valid certification
 * @throws Exception
 */
private static boolean checkServerCertValidity(final int daysFromNow) {
    KeyStore keyStore;
    try {
        keyStore = KeyStore.getInstance(getTrustStoreType());
        keyStore.load(new FileInputStream(getTrustStoreLocation()), (getTrustStorePwd() != null) ? getTrustStorePwd().toCharArray() : null);
        final Enumeration<String> aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            final String alias = aliases.nextElement();
            final Certificate cert = keyStore.getCertificate(alias);
            if (cert instanceof X509Certificate) {
                return isCertificateValid((X509Certificate) cert, daysFromNow);
            }
        }
    } catch (final Exception e) {
        return false;
    }
    return false;
}
 
Example 14
Source Project: carbon-apimgt   Source File: TokenGenTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJWTx5tEncoding() throws Exception {
    //Read public certificat
    InputStream inputStream = new FileInputStream("src/test/resources/wso2carbon.jks");
    KeyStore keystore = KeyStore.getInstance("JKS");
    char[] pwd = "wso2carbon".toCharArray();
    keystore.load(inputStream, pwd);
    Certificate cert = keystore.getCertificate("wso2carbon");

    //Generate JWT header using the above certificate
    String header = APIUtil.generateHeader(cert, "SHA256withRSA");

    //Get the public certificate's thumbprint and base64url encode it
    byte[] der = cert.getEncoded();
    MessageDigest digestValue = MessageDigest.getInstance("SHA-1");
    digestValue.update(der);
    byte[] digestInBytes = digestValue.digest();
    String publicCertThumbprint = hexify(digestInBytes);
    String encodedThumbprint = java.util.Base64.getUrlEncoder()
            .encodeToString(publicCertThumbprint.getBytes("UTF-8"));
    //Check if the encoded thumbprint get matched with JWT header's x5t
    Assert.assertTrue(header.contains(encodedThumbprint));
}
 
Example 15
public static void main(String[] args) throws Exception {
    KeyStore ks = KeyStore.getInstance("JKS");
    FileInputStream fis = new FileInputStream(
            new File(System.getProperty("test.src"),
                    "../tools/jarsigner/JarSigning.keystore"));
    ks.load(fis, "bbbbbb".toCharArray());

    PrivateKey pk = (PrivateKey) ks.getKey("c", "bbbbbb".toCharArray());
    Certificate cert = ks.getCertificate("c");

    ks = KeyStore.getInstance("Windows-MY");
    ks.load(null, null);

    ks.setKeyEntry("8143913", pk, null, new Certificate[]{cert});
    ks.deleteEntry("8143913");
}
 
Example 16
Source Project: jdk8u60   Source File: PKCS12KeyStore.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Determines if the keystore {@code Entry} for the specified
 * {@code alias} is an instance or subclass of the specified
 * {@code entryClass}.
 *
 * @param alias the alias name
 * @param entryClass the entry class
 *
 * @return true if the keystore {@code Entry} for the specified
 *          {@code alias} is an instance or subclass of the
 *          specified {@code entryClass}, false otherwise
 *
 * @since 1.5
 */
@Override
public boolean
    engineEntryInstanceOf(String alias,
                          Class<? extends KeyStore.Entry> entryClass)
{
    if (entryClass == KeyStore.TrustedCertificateEntry.class) {
        return engineIsCertificateEntry(alias);
    }

    Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
    if (entryClass == KeyStore.PrivateKeyEntry.class) {
        return (entry != null && entry instanceof PrivateKeyEntry);
    }
    if (entryClass == KeyStore.SecretKeyEntry.class) {
        return (entry != null && entry instanceof SecretKeyEntry);
    }
    return false;
}
 
Example 17
@Test
public void testSignAndVerifyValid() throws Exception {
    Protos.PaymentRequest.Builder paymentRequest = minimalPaymentRequest().toBuilder();

    // Sign
    KeyStore keyStore = X509Utils
            .loadKeyStore("JKS", "password", getClass().getResourceAsStream("test-valid-cert"));
    PrivateKey privateKey = (PrivateKey) keyStore.getKey("test-valid", "password".toCharArray());
    X509Certificate clientCert = (X509Certificate) keyStore.getCertificate("test-valid");
    PaymentProtocol.signPaymentRequest(paymentRequest, new X509Certificate[]{clientCert}, privateKey);

    // Verify
    PkiVerificationData verificationData = PaymentProtocol.verifyPaymentRequestPki(paymentRequest.build(), caStore);
    assertNotNull(verificationData);
    assertEquals(caCert, verificationData.rootAuthority.getTrustedCert());
}
 
Example 18
/**
 * 
 * @param pinNumber pin
 * @param keyStoreType PKSC12 or JKS
 * @return keystore
 */
private KeyStore getKeyStoreWithType(String pinNumber, String keyStoreType) {
    KeyStore result = null;
    try {
        result = KeyStore.getInstance(keyStoreType);
        char[] pwd = pinNumber == null ? null : pinNumber.toCharArray();
        InputStream is = new FileInputStream(this.fileKeyStore);
        result.load(is, pwd);
    } catch (Throwable error) {
        throw new KeyStoreLoaderException(coreMessagesBundle.getString("error.keystore.from.file"), error);
    }
    return result;
}
 
Example 19
private SSLSocketFactory createSSLSocketFactory(final InputStream is, final String passphrase) throws Exception
{
  final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  ks.load(is, passphrase.toCharArray());
  is.close();
  final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  tmf.init(ks);
  final X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
  final SSLContext context = SSLContext.getInstance("TLS");
  context.init(null, new TrustManager[] { defaultTrustManager}, null);
  return context.getSocketFactory();
}
 
Example 20
Source Project: HolandaCatalinaFw   Source File: HttpsServer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates the key managers required to initiate the {@link SSLContext}.
 * @return {@link KeyManager} array that will be used to initiate the {@link SSLContext}.
 * @throws Exception Key managers creation exception
 */
protected KeyManager[] createKeyManagers() throws Exception {
    KeyStore keyStore = getProvider() == null ? KeyStore.getInstance(getKeyType()) : KeyStore.getInstance(getKeyType(), getProvider());
    InputStream keyStoreIS = new FileInputStream(getKeystoreFilePath().toFile());
    try {
        keyStore.load(keyStoreIS, getKeystorePassword().toCharArray());
    } finally {
        if (keyStoreIS != null) {
            keyStoreIS.close();
        }
    }
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, getKeyPassword().toCharArray());
    return kmf.getKeyManagers();
}
 
Example 21
Source Project: cloudstack   Source File: CertificateHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static KeyStore loadKeystore(final byte[] ksData, final String storePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
    Preconditions.checkNotNull(ksData, "Keystore data cannot be null");
    final KeyStore ks = KeyStore.getInstance("JKS");
    try (final ByteArrayInputStream is = new ByteArrayInputStream(ksData)) {
        ks.load(is, storePassword != null ? storePassword.toCharArray() : null);
    }

    return ks;
}
 
Example 22
Source Project: jdk8u_jdk   Source File: TestTLS12.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static KeyStore readTestKeyStore() throws Exception {
    File file = new File(System.getProperty("test.src", "."), "keystore");
    InputStream in = new FileInputStream(file);
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(in, "passphrase".toCharArray());
    in.close();
    return ks;
}
 
Example 23
public static KeyStore.Entry getKeyEntry(String keystorePath, String storePass, String keyName, String keyPass)
        throws Exception {
    char[] keyPw = null;
    KeyStore.PasswordProtection passwordProtection = null;

    try {
        KeyStore ks = loadKeyStore(keystorePath, storePass);
        keyPw = PasswordObfuscator.getInstance().decodeAliasPassword(keystorePath, keyName, keyPass);
        passwordProtection = new KeyStore.PasswordProtection(keyPw);
        return ks.getEntry(keyName, passwordProtection);
    } finally {
        if (keyPw != null) PasswordObfuscator.flush(keyPw);
        if (passwordProtection != null) passwordProtection.destroy();
    }
}
 
Example 24
Source Project: datacollector   Source File: FTPRemoteConnector.java    License: Apache License 2.0 5 votes vote down vote up
private void setFtpsUserKeyManagerOrTrustManager(
    KeyStore keystore,
    String fileConfigName,
    String keyStorePassword,
    boolean isKeyStore, // or truststore
    List<Stage.ConfigIssue> issues,
    ConfigIssueContext context,
    Label group
) {
  try {
    if (isKeyStore) {
      FtpsFileSystemConfigBuilder.getInstance().setKeyManager(
          options,
          KeyManagerUtils.createClientKeyManager(keystore, null, keyStorePassword)
      );
    } else {
      FtpsFileSystemConfigBuilder.getInstance().setTrustManager(
          options,
          TrustManagerUtils.getDefaultTrustManager(keystore)
      );
    }
  } catch (GeneralSecurityException e) {
    issues.add(context.createConfigIssue(group.getLabel(),
        fileConfigName,
        Errors.REMOTE_15,
        isKeyStore ? "key" : "trust",
        e.getMessage(),
        e
    ));
  }
}
 
Example 25
public int loadPKCS12Certificate(String filename, String ksPassword)
throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException {
    // Open the file
    InputStream is = new FileInputStream(filename);
    if (is == null)
        throw new FileNotFoundException(filename + " could not be found");
    
    // create the keystore
    
    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(is, ksPassword == null ? null : ksPassword.toCharArray());
    return addKeyStore(ks, filename);
}
 
Example 26
Source Project: wind-im   Source File: SslKeyStore.java    License: Apache License 2.0 5 votes vote down vote up
public static KeyStore getKeyStore() {
	KeyStore ks = null;
	try {
		ks = KeyStore.getInstance("JKS");
		ks.load(new ByteArrayInputStream(JKS_CERT_BYTES), getKeyStorePassword());
	} catch (Exception ex) {
		throw new RuntimeException("Failed to load SSL key store.", ex);
	}
	return ks;
}
 
Example 27
Source Project: scipio-erp   Source File: KeyStoreUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static KeyStore getComponentKeyStore(String componentName, String keyStoreName) throws IOException, GeneralSecurityException, GenericConfigException {
    ComponentConfig.KeystoreInfo ks = ComponentConfig.getKeystoreInfo(componentName, keyStoreName);
    // SCIPIO: Prevent confusing NPE
    if (ks == null) {
        throw new IOException("Could not get keystore info for given keystore; not found");
    }
    return getStore(ks.createResourceHandler().getURL(), ks.getPassword(), ks.getType());
}
 
Example 28
public DataUnsealer initUnsealing() throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, IntegrationModuleException {
   Security.addProvider(new BouncyCastleProvider());
   KeyStore caCertificatesKeystore = KeyManager.getKeyStore(this.getCaCertificateKeystoreIs(), this.propertyHandler.getProperty("LOCAL_CA_CERTIFICATES_STORE_TYPE"), this.propertyHandler.getProperty("CAKEYSTORE_PASSWORD").toCharArray());
   Map<String, PrivateKey> clientDecryptionKeys = KeyManager.getDecryptionKeys(this.getKeyStore(), DEFAULT_PASSWORD);
   Iterator var4 = clientDecryptionKeys.keySet().iterator();

   while(var4.hasNext()) {
      String key = (String)var4.next();
      LOG.debug("Key Available for decryption : " + key);
   }

   DataUnsealer dataUnsealer = DataUnsealerBuilder.newBuilder().addOCSPPolicy(OCSPPolicy.NONE).addSigningPolicy(caCertificatesKeystore, SigningPolicy.EHEALTH_CERT, SigningPolicy.EID).addPublicKeyPolicy(EncryptionPolicy.KNOWN_RECIPIENT, EncryptionCredentials.from(clientDecryptionKeys)).build();
   return dataUnsealer;
}
 
Example 29
Source Project: Focus   Source File: HttpsUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
public MyTrustManager(X509TrustManager localTrustManager) throws NoSuchAlgorithmException, KeyStoreException
{
    TrustManagerFactory var4 = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    var4.init((KeyStore) null);
    defaultTrustManager = chooseTrustManager(var4.getTrustManagers());
    this.localTrustManager = localTrustManager;
}
 
Example 30
Source Project: jdk8u60   Source File: TestJKSWithSecretKey.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    SecretKey key = new SecretKeySpec(new byte[8], "DES");

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, passwd);

    try {
        // store the SecretKey
        ks.setKeyEntry("test_encrypt_key", key, passwd, null);
        throw new Exception("Should throw KeyStoreException when " +
            "storing SecretKey into JKS keystores");
    } catch (KeyStoreException kse) {
        // expected exception thrown; swallow
    }
}