java.security.KeyStore Java Examples

The following examples show how to use java.security.KeyStore. 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: PKCS12KeyStore.java    From jdk8u60 with 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 #2
Source File: SslConfiguration.java    From crate with 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 #3
Source File: KeyStoreKeyFactory.java    From MaxKey with 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 #4
Source File: ToolHTTPS.java    From protools with 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 #5
Source File: JWTClientUtil.java    From carbon-device-mgt with 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 #6
Source File: TrustUtil.java    From CapturePacket with 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 #7
Source File: DatawaveCertRolesLoginModuleTest.java    From datawave with 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 #8
Source File: TlsCertificateAuthorityService.java    From nifi with 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 #9
Source File: LDAPLoginModule.java    From olat with 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 #10
Source File: PoolingClientConnectionManager.java    From letv with 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 #11
Source File: TokenGenTest.java    From carbon-apimgt with 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 #12
Source File: TlsHelper.java    From localization_nifi with 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 #13
Source File: SecurityHelper.java    From MQTT-Essentials-A-Lightweight-IoT-Protocol with MIT License 6 votes vote down vote up
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 #14
Source File: CastError.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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 #15
Source File: PaymentProtocolTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@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 #16
Source File: OpenIDConnectAuthenticationTest.java    From java with 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 #17
Source File: KSTrustedCertificateEntryTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Test for <code>SecretKeyEntry(SecretKey secretKey, Set<Attribute> attributes)</code>
 * constructor
 * Assertion: throws NullPointerException when attributes is null
 */
public void testSecretKeyEntry_nullAttributes() {
    Certificate cert = new MyCertificate("TEST", new byte[10]);
    try {
        new KeyStore.TrustedCertificateEntry(cert, null /* attributes */);
        fail("NullPointerException must be thrown when attributes is null");
    } catch(NullPointerException expected) {
    }
}
 
Example #18
Source File: WLTrustHandler.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static synchronized void removeFromTrustStore(String url) throws GeneralSecurityException, IOException {
    FileObject root = FileUtil.getConfigRoot();
    FileObject ts = root.getFileObject(TRUST_STORE_PATH);
    if (ts == null) {
        return;
    }

    char[] password = Keyring.read(TRUST_PASSWORD_KEY);

    KeyStore keystore = KeyStore.getInstance("JKS"); // NOI18N
    InputStream is = new BufferedInputStream(ts.getInputStream());
    try {
        keystore.load(is, password);
    } catch (IOException ex) {
        LOGGER.log(Level.INFO, null, ex);
        return;
    } finally {
        is.close();
    }

    keystore.deleteEntry(url);

    OutputStream out = new BufferedOutputStream(ts.getOutputStream());
    try {
        keystore.store(out, password);
    } finally {
        out.close();
    }
}
 
Example #19
Source File: TestJKSWithSecretKey.java    From jdk8u60 with 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
    }
}
 
Example #20
Source File: BeIDCredential.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public KeyStore getKeyStore() throws TechnicalConnectorException {
   if (this.keyStore == null) {
      this.keyStore = KeyStoreFactory.getKeyStore();
   }

   return this.keyStore;
}
 
Example #21
Source File: TrustManagerBuilder.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
/**
 * Add certificates from the default trust store
 * @return this
 * @throws Exception In case anything explodes.
 */
public TrustManagerBuilder addBuiltinCertificates() throws Exception {
  TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  factory.init((KeyStore) null);

  X509TrustManager builtInTrustManager = findFirstX509TrustManager(factory);
  if (builtInTrustManager != null) {
    addFromTrustManager(builtInTrustManager);
  }
  return this;
}
 
Example #22
Source File: JCEKSKeyProvider.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
@Activate
public void init(Configuration config) throws GeneralSecurityException, IOException {
    this.config = config;
    // init keystore
    keystore = KeyStore.getInstance("JCEKS");
    InputStream readStream = new FileInputStream(config.path());
    keystore.load(readStream, config.password().toCharArray());
    readStream.close();

    aliasIds = new HashMap<>();
    CRC32 crc = new CRC32();
    for (String alias : config.secondaryAliases()) {
        crc.update(alias.getBytes(StandardCharsets.UTF_8));
        Object prior = aliasIds.put(crc.getValue(), alias);
        if (prior != null) {
            throw new GeneralSecurityException(
                    "Two aliases are being used that generate the same CRC-32 hash, please correct");
        }
        crc.reset();
    }

    crc.update(config.primaryAlias().getBytes(StandardCharsets.UTF_8));
    primaryId = crc.getValue();
    if (aliasIds.containsKey(primaryId)) {
        throw new GeneralSecurityException(String.format(
                "The primary alias %s is either the same as or has the same CRC-32 hash as %s in the secondary aliases, please correct",
                config.primaryAlias(), aliasIds.get(primaryId)));
    }

    aliasIds.put(primaryId, config.primaryAlias());
    crc.reset();
}
 
