Java Code Examples for java.security.PublicKey#equals()

The following examples show how to use java.security.PublicKey#equals() . 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: SecurityCheck.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static boolean checkRpkIdentity(String endpoint, Identity clientIdentity, SecurityInfo securityInfo) {
    // Manage RPK authentication
    // ----------------------------------------------------
    PublicKey publicKey = clientIdentity.getRawPublicKey();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Registration request received using the secure endpoint with rpk '{}'",
                Hex.encodeHexString(publicKey.getEncoded()));
    }

    if (publicKey == null || !publicKey.equals(securityInfo.getRawPublicKey())) {
        if (LOG.isWarnEnabled()) {
            LOG.warn("Invalid rpk for client {}: expected \n'{}'\n but was \n'{}'", endpoint,
                    Hex.encodeHexString(securityInfo.getRawPublicKey().getEncoded()),
                    Hex.encodeHexString(publicKey.getEncoded()));
        }
        return false;
    } else {
        LOG.debug("authenticated client '{}' using DTLS RPK", endpoint);
        return true;
    }
}
 
Example 2
Source File: SinglePublicKeyAuthTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testPublicKeyAuthWithCache() throws Exception {
    final ConcurrentHashMap<String, AtomicInteger> count = new ConcurrentHashMap<String, AtomicInteger>();
    TestCachingPublicKeyAuthenticator auth = new TestCachingPublicKeyAuthenticator(new PublickeyAuthenticator() {
        @SuppressWarnings("synthetic-access")
        @Override
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            String fp = KeyUtils.getFingerPrint(key);
            count.putIfAbsent(fp, new AtomicInteger());
            count.get(fp).incrementAndGet();
            return key.equals(pairRsa.getPublic());
        }
    });
    delegate = auth;

    try (SshClient client = setupTestClient()) {
        client.start();

        try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
            session.addPublicKeyIdentity(pairRsaBad);
            session.addPublicKeyIdentity(pairRsa);
            session.auth().verify(5L, TimeUnit.SECONDS);

            assertEquals("Mismatched authentication invocations count", 2, count.size());

            String fpBad = KeyUtils.getFingerPrint(pairRsaBad.getPublic());
            String fpGood = KeyUtils.getFingerPrint(pairRsa.getPublic());
            assertTrue("Missing bad public key", count.containsKey(fpBad));
            assertTrue("Missing good public key", count.containsKey(fpGood));
            assertEquals("Mismatched bad key authentication attempts", 1, count.get(fpBad).get());
            assertEquals("Mismatched good key authentication attempts", 1, count.get(fpGood).get());
        } finally {
            client.stop();
        }
    }

    Thread.sleep(100L);
    assertTrue("Cache not empty", auth.getCache().isEmpty());
}
 
Example 3
Source File: AIACertificateSource.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private CertificateToken findBestBridgeCertificate(Collection<CertificateToken> candidates) {
		if (Utils.collectionSize(candidates) <= 1) {
			return null;
		}
		PublicKey commonPublicKey = null;
		CertificateToken bestMatch = null;
		for (CertificateToken candidate : candidates) {
			PublicKey candidatePublicKey = candidate.getPublicKey();
			if (commonPublicKey == null) {
				if (!certificate.isSignedBy(candidate)) {
					return null;
				}
				commonPublicKey = candidatePublicKey;
				bestMatch = candidate;
			} else if (!candidatePublicKey.equals(commonPublicKey)) {
				return null;
			} else if (isTrusted(bestMatch)) {
				continue;
			}

//			Set<CertificateToken> tokensSet = validationCertificatePool.get(candidate.getSubject());
//			for (CertificateToken pooledToken : tokensSet) {
//				if (pooledToken.getPublicKey().equals(commonPublicKey) && isTrusted(pooledToken)) {
//					bestMatch = pooledToken;
//					certificate.isSignedBy(pooledToken);
//					break;
//				}
//			}
		}

		return bestMatch;
	}
 
Example 4
Source File: ForwardBuilder.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Verifies whether the input certificate completes the path.
 * Checks the cert against each trust anchor that was specified, in order,
 * and returns true as soon as it finds a valid anchor.
 * Returns true if the cert matches a trust anchor specified as a
 * certificate or if the cert verifies with a trust anchor that
 * was specified as a trusted {pubkey, caname} pair. Returns false if none
 * of the trust anchors are valid for this cert.
 *
 * @param cert the certificate to test
 * @return a boolean value indicating whether the cert completes the path.
 */
@Override
boolean isPathCompleted(X509Certificate cert) {
    for (TrustAnchor anchor : trustAnchors) {
        if (anchor.getTrustedCert() != null) {
            if (cert.equals(anchor.getTrustedCert())) {
                this.trustAnchor = anchor;
                return true;
            } else {
                continue;
            }
        }
        X500Principal principal = anchor.getCA();
        PublicKey publicKey = anchor.getCAPublicKey();

        if (principal != null && publicKey != null &&
                principal.equals(cert.getSubjectX500Principal())) {
            if (publicKey.equals(cert.getPublicKey())) {
                // the cert itself is a trust anchor
                this.trustAnchor = anchor;
                return true;
            }
            // else, it is a self-issued certificate of the anchor
        }

        // Check subject/issuer name chaining
        if (principal == null ||
                !principal.equals(cert.getIssuerX500Principal())) {
            continue;
        }

        // skip anchor if it contains a DSA key with no DSA params
        if (PKIX.isDSAPublicKeyWithoutParams(publicKey)) {
            continue;
        }

        /*
         * Check signature
         */
        try {
            cert.verify(publicKey, buildParams.sigProvider());
        } catch (InvalidKeyException ike) {
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() invalid "
                              + "DSA key found");
            }
            continue;
        } catch (GeneralSecurityException e){
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() " +
                              "unexpected exception");
                e.printStackTrace();
            }
            continue;
        }

        this.trustAnchor = anchor;
        return true;
    }

    return false;
}
 
