Search in sources :

Example 26 with CertificateExpiredException

use of java.security.cert.CertificateExpiredException in project robovm by robovm.

the class CertificateExpiredExceptionTest method testCertificateExpiredException03.

/**
     * Test for <code>CertificateExpiredException(String)</code> constructor
     * Assertion: constructs CertificateExpiredException when <code>msg</code>
     * is null
     */
public void testCertificateExpiredException03() {
    String msg = null;
    CertificateExpiredException tE = new CertificateExpiredException(msg);
    assertNull("getMessage() must return null.", tE.getMessage());
    assertNull("getCause() must return null", tE.getCause());
}
Also used : CertificateExpiredException(java.security.cert.CertificateExpiredException)

Example 27 with CertificateExpiredException

use of java.security.cert.CertificateExpiredException in project netty by netty.

the class SslErrorTest method testCorrectAlert.

@Test(timeout = 30000)
public void testCorrectAlert() throws Exception {
    // As this only works correctly at the moment when OpenSslEngine is used on the server-side there is
    // no need to run it if there is no openssl is available at all.
    Assume.assumeTrue(OpenSsl.isAvailable());
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(serverProvider).trustManager(new SimpleTrustManagerFactory() {

        @Override
        protected void engineInit(KeyStore keyStore) {
        }

        @Override
        protected void engineInit(ManagerFactoryParameters managerFactoryParameters) {
        }

        @Override
        protected TrustManager[] engineGetTrustManagers() {
            return new TrustManager[] { new X509TrustManager() {

                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    throw exception;
                }

                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                // NOOP
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return EmptyArrays.EMPTY_X509_CERTIFICATES;
                }
            } };
        }
    }).clientAuth(ClientAuth.REQUIRE).build();
    final SslContext sslClientCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).keyManager(new File(getClass().getResource("test.crt").getFile()), new File(getClass().getResource("test_unencrypted.pem").getFile())).sslProvider(clientProvider).build();
    Channel serverChannel = null;
    Channel clientChannel = null;
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        serverChannel = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(sslServerCtx.newHandler(ch.alloc()));
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                        ctx.close();
                    }
                });
            }
        }).bind(0).sync().channel();
        final Promise<Void> promise = group.next().newPromise();
        clientChannel = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(sslClientCtx.newHandler(ch.alloc()));
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                        // Unwrap as its wrapped by a DecoderException
                        Throwable unwrappedCause = cause.getCause();
                        if (unwrappedCause instanceof SSLException) {
                            if (exception instanceof TestCertificateException) {
                                CertPathValidatorException.Reason reason = ((CertPathValidatorException) exception.getCause()).getReason();
                                if (reason == CertPathValidatorException.BasicReason.EXPIRED) {
                                    verifyException(unwrappedCause, "expired", promise);
                                } else if (reason == CertPathValidatorException.BasicReason.NOT_YET_VALID) {
                                    verifyException(unwrappedCause, "bad", promise);
                                } else if (reason == CertPathValidatorException.BasicReason.REVOKED) {
                                    verifyException(unwrappedCause, "revoked", promise);
                                }
                            } else if (exception instanceof CertificateExpiredException) {
                                verifyException(unwrappedCause, "expired", promise);
                            } else if (exception instanceof CertificateNotYetValidException) {
                                verifyException(unwrappedCause, "bad", promise);
                            } else if (exception instanceof CertificateRevokedException) {
                                verifyException(unwrappedCause, "revoked", promise);
                            }
                        }
                    }
                });
            }
        }).connect(serverChannel.localAddress()).syncUninterruptibly().channel();
        // Block until we received the correct exception
        promise.syncUninterruptibly();
    } finally {
        if (clientChannel != null) {
            clientChannel.close().syncUninterruptibly();
        }
        if (serverChannel != null) {
            serverChannel.close().syncUninterruptibly();
        }
        group.shutdownGracefully();
        ReferenceCountUtil.release(sslServerCtx);
        ReferenceCountUtil.release(sslClientCtx);
    }
}
Also used : LoggingHandler(io.netty.handler.logging.LoggingHandler) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) CertificateExpiredException(java.security.cert.CertificateExpiredException) CertificateException(java.security.cert.CertificateException) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) SSLException(javax.net.ssl.SSLException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) CertificateRevokedException(java.security.cert.CertificateRevokedException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) SimpleTrustManagerFactory(io.netty.handler.ssl.util.SimpleTrustManagerFactory) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) CertPathValidatorException(java.security.cert.CertPathValidatorException) CertificateRevokedException(java.security.cert.CertificateRevokedException) CertificateException(java.security.cert.CertificateException) SSLException(javax.net.ssl.SSLException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) CertPathValidatorException(java.security.cert.CertPathValidatorException) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) X509TrustManager(javax.net.ssl.X509TrustManager) File(java.io.File) ManagerFactoryParameters(javax.net.ssl.ManagerFactoryParameters) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 28 with CertificateExpiredException