Example #23
Source File: EncryptionUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #24
Source File: BadPem.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 {
    String ks = System.getProperty("test.src", ".")
            + "/../../ssl/etc/keystore";
    String pass = "passphrase";
    String alias = "dummy";

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(ks), pass.toCharArray());
    byte[] cert = keyStore.getCertificate(alias).getEncoded();

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    PrintStream pout = new PrintStream(bout);
    byte[] CRLF = new byte[] {'\r', '\n'};
    pout.println(X509Factory.BEGIN_CERT);
    for (int i=0; i<cert.length; i += 48) {
        int blockLen = (cert.length > i + 48) ? 48 : (cert.length - i);
        pout.println("!" + Base64.getEncoder()
                .encodeToString(Arrays.copyOfRange(cert, i, i + blockLen)));
    }
    pout.println(X509Factory.END_CERT);

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    try {
        cf.generateCertificate(new ByteArrayInputStream(bout.toByteArray()));
        throw new Exception("Should fail");
    } catch (CertificateException e) {
        // Good
    }
}
 
Example #25
Source File: P12SecretKey.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private void run(String keystoreType) throws Exception {
    char[] pw = "password".toCharArray();
    KeyStore ks = KeyStore.getInstance(keystoreType);
    ks.load(null, pw);

    KeyGenerator kg = KeyGenerator.getInstance("AES");
    kg.init(128);
    SecretKey key = kg.generateKey();

    KeyStore.SecretKeyEntry ske = new KeyStore.SecretKeyEntry(key);
    KeyStore.ProtectionParameter kspp = new KeyStore.PasswordProtection(pw);
    ks.setEntry(ALIAS, ske, kspp);

    File ksFile = File.createTempFile("test", ".test");
    try (FileOutputStream fos = new FileOutputStream(ksFile)) {
        ks.store(fos, pw);
        fos.flush();
    }

    // now see if we can get it back
    try (FileInputStream fis = new FileInputStream(ksFile)) {
        KeyStore ks2 = KeyStore.getInstance(keystoreType);
        ks2.load(fis, pw);
        KeyStore.Entry entry = ks2.getEntry(ALIAS, kspp);
        SecretKey keyIn = ((KeyStore.SecretKeyEntry)entry).getSecretKey();
        if (Arrays.equals(key.getEncoded(), keyIn.getEncoded())) {
            System.err.println("OK: worked just fine with " + keystoreType +
                               " keystore");
        } else {
            System.err.println("ERROR: keys are NOT equal after storing in "
                               + keystoreType + " keystore");
        }
    }
}
 
Example #26
Source File: SslSocketFactory.java    From GreasySpoon with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Create a new Keystore with given password
 * @param keystoreName The key store to create
 * @param pwd password to assign to the key store
 * @return KeyStore created key store
 * @throws Exception
 */
public static KeyStore createKeyStore(String keystoreName, String pwd) throws Exception {
	String cn = HttpServer.bounded_ip.equals("")?InetAddress.getLocalHost().getHostName():HttpServer.bounded_ip;
	KeyStore _ks = KeyStore.getInstance(KEYSTORETYPE);
	_ks.load(null, pwd.toCharArray());
	X509CertificateGenerator.generateKeyFor(_ks,cn, HttpServer.adminmail,pwd);
	saveKeystore(_ks,keystoreName,pwd);
	return _ks;
}
 
Example #27
Source File: ApiEngine.java    From rnd-android-wear-tesla with MIT License 5 votes vote down vote up
public ApiEngine(KeyStore keystore, File file, int k, int l, String userAgent) {
    final HttpClientBuilder httpclientbuilder = HttpClients.custom();
    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(k);
    requestConfigBuilder.setSocketTimeout(l);
    requestConfigBuilder.setCookieSpec("best-match");
    httpclientbuilder.setDefaultRequestConfig(requestConfigBuilder.build());
    httpclientbuilder.setUserAgent(userAgent);

    cookieStore = null;
    if (file != null && file.exists() && file.isDirectory()) {
        File cookieStoreFile = new File(file, "cookie.store");
        if (cookieStoreFile.exists() && cookieStoreFile.canRead()) {
            try {
                ObjectInputStream is = new ObjectInputStream(new FileInputStream(cookieStoreFile));
                cookieStore = (BasicCookieStore) is.readObject();
                is.close();
            } catch (Exception e) {
                Log.e(Config.TAG, "Cookie file can not be read", e);
                cookieStore = null;
            }
        }
    }
    if (cookieStore == null) {
        cookieStore = new BasicCookieStore();
    }
    httpclientbuilder.setDefaultCookieStore(cookieStore);
    httpClient = httpclientbuilder.build();
}
 
Example #28
Source File: HttpsUtil.java    From Focus with 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 #29
Source File: WebsocketClient.java    From etherjar with Apache License 2.0 5 votes vote down vote up
protected SslContext prepareSsl() throws GeneralSecurityException, SSLException, KeyStoreException {
        if (!upstream.getScheme().equals("wss")) {
            return null;
        }
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        SslContext sslCtx = SslContextBuilder.forClient()
//            .trustManager(InsecureTrustManagerFactory.INSTANCE)
            .trustManager(trustManagerFactory)
            .build();
        return sslCtx;
    }
 
Example #30
Source File: NettyTransportSupport.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private static KeyStore loadStore(String storePath, final String password, String storeType) throws Exception {
   KeyStore store = KeyStore.getInstance(storeType);
   try (InputStream in = new FileInputStream(new File(storePath));) {
      store.load(in, password != null ? password.toCharArray() : null);
   }

   return store;
}