java.security.UnrecoverableKeyException Java Examples

The following examples show how to use java.security.UnrecoverableKeyException. 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: PostHTTP.java    From localization_nifi with Apache License 2.0 7 votes vote down vote up
private SSLContext createSSLContext(final SSLContextService service)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
    SSLContextBuilder builder = SSLContexts.custom();
    final String trustFilename = service.getTrustStoreFile();
    if (trustFilename != null) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    final String keyFilename = service.getKeyStoreFile();
    if (keyFilename != null) {
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }

    builder = builder.useProtocol(service.getSslAlgorithm());

    final SSLContext sslContext = builder.build();
    return sslContext;
}
 
Example #2
Source File: JmxmpClient.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** tries to connect to the given JMX url over tls, 
 * optionally using the given keystore (if null using a randomly generated key)
 * and optionally using the given truststore (if null trusting all) */
public void connectTls(String urlString, KeyStore keyStore, String keyStorePass, KeyStore trustStore) throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, InvalidKeyException, CertificateException, SecurityException, SignatureException, IOException, KeyManagementException { 
    Map env = new LinkedHashMap(); 

    env.put("jmx.remote.profiles", JmxmpAgent.TLS_JMX_REMOTE_PROFILES);

    if (keyStore==null) throw new NullPointerException("keyStore must be supplied");
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); //"SunX509");
    kmf.init(keyStore, (keyStorePass!=null ? keyStorePass : "").toCharArray());

    TrustManager tms = trustStore!=null ? SecureKeys.getTrustManager(trustStore) : SslTrustUtils.TRUST_ALL;

    SSLContext ctx = SSLContext.getInstance("TLSv1");
    ctx.init(kmf.getKeyManagers(), new TrustManager[] { tms }, null);
    SSLSocketFactory ssf = ctx.getSocketFactory(); 
    env.put(JmxmpAgent.TLS_SOCKET_FACTORY_PROPERTY, ssf); 

    connect(urlString, env); 
}
 
Example #3
Source File: JWTSecurityInterceptor.java    From msf4j with Apache License 2.0 6 votes vote down vote up
private PublicKey getPublicKey(String keyStorePath, String keyStorePassword, String alias)
        throws IOException, KeyStoreException, CertificateException,
        NoSuchAlgorithmException, UnrecoverableKeyException {

    try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(keyStorePath)) {
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(inputStream, keyStorePassword.toCharArray());

        Key key = keystore.getKey(alias, keyStorePassword.toCharArray());
        if (key instanceof PrivateKey) {
            // Get certificate of public key
            java.security.cert.Certificate cert = keystore.getCertificate(alias);

            // Get public key
            return cert.getPublicKey();
        }
    }
    return null;
}
 
Example #4
Source File: Crypto.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static byte[] unseal(byte[] data) throws IntegrationModuleException {
   try {
      EncryptionUtils encryptionUtils = EncryptionUtils.getInstance();
      DataUnsealer dataUnsealer = encryptionUtils.initUnsealing();
      return encryptionUtils.unsealingData(dataUnsealer.unseal(data));
   } catch (KeyStoreException var3) {
      throw new IntegrationModuleException("technical.connector.error.data.seal", var3);
   } catch (UnrecoverableKeyException var4) {
      throw new IntegrationModuleException("technical.connector.error.data.seal", var4);
   } catch (NoSuchAlgorithmException var5) {
      throw new IntegrationModuleException("technical.connector.error.data.seal", var5);
   } catch (CertificateException var6) {
      throw new IntegrationModuleException("technical.connector.error.data.seal", var6);
   } catch (IOException var7) {
      throw new IntegrationModuleException("technical.connector.error.data.seal", var7);
   }
}
 
Example #5
Source File: RootCAProvider.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Override
public SSLEngine createSSLEngine(final SSLContext sslContext, final String remoteAddress, final Map<String, X509Certificate> certMap) throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException {
    final KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");

    final KeyStore ks = getCaKeyStore();
    kmf.init(ks, getKeyStorePassphrase());
    tmf.init(ks);

    final boolean authStrictness = rootCAAuthStrictness.value();
    final boolean allowExpiredCertificate = rootCAAllowExpiredCert.value();

    TrustManager[] tms = new TrustManager[]{new RootCACustomTrustManager(remoteAddress, authStrictness, allowExpiredCertificate, certMap, caCertificate, crlDao)};
    sslContext.init(kmf.getKeyManagers(), tms, new SecureRandom());
    final SSLEngine sslEngine = sslContext.createSSLEngine();
    sslEngine.setNeedClientAuth(authStrictness);
    return sslEngine;
}
 