Example 5
Source File: Main.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Establishes a certificate chain (using trusted certificates in the
 * keystore), starting with the user certificate
 * and ending at a self-signed certificate found in the keystore.
 *
 * @param userCert the user certificate of the alias
 * @param certToVerify the single certificate provided in the reply
 */
private Certificate[] establishCertChain(Certificate userCert,
                                         Certificate certToVerify)
    throws Exception
{
    if (userCert != null) {
        // Make sure that the public key of the certificate reply matches
        // the original public key in the keystore
        PublicKey origPubKey = userCert.getPublicKey();
        PublicKey replyPubKey = certToVerify.getPublicKey();
        if (!origPubKey.equals(replyPubKey)) {
            throw new Exception(rb.getString
                    ("Public.keys.in.reply.and.keystore.don.t.match"));
        }

        // If the two certs are identical, we're done: no need to import
        // anything
        if (certToVerify.equals(userCert)) {
            throw new Exception(rb.getString
                    ("Certificate.reply.and.certificate.in.keystore.are.identical"));
        }
    }

    // Build a hash table of all certificates in the keystore.
    // Use the subject distinguished name as the key into the hash table.
    // All certificates associated with the same subject distinguished
    // name are stored in the same hash table entry as a vector.
    Hashtable<Principal, Vector<Certificate>> certs = null;
    if (keyStore.size() > 0) {
        certs = new Hashtable<Principal, Vector<Certificate>>(11);
        keystorecerts2Hashtable(keyStore, certs);
    }
    if (trustcacerts) {
        if (caks!=null && caks.size()>0) {
            if (certs == null) {
                certs = new Hashtable<Principal, Vector<Certificate>>(11);
            }
            keystorecerts2Hashtable(caks, certs);
        }
    }

    // start building chain
    Vector<Certificate> chain = new Vector<>(2);
    if (buildChain((X509Certificate)certToVerify, chain, certs)) {
        Certificate[] newChain = new Certificate[chain.size()];
        // buildChain() returns chain with self-signed root-cert first and
        // user-cert last, so we need to invert the chain before we store
        // it
        int j=0;
        for (int i=chain.size()-1; i>=0; i--) {
            newChain[j] = chain.elementAt(i);
            j++;
        }
        return newChain;
    } else {
        throw new Exception
            (rb.getString("Failed.to.establish.chain.from.reply"));
    }
}
 
Example 6
Source File: AbstractSupportingTokenPolicyValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Check that a WSSecurityEngineResult corresponding to a signature or encryption uses the same
 * signing/encrypting credential as one of the tokens.
 * @param result a WSSecurityEngineResult corresponding to a signature or encryption
 * @param tokenResult A list of WSSecurityEngineResults corresponding to tokens
 * @return
 */
private boolean checkSignatureOrEncryptionResult(
    WSSecurityEngineResult result,
    List<WSSecurityEngineResult> tokenResult
) {
    // See what was used to sign/encrypt this result
    X509Certificate cert =
        (X509Certificate)result.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
    byte[] secret = (byte[])result.get(WSSecurityEngineResult.TAG_SECRET);
    PublicKey publicKey =
        (PublicKey)result.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);

    // Now see if the same credential exists in the tokenResult list
    for (WSSecurityEngineResult token : tokenResult) {
        Integer actInt = (Integer)token.get(WSSecurityEngineResult.TAG_ACTION);
        BinarySecurity binarySecurity =
            (BinarySecurity)token.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);
        if (binarySecurity instanceof X509Security
            || binarySecurity instanceof PKIPathSecurity) {
            X509Certificate foundCert =
                (X509Certificate)token.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
            if (foundCert.equals(cert)) {
                return true;
            }
        } else if (actInt.intValue() == WSConstants.ST_SIGNED
            || actInt.intValue() == WSConstants.ST_UNSIGNED) {
            SamlAssertionWrapper assertionWrapper =
                (SamlAssertionWrapper)token.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
            SAMLKeyInfo samlKeyInfo = assertionWrapper.getSubjectKeyInfo();
            if (samlKeyInfo != null) {
                X509Certificate[] subjectCerts = samlKeyInfo.getCerts();
                byte[] subjectSecretKey = samlKeyInfo.getSecret();
                PublicKey subjectPublicKey = samlKeyInfo.getPublicKey();
                if ((cert != null && subjectCerts != null && cert.equals(subjectCerts[0]))
                    || (subjectSecretKey != null && Arrays.equals(subjectSecretKey, secret))
                    || (subjectPublicKey != null && subjectPublicKey.equals(publicKey))) {
                    return true;
                }
            }
        } else if (publicKey != null) {
            PublicKey foundPublicKey =
                (PublicKey)token.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);
            if (publicKey.equals(foundPublicKey)) {
                return true;
            }
        } else {
            byte[] foundSecret = (byte[])token.get(WSSecurityEngineResult.TAG_SECRET);
            byte[] derivedKey =
                (byte[])token.get(WSSecurityEngineResult.TAG_ENCRYPTED_EPHEMERAL_KEY);
            if ((foundSecret != null && Arrays.equals(foundSecret, secret))
                || (derivedKey != null && Arrays.equals(derivedKey, secret))) {
                return true;
            }
        }
    }

    return false;
}
 
