Java 类java.security.UnrecoverableKeyException 实例源码

项目:q-mail    文件:MockSmtpServer.java   
private void upgradeToTls(Socket socket) throws KeyStoreException, IOException, NoSuchAlgorithmException,
        CertificateException, UnrecoverableKeyException, KeyManagementException {

    KeyStore keyStore = keyStoreProvider.getKeyStore();

    String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(defaultAlgorithm);
    keyManagerFactory.init(keyStore, keyStoreProvider.getPassword());

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

    SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(
            socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true);
    sslSocket.setUseClientMode(false);
    sslSocket.startHandshake();

    input = Okio.buffer(Okio.source(sslSocket.getInputStream()));
    output = Okio.buffer(Okio.sink(sslSocket.getOutputStream()));
}
项目:MQTT-Essentials-A-Lightweight-IoT-Protocol    文件:SecurityHelper.java   
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;
}
项目:q-mail    文件:MockPop3Server.java   
private void handleInteractions(Socket socket) throws IOException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException,
        UnexpectedCommandException {

    ImapInteraction interaction = interactions.pop();
    if (interaction instanceof ExpectedCommand) {
        readExpectedCommand((ExpectedCommand) interaction);
    } else if (interaction instanceof CannedResponse) {
        writeCannedResponse((CannedResponse) interaction);
    } else if (interaction instanceof CloseConnection) {
        clientSocket.close();
    } else if (interaction instanceof EnableCompression) {
        enableCompression(socket);
    } else if (interaction instanceof UpgradeToTls) {
        upgradeToTls(socket);
    }
}
项目:q-mail    文件:MockPop3Server.java   
private void upgradeToTls(Socket socket) throws KeyStoreException, IOException, NoSuchAlgorithmException,
        CertificateException, UnrecoverableKeyException, KeyManagementException {

    KeyStore keyStore = keyStoreProvider.getKeyStore();

    String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(defaultAlgorithm);
    keyManagerFactory.init(keyStore, keyStoreProvider.getPassword());

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

    SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(
            socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true);
    sslSocket.setUseClientMode(false);
    sslSocket.startHandshake();

    input = Okio.buffer(Okio.source(sslSocket.getInputStream()));
    output = Okio.buffer(Okio.sink(sslSocket.getOutputStream()));
}
项目:MakiLite    文件:FingerprintUiHelper.java   
/**
 * Initialize the {@link Cipher} instance with the created key in the {@link #createKey()}
 * method.
 *
 * @return {@code true} if initialization is successful, {@code false} if the lock screen has
 * been disabled or reset after the key was generated, or if a fingerprint got enrolled after
 * the key was generated.
 */
private boolean initCipher() {
    try {
        if (mKeyStore == null) {
            mKeyStore = KeyStore.getInstance("AndroidKeyStore");
        }
        createKey();
        mKeyStore.load(null);
        SecretKey key = (SecretKey) mKeyStore.getKey(KEY_NAME, null);
        mCipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        mCipher.init(Cipher.ENCRYPT_MODE, key);
        return true;
    } catch (NoSuchPaddingException | KeyStoreException | CertificateException | UnrecoverableKeyException | IOException
            | NoSuchAlgorithmException | InvalidKeyException e) {
        return false;
    }
}
项目:hadoop-oss    文件:JavaKeyStoreProvider.java   
private boolean isBadorWrongPassword(IOException ioe) {
  // As per documentation this is supposed to be the way to figure
  // if password was correct
  if (ioe.getCause() instanceof UnrecoverableKeyException) {
    return true;
  }
  // Unfortunately that doesn't seem to work..
  // Workaround :
  if ((ioe.getCause() == null)
      && (ioe.getMessage() != null)
      && ((ioe.getMessage().contains("Keystore was tampered")) || (ioe
          .getMessage().contains("password was incorrect")))) {
    return true;
  }
  return false;
}
项目:mobile-store    文件:LocalRepoKeyStore.java   
private KeyPair getKerplappKeypair() throws KeyStoreException, UnrecoverableKeyException,
        NoSuchAlgorithmException {
    /*
     * You can't store a keypair without an associated certificate chain so,
     * we'll use the INDEX_CERT_ALIAS as the de-facto keypair/certificate
     * chain. This cert/key is initialized when the KerplappKeyStore is
     * constructed for the first time and should *always* be present.
     */
    Key key = keyStore.getKey(INDEX_CERT_ALIAS, "".toCharArray());

    if (key instanceof PrivateKey) {
        Certificate cert = keyStore.getCertificate(INDEX_CERT_ALIAS);
        PublicKey publicKey = cert.getPublicKey();
        return new KeyPair(publicKey, (PrivateKey) key);
    }

    return null;
}
项目:mobile-store    文件:LocalRepoKeyStore.java   
private void addToStore(String alias, KeyPair kp, Certificate cert) throws KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {
    Certificate[] chain = {
        cert,
    };
    keyStore.setKeyEntry(alias, kp.getPrivate(),
            "".toCharArray(), chain);

    keyStore.store(new FileOutputStream(keyStoreFile), "".toCharArray());

    /*
     * After adding an entry to the keystore we need to create a fresh
     * KeyManager by reinitializing the KeyManagerFactory with the new key
     * store content and then rewrapping the default KeyManager with our own
     */
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());

    keyManagerFactory.init(keyStore, "".toCharArray());
    KeyManager defaultKeyManager = keyManagerFactory.getKeyManagers()[0];
    KeyManager wrappedKeyManager = new KerplappKeyManager((X509KeyManager) defaultKeyManager);
    keyManagers = new KeyManager[] {
        wrappedKeyManager,
    };
}
项目:alfresco-repository    文件:KeyStoreKeyProviderTest.java   
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);
        }
    }