Example #6
Source File: DWServerConnection.java    From intellij-demandware with MIT License 6 votes vote down vote up
public DWServerConnection(DWSettingsProvider settingsProvider) throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    this.settingsProvider = settingsProvider;

    // SSLContextFactory to allow all hosts. Without this an SSLException is thrown with self signed certs
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build();
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", socketFactory).build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    connectionManager.setMaxTotal(200);
    connectionManager.setDefaultMaxPerRoute(20);

    client = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .build();

    context = new HttpClientContext();
    context.setCredentialsProvider(getCredientials());
}
 
Example #7
Source File: JumbleSSLSocketFactory.java    From Jumble with GNU General Public License v3.0 6 votes vote down vote up
public JumbleSSLSocketFactory(KeyStore keystore, String keystorePassword, String trustStorePath, String trustStorePassword, String trustStoreFormat) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException, NoSuchProviderException, IOException, CertificateException {
    mContext = SSLContext.getInstance("TLS");

    KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
    kmf.init(keystore, keystorePassword != null ? keystorePassword.toCharArray() : new char[0]);

    if(trustStorePath != null) {
        KeyStore trustStore = KeyStore.getInstance(trustStoreFormat);
        FileInputStream fis = new FileInputStream(trustStorePath);
        trustStore.load(fis, trustStorePassword.toCharArray());

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        mTrustWrapper = new JumbleTrustManagerWrapper((X509TrustManager) tmf.getTrustManagers()[0]);
        Log.i(Constants.TAG, "Using custom trust store " + trustStorePath + " with system trust store");
    } else {
        mTrustWrapper = new JumbleTrustManagerWrapper(null);
        Log.i(Constants.TAG, "Using system trust store");
    }

    mContext.init(kmf.getKeyManagers(), new TrustManager[] { mTrustWrapper }, null);
}
 
Example #8
Source File: SslContextFactory.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a SSLContext instance using the given information.
 *
 * @param keystore the full path to the keystore
 * @param keystorePasswd the keystore password
 * @param keystoreType the type of keystore (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 createSslContext(
    final String keystore, final char[] keystorePasswd, final char[] keyPasswd, final String keystoreType, final String protocol)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, KeyManagementException {

    // prepare the keystore
    final KeyStore keyStore = KeyStoreUtils.getKeyStore(keystoreType);
    try (final InputStream keyStoreStream = new FileInputStream(keystore)) {
        keyStore.load(keyStoreStream, keystorePasswd);
    }
    final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    if (keyPasswd == null) {
        keyManagerFactory.init(keyStore, keystorePasswd);
    } else {
        keyManagerFactory.init(keyStore, keyPasswd);
    }

    // initialize the ssl context
    final SSLContext ctx = SSLContext.getInstance(protocol);
    ctx.init(keyManagerFactory.getKeyManagers(), new TrustManager[0], new SecureRandom());

    return ctx;

}
 
Example #9
Source File: RecoverySession.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/** Given a map from alias to grant alias, returns a map from alias to a {@link Key} handle. */
private @NonNull Map<String, Key> getKeysFromGrants(@NonNull Map<String, String> grantAliases)
        throws InternalRecoveryServiceException {
    ArrayMap<String, Key> keysByAlias = new ArrayMap<>(grantAliases.size());
    for (String alias : grantAliases.keySet()) {
        String grantAlias = grantAliases.get(alias);
        Key key;
        try {
            key = mRecoveryController.getKeyFromGrant(grantAlias);
        } catch (UnrecoverableKeyException e) {
            throw new InternalRecoveryServiceException(
                    String.format(
                            Locale.US,
                            "Failed to get key '%s' from grant '%s'",
                            alias,
                            grantAlias), e);
        }
        keysByAlias.put(alias, key);
    }
    return keysByAlias;
}
 
Example #10
Source File: GetHTTP.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private SSLContext createSSLContext(final SSLContextService service)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {

    final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();

    if (StringUtils.isNotBlank(service.getTrustStoreFile())) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        sslContextBuilder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    if (StringUtils.isNotBlank(service.getKeyStoreFile())){
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        sslContextBuilder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }

    sslContextBuilder.useProtocol(service.getSslAlgorithm());

    return sslContextBuilder.build();
}
 
Example #11
Source File: CompositeX509KeyManager.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
public void addKeyStore(KeyStore keyStore, String keystorePass){
	synchronized (keyManagers) {
		try {
			KeyManagerFactory factory =
				KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
			factory.init(keyStore, keystorePass.toCharArray());
			KeyManager[] managers = factory.getKeyManagers();
			List<X509KeyManager> typedManagers = new ArrayList<>();
			for (KeyManager keyManager : managers) {
				if (keyManager instanceof X509KeyManager) {
					typedManagers.add((X509KeyManager) keyManager);
				}
			}
			keyManagers.put(keyStore, typedManagers);
		} catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException e) {
			LoggerFactory.getLogger(getClass()).error("Could not add trust store", e);
		}
	}
}
 