Example 7
Source File: ForwardBuilder.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Verifies whether the input certificate completes the path.
 * Checks the cert against each trust anchor that was specified, in order,
 * and returns true as soon as it finds a valid anchor.
 * Returns true if the cert matches a trust anchor specified as a
 * certificate or if the cert verifies with a trust anchor that
 * was specified as a trusted {pubkey, caname} pair. Returns false if none
 * of the trust anchors are valid for this cert.
 *
 * @param cert the certificate to test
 * @return a boolean value indicating whether the cert completes the path.
 */
@Override
boolean isPathCompleted(X509Certificate cert) {
    for (TrustAnchor anchor : trustAnchors) {
        if (anchor.getTrustedCert() != null) {
            if (cert.equals(anchor.getTrustedCert())) {
                this.trustAnchor = anchor;
                return true;
            } else {
                continue;
            }
        }
        X500Principal principal = anchor.getCA();
        PublicKey publicKey = anchor.getCAPublicKey();

        if (principal != null && publicKey != null &&
                principal.equals(cert.getSubjectX500Principal())) {
            if (publicKey.equals(cert.getPublicKey())) {
                // the cert itself is a trust anchor
                this.trustAnchor = anchor;
                return true;
            }
            // else, it is a self-issued certificate of the anchor
        }

        // Check subject/issuer name chaining
        if (principal == null ||
                !principal.equals(cert.getIssuerX500Principal())) {
            continue;
        }

        // skip anchor if it contains a DSA key with no DSA params
        if (PKIX.isDSAPublicKeyWithoutParams(publicKey)) {
            continue;
        }

        /*
         * Check signature
         */
        try {
            cert.verify(publicKey, buildParams.sigProvider());
        } catch (InvalidKeyException ike) {
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() invalid "
                              + "DSA key found");
            }
            continue;
        } catch (GeneralSecurityException e){
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() " +
                              "unexpected exception");
                e.printStackTrace();
            }
            continue;
        }

        this.trustAnchor = anchor;
        return true;
    }

    return false;
}
 
Example 8
Source File: ForwardBuilder.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Verifies whether the input certificate completes the path.
 * Checks the cert against each trust anchor that was specified, in order,
 * and returns true as soon as it finds a valid anchor.
 * Returns true if the cert matches a trust anchor specified as a
 * certificate or if the cert verifies with a trust anchor that
 * was specified as a trusted {pubkey, caname} pair. Returns false if none
 * of the trust anchors are valid for this cert.
 *
 * @param cert the certificate to test
 * @return a boolean value indicating whether the cert completes the path.
 */
@Override
boolean isPathCompleted(X509Certificate cert) {
    for (TrustAnchor anchor : trustAnchors) {
        if (anchor.getTrustedCert() != null) {
            if (cert.equals(anchor.getTrustedCert())) {
                this.trustAnchor = anchor;
                return true;
            } else {
                continue;
            }
        }
        X500Principal principal = anchor.getCA();
        PublicKey publicKey = anchor.getCAPublicKey();

        if (principal != null && publicKey != null &&
                principal.equals(cert.getSubjectX500Principal())) {
            if (publicKey.equals(cert.getPublicKey())) {
                // the cert itself is a trust anchor
                this.trustAnchor = anchor;
                return true;
            }
            // else, it is a self-issued certificate of the anchor
        }

        // Check subject/issuer name chaining
        if (principal == null ||
                !principal.equals(cert.getIssuerX500Principal())) {
            continue;
        }

        // skip anchor if it contains a DSA key with no DSA params
        if (PKIX.isDSAPublicKeyWithoutParams(publicKey)) {
            continue;
        }

        /*
         * Check signature
         */
        try {
            if (buildParams.sigProvider() != null) {
                cert.verify(publicKey, buildParams.sigProvider());
            } else {
                cert.verify(publicKey);
            }
        } catch (InvalidKeyException ike) {
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() invalid "
                              + "DSA key found");
            }
            continue;
        } catch (GeneralSecurityException e){
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() " +
                              "unexpected exception");
                e.printStackTrace();
            }
            continue;
        }

        this.trustAnchor = anchor;
        return true;
    }

    return false;
}
 
Example 9
Source File: Main.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Establishes a certificate chain (using trusted certificates in the
 * keystore and cacerts), starting with the reply (certToVerify)
 * and ending at a self-signed certificate found in the keystore.
 *
 * @param userCert optional existing certificate, mostly likely be the
 *                 original self-signed cert created by -genkeypair.
 *                 It must have the same public key as certToVerify
 *                 but cannot be the same cert.
 * @param certToVerify the starting certificate to build the chain
 * @returns the established chain, might be null if user decides not
 */