项目:message-broker    文件:Server.java   
private ChannelFuture bindToSslSocket()
        throws InterruptedException, CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException,
        KeyStoreException, KeyManagementException, IOException {
    String hostname = configuration.getHostName();
    int port = Integer.parseInt(configuration.getSsl().getPort());

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup)
     .channel(NioServerSocketChannel.class)
     .childHandler(new SslSocketChannelInitializer(ioExecutors, new SslHandlerFactory(configuration)))
     .option(ChannelOption.SO_BACKLOG, 128)
     .childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.
    ChannelFuture future = b.bind(hostname, port).sync();
    LOGGER.info("Listening AMQP/" + configuration.getSsl().getProtocol() + " on " + hostname + ":" + port);
    return future;
}
项目:iroha-demo-android    文件:MainActivity.java   
private void initNavigationHeader() {
    final Context context = getApplicationContext();
    final String alias;
    final String uuid;
    try {
        alias = Account.getAlias(context);
        uuid = Account.getUuid(context);
    } catch (NoSuchPaddingException | UnrecoverableKeyException | NoSuchAlgorithmException
            | KeyStoreException | InvalidKeyException | IOException e) {
        Toast.makeText(context, ErrorMessageFactory.create(context, e), Toast.LENGTH_SHORT).show();
        return;
    }

    View headerView = binding.navigation.getHeaderView(0);
    ((TextView) headerView.findViewById(R.id.name)).setText(alias);
    ((TextView) headerView.findViewById(R.id.email)).setText(uuid);
    Log.d(TAG, "initNavigationHeader: " + uuid);
}
项目:MQTT-Essentials-A-Lightweight-IoT-Protocol    文件:SecurityHelper.java   
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;
}
项目:FirefoxData-android    文件:SSLSocketFactory.java   
public SSLSocketFactory(
        final String algorithm,
        final KeyStore keystore,
        final String keyPassword,
        final KeyStore truststore,
        final SecureRandom random,
        final HostNameResolver nameResolver)
            throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    this(SSLContexts.custom()
            .useProtocol(algorithm)
            .setSecureRandom(random)
            .loadKeyMaterial(keystore, keyPassword != null ? keyPassword.toCharArray() : null)
            .loadTrustMaterial(truststore)
            .build(),
            nameResolver);
}
项目:nifi-registry    文件:SslContextFactory.java   
/**
 * 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 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 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;

}
项目:q-mail    文件:MockSmtpServer.java   
private void handleInteractions(Socket socket) throws IOException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException,
        UnexpectedCommandException {

    SmtpInteraction interaction = interactions.pop();
    if (interaction instanceof ExpectedCommand) {
        readExpectedCommand((ExpectedCommand) interaction);
    } else if (interaction instanceof CannedResponse) {
        writeCannedResponse((CannedResponse) interaction);
    } else if (interaction instanceof CloseConnection) {
        clientSocket.close();
    }
}
项目:java-buildpack-security-provider    文件:FileWatchingX509ExtendedKeyManager.java   
private X509ExtendedKeyManager getKeyManager(KeyStore keyStore) {
    try {
        this.keyManagerFactory.init(keyStore, new char[0]);

        for (KeyManager keyManager : this.keyManagerFactory.getKeyManagers()) {
            if (keyManager instanceof X509ExtendedKeyManager) {
                return (X509ExtendedKeyManager) keyManager;
            }
        }

        throw new IllegalStateException("No X509ExtendedKeyManager available");
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
        throw new UndeclaredThrowableException(e);
    }
}
项目:boohee_v5.6    文件:HttpUtils.java   
public CustomSSLSocketFactory(KeyStore keyStore) throws NoSuchAlgorithmException,
        KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    MyX509TrustManager myX509TrustManager;
    super(keyStore);
    try {
        myX509TrustManager = new MyX509TrustManager();
    } catch (Exception e) {
        myX509TrustManager = null;
    }
    this.a.init(null, new TrustManager[]{myX509TrustManager}, null);
}
项目:mobile-store    文件:JKS.java   
private static byte[] decryptKey(byte[] encryptedPKI, byte[] passwd)
    throws UnrecoverableKeyException
{
    try
    {
        EncryptedPrivateKeyInfo epki =
            new EncryptedPrivateKeyInfo(encryptedPKI);
        byte[] encr = epki.getEncryptedData();
        byte[] keystream = new byte[20];
        System.arraycopy(encr, 0, keystream, 0, 20);
        byte[] check = new byte[20];
        System.arraycopy(encr, encr.length-20, check, 0, 20);
        byte[] key = new byte[encr.length - 40];
        MessageDigest sha = MessageDigest.getInstance("SHA1");
        int count = 0;
        while (count < key.length)
        {
            sha.reset();
            sha.update(passwd);
            sha.update(keystream);
            sha.digest(keystream, 0, keystream.length);
            for (int i = 0; i < keystream.length && count < key.length; i++)
            {
                key[count] = (byte) (keystream[i] ^ encr[count+20]);
                count++;
            }
        }
        sha.reset();
        sha.update(passwd);
        sha.update(key);
        if (!MessageDigest.isEqual(check, sha.digest()))
            throw new UnrecoverableKeyException("checksum mismatch");
        return key;
    }
    catch (Exception x)
    {
        throw new UnrecoverableKeyException(x.getMessage());
    }
}
项目:ipack    文件:BcKeyStoreSpi.java   
public Key engineGetKey(
    String alias,
    char[] password) 
    throws NoSuchAlgorithmException, UnrecoverableKeyException
{
    StoreEntry  entry = (StoreEntry)table.get(alias);

    if (entry == null || entry.getType() == CERTIFICATE)
    {
        return null;
    }

    return (Key)entry.getObject(password);
}
项目:ipack    文件:PKCS12KeyStoreSpi.java   
public Key engineGetKey(
    String alias,
    char[] password)
    throws NoSuchAlgorithmException, UnrecoverableKeyException
{
    if (alias == null)
    {
        throw new IllegalArgumentException("null alias passed to getKey.");
    }

    return (Key)keys.get(alias);
}
项目:Fingerprint    文件:CipherHelper.java   
private boolean hasKey(){
    try {
        cipherKey = (SecretKey) keyStore.getKey(keyName, null);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
        throw new RuntimeException("Failed to get key", e);
    }
    return cipherKey != null;
}
项目:openjdk-jdk10    文件:KeyProtector.java   
/**
 * Unseals the sealed key.
 */