Example #12
Source File: MetadataEmptyTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void runTest() throws IOException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException {
    KeyStore ks = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    Key key = ks.getKey(ALIAS, PASSWORD);
    Certificate cert = ks
            .getCertificate(ALIAS);
    KeyStore.Entry entry = new KeyStore.PrivateKeyEntry(
            (PrivateKey) key,
            new Certificate[]{cert});
    if (!entry.getAttributes().isEmpty()) {
        throw new RuntimeException("Entry's attributes set "
                + "must be empty");
    }
    out.println("Test Passed");
}
 
Example #13
Source File: BridgeServerTlsContextImpl.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private static KeyManagerFactory createKeyManagerFactory(BridgeServerConfig serverConfig)
   throws IOException, KeyStoreException, CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException {
   String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
   if (algorithm == null) {
      algorithm = "SunX509";
   }

   KeyStore ks = KeyStoreLoader.loadKeyStore(
      serverConfig.getTlsServerKeystoreFilepath(),
      serverConfig.getTlsServerKeystorePassword()
   );

   KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
   kmf.init(ks, serverConfig.getTlsServerKeyPassword().toCharArray());

   return kmf;
}
 
Example #14
Source File: SSLTestConfig.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public SSLConfig buildClientSSLConfig() {
  if (!isSSLMode()) {
    return null;
  }

  return new SSLConfig(isSSLMode(), isClientAuthMode(), null, null, null, null) {
    @Override
    public SslContextFactory.Client createClientContextFactory() {
      SslContextFactory.Client factory = new SslContextFactory.Client(!checkPeerName);
      try {
        factory.setSslContext(buildClientSSLContext());
      } catch (KeyManagementException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException e) {
        throw new IllegalStateException("Unable to setup https scheme for HTTPClient to test SSL.", e);
      }
      return factory;
    }
  };
}
 
Example #15
Source File: CipherStorageAndroidKeystore.java    From keystore-ultimate with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Nullable
@Override
public String decrypt(String alias) {
    try {
        byte[] storedData = storage.getKeyBytes(alias);
        if (storedData == null) {
            return null;
        }
        KeyStore keyStore = getKeyStoreAndLoad();
        Key key = keyStore.getKey(alias, null);
        if (key == null) {
            /* Well this should not happen if you do not have a stored byte data, but just in case */
            return null;
        }
        return decryptBytes(key, storedData);
    } catch (KeyStoreException | UnrecoverableKeyException |
            NoSuchAlgorithmException | KeyStoreAccessException e) {
        return null;
    }
}
 
Example #16
Source File: AbstractSpreadSheetFlinkFileOutputFormat.java    From hadoopoffice with Apache License 2.0 6 votes vote down vote up
/***
 * Reads the  (private) key and certificate from keystore to sign
 * 
 * @throws OfficeWriterException
 * @throws IOException
 */