private Certificate[] establishCertChain(Certificate userCert,
                                         Certificate certToVerify)
    throws Exception
{
    if (userCert != null) {
        // Make sure that the public key of the certificate reply matches
        // the original public key in the keystore
        PublicKey origPubKey = userCert.getPublicKey();
        PublicKey replyPubKey = certToVerify.getPublicKey();
        if (!origPubKey.equals(replyPubKey)) {
            throw new Exception(rb.getString
                    ("Public.keys.in.reply.and.keystore.don.t.match"));
        }

        // If the two certs are identical, we're done: no need to import
        // anything
        if (certToVerify.equals(userCert)) {
            throw new Exception(rb.getString
                    ("Certificate.reply.and.certificate.in.keystore.are.identical"));
        }
    }

    // Build a hash table of all certificates in the keystore.
    // Use the subject distinguished name as the key into the hash table.
    // All certificates associated with the same subject distinguished
    // name are stored in the same hash table entry as a vector.
    Hashtable<Principal, Vector<Pair<String,X509Certificate>>> certs = null;
    if (keyStore.size() > 0) {
        certs = new Hashtable<>(11);
        keystorecerts2Hashtable(keyStore, certs);
    }
    if (trustcacerts) {
        if (caks!=null && caks.size()>0) {
            if (certs == null) {
                certs = new Hashtable<>(11);
            }
            keystorecerts2Hashtable(caks, certs);
        }
    }

    // start building chain
    Vector<Pair<String,X509Certificate>> chain = new Vector<>(2);
    if (buildChain(
            new Pair<>(rb.getString("the.input"),
                       (X509Certificate) certToVerify),
            chain, certs)) {
        for (Pair<String,X509Certificate> p : chain) {
            checkWeak(p.fst, p.snd);
        }
        Certificate[] newChain =
                new Certificate[chain.size()];
        // buildChain() returns chain with self-signed root-cert first and
        // user-cert last, so we need to invert the chain before we store
        // it
        int j=0;
        for (int i=chain.size()-1; i>=0; i--) {
            newChain[j] = chain.elementAt(i).snd;
            j++;
        }
        return newChain;
    } else {
        throw new Exception
            (rb.getString("Failed.to.establish.chain.from.reply"));
    }
}
 
Example 10
Source File: AbstractSupportingTokenPolicyValidator.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Check that a WSSecurityEngineResult corresponding to a signature or encryption uses the same 
 * signing/encrypting credential as one of the tokens.
 * @param signatureResult a WSSecurityEngineResult corresponding to a signature or encryption
 * @param tokenResult A list of WSSecurityEngineResults corresponding to tokens
 * @return 
 */
private boolean checkSignatureOrEncryptionResult(
    WSSecurityEngineResult result,
    List<WSSecurityEngineResult> tokenResult
) {
    // See what was used to sign/encrypt this result
    X509Certificate cert = 
        (X509Certificate)result.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
    byte[] secret = (byte[])result.get(WSSecurityEngineResult.TAG_SECRET);
    PublicKey publicKey = 
        (PublicKey)result.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);
    
    // Now see if the same credential exists in the tokenResult list
    for (WSSecurityEngineResult token : tokenResult) {
        Integer actInt = (Integer)token.get(WSSecurityEngineResult.TAG_ACTION);
        BinarySecurity binarySecurity = 
            (BinarySecurity)token.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);
        if (binarySecurity instanceof X509Security
            || binarySecurity instanceof PKIPathSecurity) {
            X509Certificate foundCert = 
                (X509Certificate)token.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
            if (foundCert.equals(cert)) {
                return true;
            }
        } else if (actInt.intValue() == WSConstants.ST_SIGNED
            || actInt.intValue() == WSConstants.ST_UNSIGNED) {
            AssertionWrapper assertionWrapper = 
                (AssertionWrapper)token.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
            SAMLKeyInfo samlKeyInfo = assertionWrapper.getSubjectKeyInfo();
            if (samlKeyInfo != null) {
                X509Certificate[] subjectCerts = samlKeyInfo.getCerts();
                byte[] subjectSecretKey = samlKeyInfo.getSecret();
                PublicKey subjectPublicKey = samlKeyInfo.getPublicKey();
                if ((cert != null && subjectCerts != null && cert.equals(subjectCerts[0]))
                    || (subjectSecretKey != null && Arrays.equals(subjectSecretKey, secret))
                    || (subjectPublicKey != null && subjectPublicKey.equals(publicKey))) {
                    return true;
                }
            }
        } else if (publicKey != null) {
            PublicKey foundPublicKey = 
                (PublicKey)token.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);
            if (publicKey.equals(foundPublicKey)) {
                return true;
            }
        } else {
            byte[] foundSecret = (byte[])token.get(WSSecurityEngineResult.TAG_SECRET);
            byte[] derivedKey = 
                (byte[])token.get(WSSecurityEngineResult.TAG_ENCRYPTED_EPHEMERAL_KEY);
            if ((foundSecret != null && Arrays.equals(foundSecret, secret))
                || (derivedKey != null && Arrays.equals(derivedKey, secret))) {
                return true;
            }
        }
    }
    
    return false;
}
 
Example 11
Source File: SAMLUtils.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Compare the credentials of the assertion to the credentials used in 2-way TLS or those
 * used to verify signatures.
 * Return true on a match
 * @param subjectKeyInfo the SAMLKeyInfo object
 * @param signedResults a list of all of the signed results
 * @return true if the credentials of the assertion were used to verify a signature
 */