Key unseal(SealedObject so)
    throws NoSuchAlgorithmException, UnrecoverableKeyException
{
    try {
        // create PBE key from password
        PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
        SecretKey skey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
        pbeKeySpec.clearPassword();

        SealedObjectForKeyProtector soForKeyProtector = null;
        if (!(so instanceof SealedObjectForKeyProtector)) {
            soForKeyProtector = new SealedObjectForKeyProtector(so);
        } else {
            soForKeyProtector = (SealedObjectForKeyProtector)so;
        }
        AlgorithmParameters params = soForKeyProtector.getParameters();
        if (params == null) {
            throw new UnrecoverableKeyException("Cannot get " +
                                                "algorithm parameters");
        }
        PBEWithMD5AndTripleDESCipher cipherSpi;
        cipherSpi = new PBEWithMD5AndTripleDESCipher();
        Cipher cipher = new CipherForKeyProtector(cipherSpi,
                                                  SunJCE.getInstance(),
                                                  "PBEWithMD5AndTripleDES");
        cipher.init(Cipher.DECRYPT_MODE, skey, params);
        return (Key)soForKeyProtector.getObject(cipher);
    } catch (NoSuchAlgorithmException ex) {
        // Note: this catch needed to be here because of the
        // later catch of GeneralSecurityException
        throw ex;
    } catch (IOException ioe) {
        throw new UnrecoverableKeyException(ioe.getMessage());
    } catch (ClassNotFoundException cnfe) {
        throw new UnrecoverableKeyException(cnfe.getMessage());
    } catch (GeneralSecurityException gse) {
        throw new UnrecoverableKeyException(gse.getMessage());
    }
}
项目:k-framework    文件:ReportService.java   
public String request() throws UnrecoverableKeyException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException, IOException {
    //解决XStream对出现双下划线的bug, 将要提交给API的数据对象转换成XML格式数据Post给API
    XStream xStreamForRequestPostData = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
    String postDataXML = xStreamForRequestPostData.toXML(reqData);
    String responseString = new HttpsRequest().sendPost(Configure.REPORT_API, postDataXML);

    Util.log("   report返回的数据:" + responseString);

    return responseString;
}
项目:openjdk-jdk10    文件:JceKeyStore.java   
/**
 * 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;
}
项目:message-broker    文件:Server.java   
@Override
public synchronized void start() throws InterruptedException, CertificateException, UnrecoverableKeyException,
                           NoSuchAlgorithmException, KeyStoreException, KeyManagementException,
                           IOException {
    basicHaListener.setStartCalled(); //to allow starting when the node becomes active when HA is enabled
    if (!basicHaListener.isActive()) {
        return;
    }
    super.start();
}
项目:message-broker    文件:Server.java   
/**
 * Method to start the transport, only if has been called, prior to becoming the active node.
 */