private void readSigningKeyAndCertificate() throws OfficeWriterException, IOException {
	if ((this.howc.getSigKeystoreFile()!=null) && (!"".equals(this.howc.getSigKeystoreFile()))) {
		LOG.info("Signing document");
		if ((this.howc.getSigKeystoreAlias()==null) || ("".equals(this.howc.getSigKeystoreAlias()))) {
				LOG.error("Keystore alias for signature keystore not defined. Cannot sign document");
				throw new OfficeWriterException("Keystore alias for signature keystore not defined. Cannot sign document");
		}
		if ((this.howc.getSigKeystoreType()==null) || ("".equals(this.howc.getSigKeystoreType()))) {
			LOG.error("Keystore type for signature keystore not defined. Cannot sign document");
			throw new OfficeWriterException("Keystore type for signature keystore not defined. Cannot sign document");
		}
		LOG.info("Reading keystore");
		FlinkKeyStoreManager fksm = new FlinkKeyStoreManager();
		try {
			fksm.openKeyStore(new Path(this.howc.getSigKeystoreFile()), this.howc.getSigKeystoreType(), this.howc.getSigKeystorePassword());
			this.howc.setSigKey(fksm.getPrivateKey(this.howc.getSigKeystoreAlias(), this.howc.getSigKeystorePassword()));
			this.howc.setSigCertificate((X509Certificate) fksm.getCertificate(this.howc.getSigKeystoreAlias()));
		} catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | IllegalArgumentException | UnrecoverableKeyException  e) {
			LOG.error("Cannopt read signing certificate. Exception: ",e);
			throw new OfficeWriterException("Cannot read keystore to obtain key and certificate for signing "+e);
		}
		
		
	}
}
 
Example #17
Source File: DockerServerCredentialsSSLConfig.java    From docker-swarm-plugin with MIT License 6 votes vote down vote up
@Override
public SSLContext getSSLContext()
        throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {

    try {
        final KeyStore keyStore = CertificateUtils.createKeyStore(credentials.getClientKey(),
                credentials.getClientCertificate());
        final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "docker".toCharArray());
        final KeyStore trustStore = CertificateUtils.createTrustStore(credentials.getServerCaCertificate());
        final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        final SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        return context;
    } catch (CertificateException | InvalidKeySpecException | IOException e) {
        throw new KeyStoreException("Can't build keystore from provided client key/certificate", e);
    }
}
 
Example #18
Source File: SslContextFactory.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a SSLContext instance using the given information.
 *
 * @param keystore the full path to the keystore
 * @param keystorePasswd the keystore password
 * @param keystoreType the type of keystore (e.g., PKCS12, JKS)
 * @param protocol the protocol to use for the SSL connection
 *
 * @return a SSLContext instance
 * @throws KeyStoreException if any issues accessing the keystore
 * @throws IOException for any problems loading the keystores
 * @throws NoSuchAlgorithmException if an algorithm is found to be used but is unknown
 * @throws CertificateException if there is an issue with the certificate
 * @throws UnrecoverableKeyException if the key is insufficient
 * @throws KeyManagementException if unable to manage the key
 */
public static SSLContext createSslContext(
    final String keystore, final char[] keystorePasswd, final char[] keyPasswd, final String keystoreType, final String protocol)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, KeyManagementException {

    // prepare the keystore
    final KeyStore keyStore = KeyStoreUtils.getKeyStore(keystoreType);
    try (final InputStream keyStoreStream = new FileInputStream(keystore)) {
        keyStore.load(keyStoreStream, keystorePasswd);
    }
    final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    if (keyPasswd == null) {
        keyManagerFactory.init(keyStore, keystorePasswd);
    } else {
        keyManagerFactory.init(keyStore, keyPasswd);
    }

    // initialize the ssl context
    final SSLContext ctx = SSLContext.getInstance(protocol);
    ctx.init(keyManagerFactory.getKeyManagers(), new TrustManager[0], new SecureRandom());

    return ctx;

}
 
Example #19
Source File: MetadataEmptyTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private void runTest() throws IOException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException {
    KeyStore ks = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    Key key = ks.getKey(ALIAS, PASSWORD);
    Certificate cert = ks
            .getCertificate(ALIAS);
    KeyStore.Entry entry = new KeyStore.PrivateKeyEntry(
            (PrivateKey) key,
            new Certificate[]{cert});
    if (!entry.getAttributes().isEmpty()) {
        throw new RuntimeException("Entry's attributes set "
                + "must be empty");
    }
    out.println("Test Passed");
}
 
Example #20
Source File: MetadataEmptyTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private void runTest() throws IOException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException {
    KeyStore ks = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    Key key = ks.getKey(ALIAS, PASSWORD);
    Certificate cert = ks
            .getCertificate(ALIAS);
    KeyStore.Entry entry = new KeyStore.PrivateKeyEntry(
            (PrivateKey) key,
            new Certificate[]{cert});
    if (!entry.getAttributes().isEmpty()) {
        throw new RuntimeException("Entry's attributes set "
                + "must be empty");
    }
    out.println("Test Passed");
}
 