public static boolean compareCredentials(
    SAMLKeyInfo subjectKeyInfo,
    List<WSSecurityEngineResult> signedResults,
    Certificate[] tlsCerts
) {
    X509Certificate[] subjectCerts = subjectKeyInfo.getCerts();
    PublicKey subjectPublicKey = subjectKeyInfo.getPublicKey();
    byte[] subjectSecretKey = subjectKeyInfo.getSecret();
    
    //
    // Try to match the TLS certs first
    //
    if (tlsCerts != null && tlsCerts.length > 0 && subjectCerts != null 
        && subjectCerts.length > 0 && tlsCerts[0].equals(subjectCerts[0])) {
        return true;
    } else if (tlsCerts != null && tlsCerts.length > 0 && subjectPublicKey != null
        && tlsCerts[0].getPublicKey().equals(subjectPublicKey)) {
        return true;
    }
    
    //
    // Now try the message-level signatures
    //
    for (WSSecurityEngineResult signedResult : signedResults) {
        X509Certificate[] certs =
            (X509Certificate[])signedResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATES);
        PublicKey publicKey =
            (PublicKey)signedResult.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);
        byte[] secretKey =
            (byte[])signedResult.get(WSSecurityEngineResult.TAG_SECRET);
        if (certs != null && certs.length > 0 && subjectCerts != null
            && subjectCerts.length > 0 && certs[0].equals(subjectCerts[0])) {
            return true;
        }
        if (publicKey != null && publicKey.equals(subjectPublicKey)) {
            return true;
        }
        if (checkSecretKey(secretKey, subjectSecretKey, signedResult)) {
            return true;
        }
    }
    return false;
}
 
Example 12
Source File: Main.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Establishes a certificate chain (using trusted certificates in the
 * keystore and cacerts), starting with the reply (certToVerify)
 * and ending at a self-signed certificate found in the keystore.
 *
 * @param userCert optional existing certificate, mostly likely be the
 *                 original self-signed cert created by -genkeypair.
 *                 It must have the same public key as certToVerify
 *                 but cannot be the same cert.
 * @param certToVerify the starting certificate to build the chain
 * @returns the established chain, might be null if user decides not
 */
private Certificate[] establishCertChain(Certificate userCert,
                                         Certificate certToVerify)
    throws Exception
{
    if (userCert != null) {
        // Make sure that the public key of the certificate reply matches
        // the original public key in the keystore
        PublicKey origPubKey = userCert.getPublicKey();
        PublicKey replyPubKey = certToVerify.getPublicKey();
        if (!origPubKey.equals(replyPubKey)) {
            throw new Exception(rb.getString
                    ("Public.keys.in.reply.and.keystore.don.t.match"));
        }

        // If the two certs are identical, we're done: no need to import
        // anything
        if (certToVerify.equals(userCert)) {
            throw new Exception(rb.getString
                    ("Certificate.reply.and.certificate.in.keystore.are.identical"));
        }
    }

    // Build a hash table of all certificates in the keystore.
    // Use the subject distinguished name as the key into the hash table.
    // All certificates associated with the same subject distinguished
    // name are stored in the same hash table entry as a vector.
    Hashtable<Principal, Vector<Pair<String,X509Certificate>>> certs = null;
    if (keyStore.size() > 0) {
        certs = new Hashtable<>(11);
        keystorecerts2Hashtable(keyStore, certs);
    }
    if (trustcacerts) {
        if (caks!=null && caks.size()>0) {
            if (certs == null) {
                certs = new Hashtable<>(11);
            }
            keystorecerts2Hashtable(caks, certs);
        }
    }

    // start building chain
    Vector<Pair<String,X509Certificate>> chain = new Vector<>(2);
    if (buildChain(
            new Pair<>(rb.getString("the.input"),
                       (X509Certificate) certToVerify),
            chain, certs)) {
        for (Pair<String,X509Certificate> p : chain) {
            checkWeak(p.fst, p.snd);
        }
        Certificate[] newChain =
                new Certificate[chain.size()];
        // buildChain() returns chain with self-signed root-cert first and
        // user-cert last, so we need to invert the chain before we store
        // it
        int j=0;
        for (int i=chain.size()-1; i>=0; i--) {
            newChain[j] = chain.elementAt(i).snd;
            j++;
        }
        return newChain;
    } else {
        throw new Exception
            (rb.getString("Failed.to.establish.chain.from.reply"));
    }
}
 
Example 13
Source File: SAMLUtils.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Compare the credentials of the assertion to the credentials used in 2-way TLS or those
 * used to verify signatures.
 * Return true on a match
 * @param subjectKeyInfo the SAMLKeyInfo object
 * @param signedResults a list of all of the signed results
 * @return true if the credentials of the assertion were used to verify a signature
 */
public static boolean compareCredentials(
    SAMLKeyInfo subjectKeyInfo,
    List<WSSecurityEngineResult> signedResults,
    Certificate[] tlsCerts
) {
    X509Certificate[] subjectCerts = subjectKeyInfo.getCerts();
    PublicKey subjectPublicKey = subjectKeyInfo.getPublicKey();
    byte[] subjectSecretKey = subjectKeyInfo.getSecret();
    
    //
    // Try to match the TLS certs first
    //
    if (tlsCerts != null && tlsCerts.length > 0 && subjectCerts != null 
        && subjectCerts.length > 0 && tlsCerts[0].equals(subjectCerts[0])) {
        return true;
    } else if (tlsCerts != null && tlsCerts.length > 0 && subjectPublicKey != null
        && tlsCerts[0].getPublicKey().equals(subjectPublicKey)) {
        return true;
    }
    
    //
    // Now try the message-level signatures
    //
    for (WSSecurityEngineResult signedResult : signedResults) {
        X509Certificate[] certs =
            (X509Certificate[])signedResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATES);
        PublicKey publicKey =
            (PublicKey)signedResult.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);
        byte[] secretKey =
            (byte[])signedResult.get(WSSecurityEngineResult.TAG_SECRET);
        if (certs != null && certs.length > 0 && subjectCerts != null
            && subjectCerts.length > 0 && certs[0].equals(subjectCerts[0])) {
            return true;
        }
        if (publicKey != null && publicKey.equals(subjectPublicKey)) {
            return true;
        }
        if (checkSecretKey(secretKey, subjectSecretKey, signedResult)) {
            return true;
        }
    }
    return false;
}
 