use of java.security.cert.CertificateExpiredException in project XobotOS by xamarin.

the class RFC3280CertPathUtilities method processCertA.

protected static void processCertA(CertPath certPath, ExtendedPKIXParameters paramsPKIX, int index, PublicKey workingPublicKey, boolean verificationAlreadyPerformed, X500Principal workingIssuerName, X509Certificate sign) throws ExtCertPathValidatorException {
    List certs = certPath.getCertificates();
    X509Certificate cert = (X509Certificate) certs.get(index);
    //
    if (!verificationAlreadyPerformed) {
        try {
            // (a) (1)
            //
            CertPathValidatorUtilities.verifyX509Certificate(cert, workingPublicKey, paramsPKIX.getSigProvider());
        } catch (GeneralSecurityException e) {
            throw new ExtCertPathValidatorException("Could not validate certificate signature.", e, certPath, index);
        }
    }
    try {
        // (a) (2)
        //
        cert.checkValidity(CertPathValidatorUtilities.getValidCertDateFromValidityModel(paramsPKIX, certPath, index));
    } catch (CertificateExpiredException e) {
        throw new ExtCertPathValidatorException("Could not validate certificate: " + e.getMessage(), e, certPath, index);
    } catch (CertificateNotYetValidException e) {
        throw new ExtCertPathValidatorException("Could not validate certificate: " + e.getMessage(), e, certPath, index);
    } catch (AnnotatedException e) {
        throw new ExtCertPathValidatorException("Could not validate time of certificate.", e, certPath, index);
    }
    //
    if (paramsPKIX.isRevocationEnabled()) {
        try {
            checkCRLs(paramsPKIX, cert, CertPathValidatorUtilities.getValidCertDateFromValidityModel(paramsPKIX, certPath, index), sign, workingPublicKey, certs);
        } catch (AnnotatedException e) {
            Throwable cause = e;
            if (null != e.getCause()) {
                cause = e.getCause();
            }
            throw new ExtCertPathValidatorException(e.getMessage(), cause, certPath, index);
        }
    }
    //
    if (!CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert).equals(workingIssuerName)) {
        throw new ExtCertPathValidatorException("IssuerName(" + CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert) + ") does not match SubjectName(" + workingIssuerName + ") of signing certificate.", null, certPath, index);
    }
}
Also used : CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) CertificateExpiredException(java.security.cert.CertificateExpiredException) GeneralSecurityException(java.security.GeneralSecurityException) List(java.util.List) ArrayList(java.util.ArrayList) X509Certificate(java.security.cert.X509Certificate)

Example 29 with CertificateExpiredException

use of java.security.cert.CertificateExpiredException in project otertool by wuntee.

the class JarSigner method getAliasInfo.