Example #21
Source File: KeyStoreKeyProviderTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testAliasWithIncorrectPassword_One() throws Exception
    {
        try
        {
        	getTestKeyStoreProvider(FILE_ONE, Collections.singletonMap(ALIAS_ONE, "password_fail"));	
        	
//            new KeystoreKeyProvider(
//                    FILE_ONE,
//                    getKeyStoreLoader(),
//                    "SunJCE",
//                    "JCEKS",
//                    Collections.singletonMap(ALIAS_ONE, "password_fail"));
            fail("Expect to fail because password is incorrect");
        }
        catch (AlfrescoRuntimeException e)
        {
            // Expected
            assertTrue(e.getCause() instanceof UnrecoverableKeyException);
        }
    }
 
Example #22
Source File: CryptoPrimitivesTest.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
// TODO need to regen key now that we're using CryptoSuite
public void testSign() {

    byte[] plainText = "123456".getBytes(UTF_8);
    byte[] signature;
    try {
        PrivateKey key = (PrivateKey) crypto.getTrustStore().getKey("key", "123456".toCharArray());
        signature = crypto.sign(key, plainText);

        BufferedInputStream bis = new BufferedInputStream(
                this.getClass().getResourceAsStream("/keypair-signed.crt"));
        byte[] cert = IOUtils.toByteArray(bis);
        bis.close();

        assertTrue(crypto.verify(cert, SIGNING_ALGORITHM, signature, plainText));
    } catch (KeyStoreException | CryptoException | IOException | UnrecoverableKeyException
            | NoSuchAlgorithmException e) {
        fail("Could not verify signature. Error: " + e.getMessage());
    }
}
 
Example #23
Source File: KeyStoreHelper.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
/**
 * Generates the signature for the given byte[] using MD5 with RSA algorithm and the
 * private key with which this helper was initialised.
 *
 * @param data the byte[] of data to be signed
 *
 * @return the signature, encrypted with the private key
 *
 * @throws UnrecoverableKeyException
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
public byte[] signDataWithPrivateKey(byte[] data) throws UnrecoverableKeyException,
                                                 KeyStoreException,
                                                 NoSuchAlgorithmException,
                                                 InvalidKeyException,
                                                 SignatureException {
    if( pvtKeyStore == null ) {
        throw new RuntimeException( "Key store with private key not configured. Please configure it properly before using signed serialization." );
    }
    PrivateKey pvtkey = (PrivateKey) pvtKeyStore.getKey( pvtKeyAlias,
                                                         pvtKeyPassword );
    Signature sig = Signature.getInstance( "MD5withRSA" );
    sig.initSign( pvtkey );
    sig.update( data );
    return sig.sign();
}
 
Example #24
Source File: DebugKeyProvider.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the debug {@link PrivateKey} to use to sign applications for debug purpose.
 * @return the private key or <code>null</code> if its creation failed.
 */
@SuppressWarnings("unused") // the thrown Exceptions are not actually thrown
public PrivateKey getDebugKey() throws KeyStoreException, NoSuchAlgorithmException,
        UnrecoverableKeyException, UnrecoverableEntryException {
    if (mEntry != null) {
        return mEntry.getPrivateKey();
    }

    return null;
}
 
Example #25
Source File: ECKeyStore.java    From balzac with Apache License 2.0 5 votes vote down vote up
public PrivateKey getKey(String keyID) throws KeyStoreException {
    checkState(ks.containsAlias(keyID));
    Key entryKey;
    try {
        entryKey = ks.getKey(keyID, password);
        return PrivateKey.from(entryKey.getEncoded(), netwotkTypeMap.get(keyID));
    } catch (UnrecoverableKeyException | NoSuchAlgorithmException e) {
        throw new KeyStoreException("Cannot fetch key " + keyID + ": " + e.getMessage(), e);
    }
}
 