Example 14
Source File: AbstractSupportingTokenPolicyValidator.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Check that a WSSecurityEngineResult corresponding to a signature or encryption uses the same 
 * signing/encrypting credential as one of the tokens.
 * @param signatureResult a WSSecurityEngineResult corresponding to a signature or encryption
 * @param tokenResult A list of WSSecurityEngineResults corresponding to tokens
 * @return 
 */
private boolean checkSignatureOrEncryptionResult(
    WSSecurityEngineResult result,
    List<WSSecurityEngineResult> tokenResult
) {
    // See what was used to sign/encrypt this result
    X509Certificate cert = 
        (X509Certificate)result.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
    byte[] secret = (byte[])result.get(WSSecurityEngineResult.TAG_SECRET);
    PublicKey publicKey = 
        (PublicKey)result.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);
    
    // Now see if the same credential exists in the tokenResult list
    for (WSSecurityEngineResult token : tokenResult) {
        Integer actInt = (Integer)token.get(WSSecurityEngineResult.TAG_ACTION);
        BinarySecurity binarySecurity = 
            (BinarySecurity)token.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);
        if (binarySecurity instanceof X509Security
            || binarySecurity instanceof PKIPathSecurity) {
            X509Certificate foundCert = 
                (X509Certificate)token.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
            if (foundCert.equals(cert)) {
                return true;
            }
        } else if (actInt.intValue() == WSConstants.ST_SIGNED
            || actInt.intValue() == WSConstants.ST_UNSIGNED) {
            AssertionWrapper assertionWrapper = 
                (AssertionWrapper)token.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
            SAMLKeyInfo samlKeyInfo = assertionWrapper.getSubjectKeyInfo();
            if (samlKeyInfo != null) {
                X509Certificate[] subjectCerts = samlKeyInfo.getCerts();
                byte[] subjectSecretKey = samlKeyInfo.getSecret();
                PublicKey subjectPublicKey = samlKeyInfo.getPublicKey();
                if ((cert != null && subjectCerts != null && cert.equals(subjectCerts[0]))
                    || (subjectSecretKey != null && Arrays.equals(subjectSecretKey, secret))
                    || (subjectPublicKey != null && subjectPublicKey.equals(publicKey))) {
                    return true;
                }
            }
        } else if (publicKey != null) {
            PublicKey foundPublicKey = 
                (PublicKey)token.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);
            if (publicKey.equals(foundPublicKey)) {
                return true;
            }
        } else {
            byte[] foundSecret = (byte[])token.get(WSSecurityEngineResult.TAG_SECRET);
            byte[] derivedKey = 
                (byte[])token.get(WSSecurityEngineResult.TAG_ENCRYPTED_EPHEMERAL_KEY);
            if ((foundSecret != null && Arrays.equals(foundSecret, secret))
                || (derivedKey != null && Arrays.equals(derivedKey, secret))) {
                return true;
            }
        }
    }
    
    return false;
}
 
Example 15
Source File: LayoutPolicyValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Find the index of the token corresponding to either the X509Certificate or PublicKey used
 * to sign the "signatureResult" argument.
 */
private int findCorrespondingTokenIndex(
    WSSecurityEngineResult signatureResult,
    List<WSSecurityEngineResult> results
) {
    // See what was used to sign this result
    X509Certificate cert =
        (X509Certificate)signatureResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
    PublicKey publicKey =
        (PublicKey)signatureResult.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);

    for (int i = 0; i < results.size(); i++) {
        WSSecurityEngineResult token = results.get(i);
        Integer actInt = (Integer)token.get(WSSecurityEngineResult.TAG_ACTION);
        if (actInt == WSConstants.SIGN) {
            continue;
        }

        BinarySecurity binarySecurity =
            (BinarySecurity)token.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);
        PublicKey foundPublicKey =
            (PublicKey)token.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);
        if (binarySecurity instanceof X509Security
            || binarySecurity instanceof PKIPathSecurity) {
            X509Certificate foundCert =
                (X509Certificate)token.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
            if (foundCert.equals(cert)) {
                return i;
            }
        } else if (actInt.intValue() == WSConstants.ST_SIGNED
            || actInt.intValue() == WSConstants.ST_UNSIGNED) {
            SamlAssertionWrapper assertionWrapper =
                (SamlAssertionWrapper)token.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
            SAMLKeyInfo samlKeyInfo = assertionWrapper.getSubjectKeyInfo();
            if (samlKeyInfo != null) {
                X509Certificate[] subjectCerts = samlKeyInfo.getCerts();
                PublicKey subjectPublicKey = samlKeyInfo.getPublicKey();
                if ((cert != null && subjectCerts != null
                    && cert.equals(subjectCerts[0]))
                    || (subjectPublicKey != null && subjectPublicKey.equals(publicKey))) {
                    return i;
                }
            }
        } else if (publicKey != null && publicKey.equals(foundPublicKey)) {
            return i;
        }
    }
    return -1;
}
 