void getAliasInfo(String alias) throws JarSigningException {
    Key key = null;
    try {
        java.security.cert.Certificate[] cs = null;
        try {
            cs = store.getCertificateChain(alias);
        } catch (KeyStoreException kse) {
        // this never happens, because keystore has been loaded
        }
        if (cs == null) {
            MessageFormat form = new MessageFormat(rb.getString("Certificate chain not found for: alias.  alias must reference a valid KeyStore key entry containing a private key and corresponding public key certificate chain."));
            Object[] source = { alias, alias };
            error(form.format(source));
        }
        certChain = new X509Certificate[cs.length];
        for (int i = 0; i < cs.length; i++) {
            if (!(cs[i] instanceof X509Certificate)) {
                error(rb.getString("found non-X.509 certificate in signer's chain"));
            }
            certChain[i] = (X509Certificate) cs[i];
        }
        // order the cert chain if necessary (put user cert first,
        // root-cert last in the chain)
        X509Certificate userCert = (X509Certificate) store.getCertificate(alias);
        // check validity of signer certificate
        try {
            userCert.checkValidity();
            if (userCert.getNotAfter().getTime() < System.currentTimeMillis() + SIX_MONTHS) {
                hasExpiringCert = true;
            }
        } catch (CertificateExpiredException cee) {
            hasExpiredCert = true;
        } catch (CertificateNotYetValidException cnyve) {
            notYetValidCert = true;
        }
        checkCertUsage(userCert, null);
        if (!userCert.equals(certChain[0])) {
            // need to order ...
            X509Certificate[] certChainTmp = new X509Certificate[certChain.length];
            certChainTmp[0] = userCert;
            Principal issuer = userCert.getIssuerDN();
            for (int i = 1; i < certChain.length; i++) {
                int j;
                // given issuer
                for (j = 0; j < certChainTmp.length; j++) {
                    if (certChainTmp[j] == null)
                        continue;
                    Principal subject = certChainTmp[j].getSubjectDN();
                    if (issuer.equals(subject)) {
                        certChain[i] = certChainTmp[j];
                        issuer = certChainTmp[j].getIssuerDN();
                        certChainTmp[j] = null;
                        break;
                    }
                }
                if (j == certChainTmp.length) {
                    error(rb.getString("incomplete certificate chain"));
                }
            }
            // ordered
            certChain = certChainTmp;
        }
        try {
            if (!token && keypass == null)
                key = store.getKey(alias, storepass);
            else
                key = store.getKey(alias, keypass);
        } catch (UnrecoverableKeyException e) {
            if (token) {
                throw e;
            }
        }
    } catch (NoSuchAlgorithmException e) {
        error(e.getMessage());
    } catch (UnrecoverableKeyException e) {
        error(rb.getString("unable to recover key from keystore"));
    } catch (KeyStoreException kse) {
    // this never happens, because keystore has been loaded
    }
    if (!(key instanceof PrivateKey)) {
        MessageFormat form = new MessageFormat(rb.getString("key associated with alias not a private key"));
        Object[] source = { alias };
        error(form.format(source));
    } else {
        privateKey = (PrivateKey) key;
    }
}
Also used : CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) PrivateKey(java.security.PrivateKey) MessageFormat(java.text.MessageFormat) CertificateExpiredException(java.security.cert.CertificateExpiredException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X509Certificate(java.security.cert.X509Certificate) UnrecoverableKeyException(java.security.UnrecoverableKeyException) Key(java.security.Key) PrivateKey(java.security.PrivateKey) Principal(java.security.Principal) X509Certificate(java.security.cert.X509Certificate)

Example 30 with CertificateExpiredException

use of java.security.cert.CertificateExpiredException in project mobile-center-sdk-android by Microsoft.

the class CryptoTest method verifyRsaPreferred.

private void verifyRsaPreferred(int apiLevel) throws Exception {
    CryptoUtils cryptoUtils = new CryptoUtils(mContext, mCryptoFactory, apiLevel);
    String encrypted = cryptoUtils.encrypt("anything");
    assertEquals(CIPHER_RSA + "/" + RSA_KEY_SIZE + ALGORITHM_DATA_SEPARATOR + "anything", encrypted);
    CryptoUtils.DecryptedData decryptedData = cryptoUtils.decrypt(encrypted);
    assertEquals("anything", decryptedData.getDecryptedData());
    assertNull(decryptedData.getNewEncryptedData());
    /* Test old data encryption upgrade. */
    CryptoUtils.DecryptedData oldDecryptedData = cryptoUtils.decrypt("None:oldData");
    assertEquals("oldData", oldDecryptedData.getDecryptedData());
    assertEquals(CIPHER_RSA + "/" + RSA_KEY_SIZE + ALGORITHM_DATA_SEPARATOR + "oldData", oldDecryptedData.getNewEncryptedData());
    /* Check we can still read data after expiration. */
    doThrow(new CertificateExpiredException()).doNothing().when(mRsaCert).checkValidity();
    decryptedData = cryptoUtils.decrypt(encrypted);
    assertEquals("anything", decryptedData.getDecryptedData());
    assertNull(decryptedData.getNewEncryptedData());
    /* But encrypt will use another cert. */
    encrypted = cryptoUtils.encrypt("anything");
    assertEquals(CIPHER_RSA + "/" + RSA_KEY_SIZE + ALGORITHM_DATA_SEPARATOR + "anything", encrypted);
    /* Verify another cert was created. */
    ArgumentCaptor<String> alias = ArgumentCaptor.forClass(String.class);
    verify(mRsaBuilder, times(2)).setAlias(alias.capture());
    String alias0 = alias.getAllValues().get(0);
    String alias1 = alias.getAllValues().get(1);
    assertNotEquals(alias0, alias1);
    verify(mKeyStore).getEntry(alias1, null);
    /* Count how many times alias0 was used to test interactions after more easily... */
    alias = ArgumentCaptor.forClass(String.class);
    verify(mKeyStore, atLeastOnce()).getEntry(alias.capture(), any(KeyStore.ProtectionParameter.class));
    int alias0count = 0;
    for (String aliasValue : alias.getAllValues()) {
        if (aliasValue.equals(alias0)) {
            alias0count++;
        }
    }
    /* If we restart crypto utils it must pick up the second cert. */
    when(mKeyStore.containsAlias(alias0)).thenReturn(true);
    when(mKeyStore.containsAlias(alias1)).thenReturn(true);
    Calendar calendar = Calendar.getInstance();
    when(mKeyStore.getCreationDate(alias0)).thenReturn(calendar.getTime());
    calendar.add(Calendar.YEAR, 1);
    when(mKeyStore.getCreationDate(alias1)).thenReturn(calendar.getTime());
    cryptoUtils = new CryptoUtils(mContext, mCryptoFactory, apiLevel);
    encrypted = cryptoUtils.encrypt("anything");
    assertEquals(CIPHER_RSA + "/" + RSA_KEY_SIZE + ALGORITHM_DATA_SEPARATOR + "anything", encrypted);
    /* Check alias0 no more used and that we used second alias to encrypt that value. */
    verify(mKeyStore, times(alias0count)).getEntry(alias0, null);
    verify(mKeyStore, times(2)).getEntry(alias1, null);
    /* Roll over a second time. */
    doThrow(new CertificateExpiredException()).doNothing().when(mRsaCert).checkValidity();
    encrypted = cryptoUtils.encrypt("anything");
    assertEquals(CIPHER_RSA + "/" + RSA_KEY_SIZE + ALGORITHM_DATA_SEPARATOR + "anything", encrypted);
    /* Verify another cert was created with reusing first alias name, deleting old one. */
    alias = ArgumentCaptor.forClass(String.class);
    verify(mRsaBuilder, times(3)).setAlias(alias.capture());
    assertNotEquals(alias0, alias1);
    assertEquals(alias0, alias.getAllValues().get(2));
    verify(mKeyStore).deleteEntry(alias0);
    verify(mKeyStore, times(alias0count + 1)).getEntry(alias0, null);
    verify(mKeyStore, times(3)).getEntry(alias1, null);
    /* Check that it will reload alias0 again after restart. */
    calendar.add(Calendar.YEAR, 1);
    when(mKeyStore.getCreationDate(alias0)).thenReturn(calendar.getTime());
    cryptoUtils = new CryptoUtils(mContext, mCryptoFactory, apiLevel);
    encrypted = cryptoUtils.encrypt("anything");
    assertEquals(CIPHER_RSA + "/" + RSA_KEY_SIZE + ALGORITHM_DATA_SEPARATOR + "anything", encrypted);
    verify(mKeyStore, times(alias0count + 2)).getEntry(alias0, null);
    verify(mKeyStore, times(3)).getEntry(alias1, null);
}
Also used : CertificateExpiredException(java.security.cert.CertificateExpiredException) Calendar(java.util.Calendar) Matchers.anyString(org.mockito.Matchers.anyString) SuppressLint(android.annotation.SuppressLint)

Aggregations

CertificateExpiredException (java.security.cert.CertificateExpiredException)46 X509Certificate (java.security.cert.X509Certificate)32 CertificateNotYetValidException (java.security.cert.CertificateNotYetValidException)28 CertificateException (java.security.cert.CertificateException)15 ArrayList (java.util.ArrayList)7 GeneralSecurityException (java.security.GeneralSecurityException)6 InvalidKeyException (java.security.InvalidKeyException)6 KeyStore (java.security.KeyStore)6 Certificate (java.security.cert.Certificate)6 IOException (java.io.IOException)5 KeyStoreException (java.security.KeyStoreException)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 Date (java.util.Date)5 SuppressLint (android.annotation.SuppressLint)4 Principal (java.security.Principal)4 Calendar (java.util.Calendar)4 Test (org.junit.Test)4 FileNotFoundException (java.io.FileNotFoundException)3 CertificateFactory (java.security.cert.CertificateFactory)3 X509TrustManager (javax.net.ssl.X509TrustManager)3