private synchronized void startOnBecomingActive() {
    if (basicHaListener.isStartCalled()) {
        try {
            start();
        } catch (InterruptedException | CertificateException | UnrecoverableKeyException
                | NoSuchAlgorithmException | KeyStoreException | KeyManagementException | IOException e) {
            LOGGER.error("Error while starting the AMQP Transport ", e);
        }
    }
}
项目:iroha-demo-android    文件:SplashActivity.java   
private void openSplashFragment() {
    splashFragment = SplashFragment.newInstance();
    splashFragment.show(getSupportFragmentManager(), SplashFragment.TAG);
    try {
        final String uuid = Account.getUuid(getApplicationContext());
        new Handler().postDelayed(screenTransitionTask(uuid), 1000);
    } catch (NoSuchAlgorithmException | UnrecoverableKeyException | NoSuchPaddingException
            | KeyStoreException | InvalidKeyException | IOException e) {
        new Handler().postDelayed(screenTransitionTask(null), 1000);
    }
}
项目:iroha-demo-android    文件:WalletPresenter.java   
private String getUuid() {
    final Context context = walletView.getContext();
    final String uuid;
    try {
        uuid = Account.getUuid(context);
    } catch (NoSuchPaddingException | UnrecoverableKeyException | NoSuchAlgorithmException
            | KeyStoreException | InvalidKeyException | IOException e) {
        Crashlytics.log(Log.ERROR, AssetSenderPresenter.TAG, e.getMessage());
        walletView.showError(ErrorMessageFactory.create(context, e), e);
        return null;
    }
    return uuid;
}
项目:openjdk-jdk10    文件:SSLEngineTestCase.java   
/**
 * Returns SSLContext with TESTED_SECURITY_PROTOCOL protocol and
 * sets up keys.
 *
 * @return - SSLContext with a protocol specified by
 *           TESTED_SECURITY_PROTOCOL.
 */