Example 16
Source File: SinglePublicKeyAuthTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Test
public void testPublicKeyAuthWithoutCache() throws Exception {
    final ConcurrentHashMap<String, AtomicInteger> count = new ConcurrentHashMap<String, AtomicInteger>();
    delegate = new PublickeyAuthenticator() {
        @SuppressWarnings("synthetic-access")
        @Override
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            String fp = KeyUtils.getFingerPrint(key);
            count.putIfAbsent(fp, new AtomicInteger());
            count.get(fp).incrementAndGet();
            return key.equals(pairRsa.getPublic());
        }
    };

    try (SshClient client = setupTestClient()) {
        client.start();

        try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
            session.addPublicKeyIdentity(pairRsaBad);
            session.addPublicKeyIdentity(pairRsa);

            AuthFuture auth = session.auth();
            assertTrue("Failed to authenticate on time", auth.await(5L, TimeUnit.SECONDS));
            assertTrue("Authentication failed", auth.isSuccess());
        } finally {
            client.stop();
        }
    }

    assertEquals("Mismatched attempted keys count", 2, count.size());

    String badFingerPrint = KeyUtils.getFingerPrint(pairRsaBad.getPublic());
    Number badIndex = count.get(badFingerPrint);
    assertNotNull("Missing bad RSA key", badIndex);
    assertEquals("Mismatched attempt index for bad key", 1, badIndex.intValue());

    String goodFingerPrint = KeyUtils.getFingerPrint(pairRsa.getPublic());
    Number goodIndex = count.get(goodFingerPrint);
    assertNotNull("Missing good RSA key", goodIndex);
    assertEquals("Mismatched attempt index for good key", 2, goodIndex.intValue());
}
 
Example 17
Source File: Main.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Establishes a certificate chain (using trusted certificates in the
 * keystore), starting with the user certificate
 * and ending at a self-signed certificate found in the keystore.
 *
 * @param userCert the user certificate of the alias
 * @param certToVerify the single certificate provided in the reply
 */
private Certificate[] establishCertChain(Certificate userCert,
                                         Certificate certToVerify)
    throws Exception
{
    if (userCert != null) {
        // Make sure that the public key of the certificate reply matches
        // the original public key in the keystore
        PublicKey origPubKey = userCert.getPublicKey();
        PublicKey replyPubKey = certToVerify.getPublicKey();
        if (!origPubKey.equals(replyPubKey)) {
            throw new Exception(rb.getString
                    ("Public.keys.in.reply.and.keystore.don.t.match"));
        }

        // If the two certs are identical, we're done: no need to import
        // anything
        if (certToVerify.equals(userCert)) {
            throw new Exception(rb.getString
                    ("Certificate.reply.and.certificate.in.keystore.are.identical"));
        }
    }

    // Build a hash table of all certificates in the keystore.
    // Use the subject distinguished name as the key into the hash table.
    // All certificates associated with the same subject distinguished
    // name are stored in the same hash table entry as a vector.
    Hashtable<Principal, Vector<Certificate>> certs = null;
    if (keyStore.size() > 0) {
        certs = new Hashtable<Principal, Vector<Certificate>>(11);
        keystorecerts2Hashtable(keyStore, certs);
    }
    if (trustcacerts) {
        if (caks!=null && caks.size()>0) {
            if (certs == null) {
                certs = new Hashtable<Principal, Vector<Certificate>>(11);
            }
            keystorecerts2Hashtable(caks, certs);
        }
    }

    // start building chain
    Vector<Certificate> chain = new Vector<>(2);
    if (buildChain((X509Certificate)certToVerify, chain, certs)) {
        Certificate[] newChain = new Certificate[chain.size()];
        // buildChain() returns chain with self-signed root-cert first and
        // user-cert last, so we need to invert the chain before we store
        // it
        int j=0;
        for (int i=chain.size()-1; i>=0; i--) {
            newChain[j] = chain.elementAt(i);
            j++;
        }
        return newChain;
    } else {
        throw new Exception
            (rb.getString("Failed.to.establish.chain.from.reply"));
    }
}
 
Example 18
Source File: ForwardBuilder.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Verifies whether the input certificate completes the path.
 * Checks the cert against each trust anchor that was specified, in order,
 * and returns true as soon as it finds a valid anchor.
 * Returns true if the cert matches a trust anchor specified as a
 * certificate or if the cert verifies with a trust anchor that
 * was specified as a trusted {pubkey, caname} pair. Returns false if none
 * of the trust anchors are valid for this cert.
 *
 * @param cert the certificate to test
 * @return a boolean value indicating whether the cert completes the path.
 */
@Override
boolean isPathCompleted(X509Certificate cert) {
    for (TrustAnchor anchor : trustAnchors) {
        if (anchor.getTrustedCert() != null) {
            if (cert.equals(anchor.getTrustedCert())) {
                this.trustAnchor = anchor;
                return true;
            } else {
                continue;
            }
        }
        X500Principal principal = anchor.getCA();
        PublicKey publicKey = anchor.getCAPublicKey();

        if (principal != null && publicKey != null &&
                principal.equals(cert.getSubjectX500Principal())) {
            if (publicKey.equals(cert.getPublicKey())) {
                // the cert itself is a trust anchor
                this.trustAnchor = anchor;
                return true;
            }
            // else, it is a self-issued certificate of the anchor
        }

        // Check subject/issuer name chaining
        if (principal == null ||
                !principal.equals(cert.getIssuerX500Principal())) {
            continue;
        }

        // skip anchor if it contains a DSA key with no DSA params
        if (PKIX.isDSAPublicKeyWithoutParams(publicKey)) {
            continue;
        }

        /*
         * Check signature
         */
        try {
            cert.verify(publicKey, buildParams.sigProvider());
        } catch (InvalidKeyException ike) {
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() invalid "
                              + "DSA key found");
            }
            continue;
        } catch (GeneralSecurityException e){
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() " +
                              "unexpected exception");
                e.printStackTrace();
            }
            continue;
        }

        this.trustAnchor = anchor;
        return true;
    }

    return false;
}
 