Example #26
Source File: SamlKeyLoaderIT.java    From development with Apache License 2.0 5 votes vote down vote up
@Test(expected = SaaSApplicationException.class)
public void loadPrivateKeyFromStore_invalidAlias()
        throws CertificateException, SaaSApplicationException,
        UnrecoverableKeyException, NoSuchAlgorithmException, IOException,
        KeyStoreException {
    // when
    samlKeyLoader.loadPrivateKeyFromStore(getPath(KEYSTORE_FILE),
            KEYSTORE_PASSWORD, "invalidAlias");
}
 
Example #27
Source File: JKS.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
public Key engineGetKey(String alias, char[] password)
    throws NoSuchAlgorithmException, UnrecoverableKeyException
{
    alias = alias.toLowerCase();

    if (!privateKeys.containsKey(alias))
        return null;
    byte[] key = decryptKey((byte[]) privateKeys.get(alias),
        charsToBytes(password));
    Certificate[] chain = engineGetCertificateChain(alias);
    if (chain.length > 0)
    {
        try
        {
            // Private and public keys MUST have the same algorithm.
            KeyFactory fact = KeyFactory.getInstance(
                chain[0].getPublicKey().getAlgorithm());
            return fact.generatePrivate(new PKCS8EncodedKeySpec(key));
        }
        catch (InvalidKeySpecException x)
        {
            throw new UnrecoverableKeyException(x.getMessage());
        }
    }
    else
        return new SecretKeySpec(key, alias);
}
 
Example #28
Source File: JceKeyStore.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the key associated with the given alias, using the given
 * password to recover it.
 *
 * @param alias the alias name
 * @param password the password for recovering the key
 *
 * @return the requested key, or null if the given alias does not exist
 * or does not identify a <i>key entry</i>.
 *
 * @exception NoSuchAlgorithmException if the algorithm for recovering the
 * key cannot be found
 * @exception UnrecoverableKeyException if the key cannot be recovered
 * (e.g., the given password is wrong).
 */
public Key engineGetKey(String alias, char[] password)
    throws NoSuchAlgorithmException, UnrecoverableKeyException
{
    Key key = null;

    Object entry = entries.get(alias.toLowerCase(Locale.ENGLISH));

    if (!((entry instanceof PrivateKeyEntry) ||
          (entry instanceof SecretKeyEntry))) {
        return null;
    }

    KeyProtector keyProtector = new KeyProtector(password);

    if (entry instanceof PrivateKeyEntry) {
        byte[] encrBytes = ((PrivateKeyEntry)entry).protectedKey;
        EncryptedPrivateKeyInfo encrInfo;
        try {
            encrInfo = new EncryptedPrivateKeyInfo(encrBytes);
        } catch (IOException ioe) {
            throw new UnrecoverableKeyException("Private key not stored "
                                                + "as PKCS #8 " +
                                                "EncryptedPrivateKeyInfo");
        }
        key = keyProtector.recover(encrInfo);
    } else {
        key =
            keyProtector.unseal(((SecretKeyEntry)entry).sealedKey);
    }

    return key;
}
 
Example #29
Source File: Crypto.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static byte[] seal(byte[] data, SecretKey secretKey, String keyId) throws IntegrationModuleException {
    try {
        DataSealer dataSealer = EncryptionUtils.getInstance().initSealing();
        return dataSealer.seal(data, secretKey, keyId);
    } catch (KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException | CertificateException | IOException | DataSealerException ex) {
        throw new IntegrationModuleException("technical.connector.error.data.seal", ex);
    }
}
 
Example #30
Source File: Utils.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Load {@link KeyPair} from JKS keystore.
 * @param is keystore data from {@link InputStream}.
 * @param keystorePassword password to open keystore.
 * @param keyPairAlias name of the keystore entry representing the {@link KeyPair}
 * @param keyPairPassword password for {@link KeyPair} entity
 * @return instance of {@link KeyPair}
 * @throws KeyStoreException
 * @throws IOException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws UnrecoverableKeyException
 */
public static KeyPair loadKeyPair(InputStream is, String keystorePassword, String keyPairAlias, String keyPairPassword)
        throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, UnrecoverableKeyException {
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(is, keystorePassword.toCharArray());

    Key key = keystore.getKey(keyPairAlias, keyPairPassword.toCharArray());
    if (key instanceof PrivateKey) {
        Certificate cert = keystore.getCertificate(keyPairAlias);
        PublicKey publicKey = cert.getPublicKey();
        return new KeyPair(publicKey, (PrivateKey) key);
    }
    throw new UnrecoverableKeyException("KeyPair not found");
}