public static SSLContext getContext() {
    try {
        java.security.Security.setProperty(
                "jdk.tls.disabledAlgorithms", "");
        java.security.Security.setProperty(
                "jdk.certpath.disabledAlgorithms", "");
        KeyStore ks = KeyStore.getInstance("JKS");
        KeyStore ts = KeyStore.getInstance("JKS");
        char[] passphrase = PASSWD.toCharArray();
        try (FileInputStream keyFileStream =
                new FileInputStream(KEY_FILE_NAME)) {
            ks.load(keyFileStream, passphrase);
        }
        try (FileInputStream trustFileStream =
                new FileInputStream(TRUST_FILE_NAME)) {
            ts.load(trustFileStream, passphrase);
        }
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passphrase);
        TrustManagerFactory tmf =
                TrustManagerFactory.getInstance("SunX509");
        tmf.init(ts);
        SSLContext sslCtx =
                SSLContext.getInstance(TESTED_SECURITY_PROTOCOL);
        sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        return sslCtx;
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException |
            CertificateException | UnrecoverableKeyException |
            KeyManagementException ex) {
        throw new Error("Unexpected exception", ex);
    }
}
项目:iroha-demo-android    文件:AssetReceivePresenter.java   
@NotNull
private String getUuid() {
    final Context context = assetReceiveView.getContext();
    if (uuid == null || uuid.isEmpty()) {
        try {
            uuid = Account.getUuid(context);
        } catch (NoSuchPaddingException | UnrecoverableKeyException | NoSuchAlgorithmException
                | KeyStoreException | InvalidKeyException | IOException e) {
            assetReceiveView.showError(ErrorMessageFactory.create(context, e), e);
            return "";
        }
    }
    return uuid;
}
项目:xitk    文件:XiKeyStoreSpi.java   
@Override
public Key engineGetKey(String alias, char[] password)
        throws NoSuchAlgorithmException, UnrecoverableKeyException {
    if (!keyCerts.containsKey(alias)) {
        return null;
    }

    return keyCerts.get(alias).getKey();
}
项目:xitk    文件:SoftTokenMacContentSignerBuilder.java   
public SoftTokenMacContentSignerBuilder(String keystoreType, InputStream keystoreStream,
        char[] keystorePassword, String keyname, char[] keyPassword)
        throws XiSecurityException {
    if (!"JCEKS".equalsIgnoreCase(keystoreType)) {
        throw new IllegalArgumentException("unsupported keystore type: " + keystoreType);
    }
    ParamUtil.requireNonNull("keystoreStream", keystoreStream);
    ParamUtil.requireNonNull("keystorePassword", keystorePassword);
    ParamUtil.requireNonNull("keyPassword", keyPassword);

    try {
        KeyStore ks = KeyUtil.getKeyStore(keystoreType);
        ks.load(keystoreStream, keystorePassword);

        String tmpKeyname = keyname;
        if (tmpKeyname == null) {
            Enumeration<String> aliases = ks.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                if (ks.isKeyEntry(alias)) {
                    tmpKeyname = alias;
                    break;
                }
            }
        } else {
            if (!ks.isKeyEntry(tmpKeyname)) {
                throw new XiSecurityException("unknown key named " + tmpKeyname);
            }
        }

        this.key = (SecretKey) ks.getKey(tmpKeyname, keyPassword);
    } catch (KeyStoreException | NoSuchProviderException | NoSuchAlgorithmException
            | CertificateException | IOException | UnrecoverableKeyException
            | ClassCastException ex) {
        throw new XiSecurityException(ex.getMessage(), ex);
    }
}
项目:RISE-V2G    文件:SecurityUtils.java   
/**
 * Sets the SSLContext of the TLSServer and TLSClient with the given keystore and truststore locations as
 * well as the password protecting the keystores/truststores.
 * 
 * @param keyStorePath The relative path and filename for the keystore
 * @param trustStorePath The relative path and filename for the truststore
 * @param keyStorePassword The password protecting the keystore
 */