Example 19
Source File: Main.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Establishes a certificate chain (using trusted certificates in the
 * keystore), starting with the user certificate
 * and ending at a self-signed certificate found in the keystore.
 *
 * @param userCert the user certificate of the alias
 * @param certToVerify the single certificate provided in the reply
 */
private Certificate[] establishCertChain(Certificate userCert,
                                         Certificate certToVerify)
    throws Exception
{
    if (userCert != null) {
        // Make sure that the public key of the certificate reply matches
        // the original public key in the keystore
        PublicKey origPubKey = userCert.getPublicKey();
        PublicKey replyPubKey = certToVerify.getPublicKey();
        if (!origPubKey.equals(replyPubKey)) {
            throw new Exception(rb.getString
                    ("Public.keys.in.reply.and.keystore.don.t.match"));
        }

        // If the two certs are identical, we're done: no need to import
        // anything
        if (certToVerify.equals(userCert)) {
            throw new Exception(rb.getString
                    ("Certificate.reply.and.certificate.in.keystore.are.identical"));
        }
    }

    // Build a hash table of all certificates in the keystore.
    // Use the subject distinguished name as the key into the hash table.
    // All certificates associated with the same subject distinguished
    // name are stored in the same hash table entry as a vector.
    Hashtable<Principal, Vector<Certificate>> certs = null;
    if (keyStore.size() > 0) {
        certs = new Hashtable<Principal, Vector<Certificate>>(11);
        keystorecerts2Hashtable(keyStore, certs);
    }
    if (trustcacerts) {
        if (caks!=null && caks.size()>0) {
            if (certs == null) {
                certs = new Hashtable<Principal, Vector<Certificate>>(11);
            }
            keystorecerts2Hashtable(caks, certs);
        }
    }

    // start building chain
    Vector<Certificate> chain = new Vector<>(2);
    if (buildChain((X509Certificate)certToVerify, chain, certs)) {
        Certificate[] newChain = new Certificate[chain.size()];
        // buildChain() returns chain with self-signed root-cert first and
        // user-cert last, so we need to invert the chain before we store
        // it
        int j=0;
        for (int i=chain.size()-1; i>=0; i--) {
            newChain[j] = chain.elementAt(i);
            j++;
        }
        return newChain;
    } else {
        throw new Exception
            (rb.getString("Failed.to.establish.chain.from.reply"));
    }
}
 
Example 20
Source File: Main.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Establishes a certificate chain (using trusted certificates in the
 * keystore), starting with the user certificate
 * and ending at a self-signed certificate found in the keystore.
 *
 * @param userCert the user certificate of the alias
 * @param certToVerify the single certificate provided in the reply
 */
private Certificate[] establishCertChain(Certificate userCert,
                                         Certificate certToVerify)
    throws Exception
{
    if (userCert != null) {
        // Make sure that the public key of the certificate reply matches
        // the original public key in the keystore
        PublicKey origPubKey = userCert.getPublicKey();
        PublicKey replyPubKey = certToVerify.getPublicKey();
        if (!origPubKey.equals(replyPubKey)) {
            throw new Exception(rb.getString
                    ("Public.keys.in.reply.and.keystore.don.t.match"));
        }

        // If the two certs are identical, we're done: no need to import
        // anything
        if (certToVerify.equals(userCert)) {
            throw new Exception(rb.getString
                    ("Certificate.reply.and.certificate.in.keystore.are.identical"));
        }
    }

    // Build a hash table of all certificates in the keystore.
    // Use the subject distinguished name as the key into the hash table.
    // All certificates associated with the same subject distinguished
    // name are stored in the same hash table entry as a vector.
    Hashtable<Principal, Vector<Certificate>> certs = null;
    if (keyStore.size() > 0) {
        certs = new Hashtable<Principal, Vector<Certificate>>(11);
        keystorecerts2Hashtable(keyStore, certs);
    }
    if (trustcacerts) {
        if (caks!=null && caks.size()>0) {
            if (certs == null) {
                certs = new Hashtable<Principal, Vector<Certificate>>(11);
            }
            keystorecerts2Hashtable(caks, certs);
        }
    }

    // start building chain
    Vector<Certificate> chain = new Vector<>(2);
    if (buildChain((X509Certificate)certToVerify, chain, certs)) {
        Certificate[] newChain = new Certificate[chain.size()];
        // buildChain() returns chain with self-signed root-cert first and
        // user-cert last, so we need to invert the chain before we store
        // it
        int j=0;
        for (int i=chain.size()-1; i>=0; i--) {
            newChain[j] = chain.elementAt(i);
            j++;
        }
        return newChain;
    } else {
        throw new Exception
            (rb.getString("Failed.to.establish.chain.from.reply"));
    }
}