public static void setSSLContext(
        String keyStorePath, 
        String trustStorePath,
        String keyStorePassword) {
    KeyStore keyStore = SecurityUtils.getKeyStore(keyStorePath, keyStorePassword);
    KeyStore trustStore = SecurityUtils.getKeyStore(trustStorePath, keyStorePassword);

    try {
        // Initialize a key manager factory with the keystore
        KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyFactory.init(keyStore, keyStorePassword.toCharArray());
        KeyManager[] keyManagers = keyFactory.getKeyManagers();

        // Initialize a trust manager factory with the truststore
        TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());    
        trustFactory.init(trustStore);
        TrustManager[] trustManagers = trustFactory.getTrustManagers();

        // Initialize an SSL context to use these managers and set as default
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagers, null);
        SSLContext.setDefault(sslContext); 
    } catch (NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException | 
            KeyManagementException e) {
        getLogger().error(e.getClass().getSimpleName() + " occurred while trying to initialize SSL context");
    }    
}
项目:oscm    文件:SamlKeyLoaderIT.java   
@Test
public void loadPrivateKeyFromStore_OK() throws CertificateException,
        SaaSApplicationException, UnrecoverableKeyException,
        NoSuchAlgorithmException, IOException, KeyStoreException {
    // when
    samlKeyLoader.loadPrivateKeyFromStore(getPath(KEYSTORE_FILE),
            KEYSTORE_PASSWORD, ALIAS);
    // then
}
项目:oscm    文件:SamlKeyLoaderIT.java   
@Test(expected = IOException.class)
public void loadPrivateKeyFromStore_invalidPassword()
        throws CertificateException, SaaSApplicationException,
        UnrecoverableKeyException, NoSuchAlgorithmException, IOException,
        KeyStoreException {
    // given
    String password = "invalidPassword";
    // when
    samlKeyLoader.loadPrivateKeyFromStore(getPath(KEYSTORE_FILE), password,
            ALIAS);
    // then
}
项目:oscm    文件:SamlKeyLoaderIT.java   
@Test(expected = SaaSApplicationException.class)
public void loadPrivateKeyFromStore_invalidAlias()
        throws CertificateException, SaaSApplicationException,
        UnrecoverableKeyException, NoSuchAlgorithmException, IOException,
        KeyStoreException {
    // when
    samlKeyLoader.loadPrivateKeyFromStore(getPath(KEYSTORE_FILE),
            KEYSTORE_PASSWORD, "invalidAlias");
}
项目:Oauth2-Stateless-Authentication-with-Spring-and-JWT-Token    文件:AuthorizationServerConfig.java   
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    try {
        converter.setSigningKey(keyProvider.getKey());
    } catch (URISyntaxException | KeyStoreException | NoSuchAlgorithmException | IOException | UnrecoverableKeyException | CertificateException e) {
        e.printStackTrace();
    }

    return converter;
}
项目:esup-ecandidat    文件:SignaturePdfManager.java   
/** Signe un PDF
 * Pour créer un keystore, lancer en ligne de commande :
 * keytool -genkeypair -storepass 123456 -storetype pkcs12 -alias keystoreAlias -validity 365 -v -keyalg RSA -keystore keystore.p12
 * @param inStream
 * @return le stream signé
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws UnrecoverableKeyException
 */
public InputStream signPdf(ByteArrayInOutStream inStream) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException{
    if (!isSignPdfEnable()){
        return inStream.getInputStream();
    }
    KeyStore keystore = KeyStore.getInstance("PKCS12", provider);
       char[] pin = pdfSignaturePass.toCharArray();
       keystore.load(new FileInputStream(pdfSignatureKeystorePath), pin);
    CreateSignaturePdf signing = new CreateSignaturePdf(keystore, pin.clone());     
       return signing.signPdf(inStream,applicationContext.getMessage("pdf.signature.nom", null, UI.getCurrent().getLocale()),
            applicationContext.getMessage("pdf.signature.lieu", null, UI.getCurrent().getLocale()),
            applicationContext.getMessage("pdf.signature.raison", null, UI.getCurrent().getLocale()),
            applicationContext.getMessage("pdf.signature.contact.info", null, UI.getCurrent().getLocale()));
}
项目:letv    文件:HttpUtils.java   
public CustomSSLSocketFactory(KeyStore keyStore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    MyX509TrustManager myX509TrustManager;
    super(keyStore);
    try {
        myX509TrustManager = new MyX509TrustManager();
    } catch (Exception e) {
        myX509TrustManager = null;
    }
    this.a.init(null, new TrustManager[]{myX509TrustManager}, null);
}
项目:java-buildpack-security-provider    文件:CloudFoundryContainerKeyManagerFactoryTest.java   
@Test
public void defaultKeyManagerForNullCertificatesLocation() throws NoSuchProviderException, NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException,
    UnrecoverableKeyException {
    CloudFoundryContainerKeyManagerFactory.SunX509 factory = new CloudFoundryContainerKeyManagerFactory.SunX509(
        null,
        Paths.get("src/test/resources/client-private-key-1.pem"));
    factory.engineInit(getKeyStore(), new char[0]);


    KeyManager keyManager = factory.engineGetKeyManagers()[0];
    assertThat(keyManager).isInstanceOf(DelegatingX509ExtendedKeyManager.class);
    assertThat(((DelegatingX509ExtendedKeyManager) keyManager).size()).isEqualTo(1);
}