List of usage examples for java.security.cert X509Certificate equals
public boolean equals(Object other)
From source file:pl.psnc.synat.wrdz.realm.db.WrdzUserDatabaseHandler.java
/** * Authenticates user using certificate he provided and comparing it to the data in the user database. * //from w w w. j a va2 s . c o m * @param x509Certificate * certificate of the user who is to be authenticated. * @return whether or not user data is valid (passed user data matches data in the database). */ public boolean isUserValid(X509Certificate x509Certificate) { Connection connection = null; PreparedStatement statement = null; ResultSet rs = null; boolean valid = false; String username = findUsername(x509Certificate); try { connection = getConnection(); statement = connection.prepareStatement(certificateQuery); statement.setString(1, username); rs = statement.executeQuery(); if (rs.next()) { X509Certificate certificateFromDB = null; try { CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); certificateFromDB = (X509Certificate) certFactory .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(rs.getString(1)))); } catch (CertificateException e) { logger.log(Level.SEVERE, "Wrong certificate format or data corrupt.", e); return false; } if (certificateFromDB.equals(x509Certificate)) { valid = true; } } } catch (SQLException ex) { logger.log(Level.SEVERE, "Cannot validate user " + username + ", exception: " + ex.toString()); if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "Cannot validate user", ex); } } catch (Exception ex) { logger.log(Level.SEVERE, "Invalid user " + username); if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "Cannot validate user", ex); } } finally { close(connection, statement, rs); } return valid; }
From source file:eu.europa.ec.markt.dss.validation.SignedDocumentValidator.java
/** * For level -XL, every certificates values contained in the ValidationContext (except the SigningCertificate) must * be in the CertificatesValues of the signature * /*from w ww . j a v a 2 s . c o m*/ * @param ctx * @param certificates * @param signingCert * @return */ protected boolean everyCertificateValueAreThere(ValidationContext ctx, List<X509Certificate> certificates, X509Certificate signingCert) { for (CertificateAndContext neededCert : ctx.getNeededCertificates()) { /* We don't need the signing certificate in the XL values */ if (neededCert.getCertificate().equals(signingCert)) { continue; } LOG.info("Looking for the certificate ref of " + neededCert); boolean found = false; for (X509Certificate referencedCert : certificates) { LOG.info("Compare to " + referencedCert.getSubjectDN()); if (referencedCert.equals(neededCert.getCertificate())) { found = true; break; } } LOG.info("Cert " + (found ? " found" : " not found")); if (!found) { return false; } } return true; }
From source file:controller.CCInstance.java
public final Certificate[] getCompleteTrustedCertificateChain(final X509Certificate x509c) throws KeyStoreException, IOException, FileNotFoundException, NoSuchAlgorithmException, CertificateException, InvalidAlgorithmParameterException { final ArrayList<X509Certificate> certChainList = new ArrayList<>(); certChainList.add(x509c);//from w w w.ja va 2 s.co m X509Certificate temp = x509c; while (true) { X509Certificate issuer = (X509Certificate) hasTrustedIssuerCertificate(temp); if (null != issuer) { if (temp.equals(issuer)) { break; } certChainList.add(issuer); temp = issuer; } else { break; } } final Certificate[] certificateChain = new Certificate[certChainList.size()]; for (int i = 0; i < certChainList.size(); i++) { certificateChain[i] = certChainList.get(i); } return certificateChain; }
From source file:org.josso.gateway.identity.service.store.MemoryIdentityStore.java
/** * Load user UID (username) from store./*from w ww . ja va 2s .co m*/ * * @param key the key used to load UID from store. * @param cp credential provider * @throws SSOIdentityException */ public String loadUID(CredentialKey key, CredentialProvider cp) throws SSOIdentityException { if (!(key instanceof SimpleUserKey)) { throw new SSOIdentityException("Unsupported key type : " + key.getClass().getName()); } SimpleUserKey simpleKey = (SimpleUserKey) key; if (key instanceof CertificateUserKey) { X509Certificate certificate = ((CertificateUserKey) key).getCertificate(); if (certificate != null) { List<Element> credentialElements = getCredentialElements(simpleKey, cp); for (Element credentialElement : credentialElements) { List<Credential> creds = toCredentials(credentialElement, cp); for (Credential cred : creds) { if (((BaseCredential) cred).getValue() instanceof X509Certificate && certificate.equals((X509Certificate) ((BaseCredential) cred).getValue())) { return getTextContent(credentialElement.getElementsByTagName("key").item(0)); } } } } } else { return simpleKey.getId(); } return null; }
From source file:be.fedict.eid.applet.service.impl.handler.AuthenticationDataMessageHandler.java
public Object handleMessage(AuthenticationDataMessage message, Map<String, String> httpHeaders, HttpServletRequest request, HttpSession session) throws ServletException { LOG.debug("authentication data message received"); if (null == message.authnCert) { /*// w ww . j a v a 2 s .co m * Can be the case for future (Kids) eID cards that have some * certificates missing. */ String msg = "authentication certificate not present"; LOG.warn(msg); throw new ServletException(msg); } byte[] signatureValue = message.signatureValue; LOG.debug("authn signing certificate subject: " + message.authnCert.getSubjectX500Principal()); PublicKey signingKey = message.authnCert.getPublicKey(); if (this.sessionIdChannelBinding) { checkSessionIdChannelBinding(message, request); if (null == this.serverCertificate) { LOG.warn("adviced to use in combination with server certificate channel binding"); } } ChannelBindingService channelBindingService = this.channelBindingServiceLocator.locateService(); if (null != this.serverCertificate || null != channelBindingService) { LOG.debug("using server certificate channel binding"); } if (false == this.sessionIdChannelBinding && null == this.serverCertificate && null == channelBindingService) { LOG.warn("not using any secure channel binding"); } byte[] challenge; try { challenge = AuthenticationChallenge.getAuthnChallenge(session, this.maxMaturity); } catch (SecurityException e) { AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { String remoteAddress = request.getRemoteAddr(); auditService.authenticationError(remoteAddress, message.authnCert); } throw new ServletException("security error: " + e.getMessage(), e); } byte[] serverCertificateClientPOV = null; try { if (null != message.serverCertificate) { serverCertificateClientPOV = message.serverCertificate.getEncoded(); } } catch (CertificateEncodingException e) { throw new ServletException("server cert decoding error: " + e.getMessage(), e); } /* * We validate the authentication contract using the client-side * communicated server SSL certificate in case of secure channel * binding. */ AuthenticationContract authenticationContract = new AuthenticationContract(message.saltValue, this.hostname, this.inetAddress, message.sessionId, serverCertificateClientPOV, challenge); byte[] toBeSigned; try { toBeSigned = authenticationContract.calculateToBeSigned(); } catch (IOException e) { throw new ServletException("IO error: " + e.getMessage(), e); } try { Signature signature = Signature.getInstance("SHA1withRSA"); signature.initVerify(signingKey); signature.update(toBeSigned); boolean result = signature.verify(signatureValue); if (false == result) { AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { String remoteAddress = request.getRemoteAddr(); auditService.authenticationError(remoteAddress, message.authnCert); } throw new SecurityException("authn signature incorrect"); } } catch (NoSuchAlgorithmException e) { throw new SecurityException("algo error"); } catch (InvalidKeyException e) { throw new SecurityException("authn key error"); } catch (SignatureException e) { throw new SecurityException("signature error"); } RequestContext requestContext = new RequestContext(session); String transactionMessage = requestContext.getTransactionMessage(); if (null != transactionMessage) { LOG.debug("verifying TransactionMessage signature"); byte[] transactionMessageSignature = message.transactionMessageSignature; if (null == transactionMessageSignature) { throw new SecurityException("missing TransactionMessage signature"); } try { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, signingKey); byte[] signatureDigestInfoValue = cipher.doFinal(transactionMessageSignature); ASN1InputStream aIn = new ASN1InputStream(signatureDigestInfoValue); DigestInfo signatureDigestInfo = new DigestInfo((ASN1Sequence) aIn.readObject()); if (false == PLAIN_TEXT_DIGEST_ALGO_OID .equals(signatureDigestInfo.getAlgorithmId().getObjectId().getId())) { throw new SecurityException("TransactionMessage signature algo OID incorrect"); } if (false == Arrays.equals(transactionMessage.getBytes(), signatureDigestInfo.getDigest())) { throw new SecurityException("signed TransactionMessage incorrect"); } LOG.debug("TransactionMessage signature validated"); } catch (Exception e) { LOG.error("error verifying TransactionMessage signature", e); AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { String remoteAddress = request.getRemoteAddr(); auditService.authenticationError(remoteAddress, message.authnCert); } throw new SecurityException("error verifying TransactionMessage signature: " + e.getMessage()); } } /* * Secure channel binding verification. */ if (null != channelBindingService) { X509Certificate serverCertificate = channelBindingService.getServerCertificate(); if (null == serverCertificate) { LOG.warn("could not verify secure channel binding as the server does not know its identity yet"); } else { if (false == serverCertificate.equals(message.serverCertificate)) { AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { String remoteAddress = request.getRemoteAddr(); auditService.authenticationError(remoteAddress, message.authnCert); } throw new SecurityException("secure channel binding identity mismatch"); } LOG.debug("secure channel binding verified"); } } else { if (null != this.serverCertificate) { if (false == this.serverCertificate.equals(message.serverCertificate)) { AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { String remoteAddress = request.getRemoteAddr(); auditService.authenticationError(remoteAddress, message.authnCert); } throw new SecurityException("secure channel binding identity mismatch"); } LOG.debug("secure channel binding verified"); } } AuthenticationService authenticationService = this.authenticationServiceLocator.locateService(); List<X509Certificate> certificateChain = new LinkedList<X509Certificate>(); certificateChain.add(message.authnCert); certificateChain.add(message.citizenCaCert); certificateChain.add(message.rootCaCert); certificateChain.add(message.rrnCertificate); try { authenticationService.setHttpSessionObject(request.getSession()); authenticationService.validateCertificateChain(certificateChain); } catch (ExpiredCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED); } catch (RevokedCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED); } catch (TrustCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED); } catch (CertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE); } catch (Exception e) { /* * We don't want to depend on the full JavaEE profile in this * artifact. */ if ("javax.ejb.EJBException".equals(e.getClass().getName())) { Exception exception; try { Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException", new Class[] {}); exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {}); } catch (Exception e2) { LOG.debug("error: " + e.getMessage(), e); throw new SecurityException("error retrieving the root cause: " + e2.getMessage()); } if (exception instanceof ExpiredCertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED); } if (exception instanceof RevokedCertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED); } if (exception instanceof TrustCertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED); } if (exception instanceof CertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE); } } throw new SecurityException("authn service error: " + e.getMessage()); } String userId = UserIdentifierUtil.getUserId(message.authnCert); LOG.info("authenticated: " + userId + " @ " + request.getRemoteAddr()); if (null != this.nrcidSecret) { userId = UserIdentifierUtil.getNonReversibleCitizenIdentifier(userId, this.nrcidOrgId, this.nrcidAppId, this.nrcidSecret); } /* * Some people state that you cannot use the national register number * without hashing. Problem is that hashing introduces hash collision * problems. The probability is very low, but what if it's your leg * they're cutting of because of a patient mismatch based on the SHA1 of * your national register number? */ /* * Push authenticated used Id into the HTTP session. */ session.setAttribute(AUTHENTICATED_USER_IDENTIFIER_SESSION_ATTRIBUTE, userId); EIdData eidData = (EIdData) session.getAttribute(IdentityDataMessageHandler.EID_SESSION_ATTRIBUTE); if (null == eidData) { eidData = new EIdData(); session.setAttribute(IdentityDataMessageHandler.EID_SESSION_ATTRIBUTE, eidData); } eidData.identifier = userId; AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { auditService.authenticated(userId); } boolean includeIdentity = requestContext.includeIdentity(); boolean includeAddress = requestContext.includeAddress(); boolean includeCertificates = requestContext.includeCertificates(); boolean includePhoto = requestContext.includePhoto(); /* * Also process the identity data in case it was requested. */ if (includeIdentity) { if (null == message.identityData) { throw new ServletException("identity data not included while requested"); } } if (includeAddress) { if (null == message.addressData) { throw new ServletException("address data not included while requested"); } } if (includePhoto) { if (null == message.photoData) { throw new ServletException("photo data not included while requested"); } } IdentityIntegrityService identityIntegrityService = this.identityIntegrityServiceLocator.locateService(); if (null != identityIntegrityService) { if (null == message.rrnCertificate) { throw new ServletException("national registry certificate not included while requested"); } List<X509Certificate> rrnCertificateChain = new LinkedList<X509Certificate>(); rrnCertificateChain.add(message.rrnCertificate); rrnCertificateChain.add(message.rootCaCert); try { identityIntegrityService.checkNationalRegistrationCertificate(rrnCertificateChain); } catch (ExpiredCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED); } catch (RevokedCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED); } catch (TrustCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED); } catch (CertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE); } catch (Exception e) { if ("javax.ejb.EJBException".equals(e.getClass().getName())) { Exception exception; try { Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException", new Class[] {}); exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {}); } catch (Exception e2) { LOG.debug("error: " + e.getMessage(), e); throw new SecurityException("error retrieving the root cause: " + e2.getMessage()); } if (exception instanceof ExpiredCertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED); } if (exception instanceof RevokedCertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED); } if (exception instanceof TrustCertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED); } if (exception instanceof CertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE); } } throw new SecurityException("error checking the NRN certificate: " + e.getMessage(), e); } PublicKey rrnPublicKey = message.rrnCertificate.getPublicKey(); if (includeIdentity) { if (null == message.identitySignatureData) { throw new ServletException("identity signature data not included while requested"); } verifySignature(message.rrnCertificate.getSigAlgName(), message.identitySignatureData, rrnPublicKey, request, message.identityData); } if (includeAddress) { if (null == message.addressSignatureData) { throw new ServletException("address signature data not included while requested"); } byte[] addressFile = trimRight(message.addressData); verifySignature(message.rrnCertificate.getSigAlgName(), message.addressSignatureData, rrnPublicKey, request, addressFile, message.identitySignatureData); } } if (includeIdentity) { Identity identity = TlvParser.parse(message.identityData, Identity.class); if (false == UserIdentifierUtil.getUserId(message.authnCert).equals(identity.nationalNumber)) { throw new ServletException("national number mismatch"); } session.setAttribute(IdentityDataMessageHandler.IDENTITY_SESSION_ATTRIBUTE, identity); eidData.identity = identity; auditService = this.auditServiceLocator.locateService(); if (null != auditService) { auditService.identified(identity.nationalNumber); } } if (includeAddress) { Address address = TlvParser.parse(message.addressData, Address.class); session.setAttribute(IdentityDataMessageHandler.ADDRESS_SESSION_ATTRIBUTE, address); eidData.address = address; } if (includePhoto) { if (includeIdentity) { byte[] expectedPhotoDigest = eidData.identity.photoDigest; byte[] actualPhotoDigest = digestPhoto(getDigestAlgo(expectedPhotoDigest.length), message.photoData); if (false == Arrays.equals(expectedPhotoDigest, actualPhotoDigest)) { throw new ServletException("photo digest incorrect"); } } session.setAttribute(IdentityDataMessageHandler.PHOTO_SESSION_ATTRIBUTE, message.photoData); eidData.photo = message.photoData; } if (includeCertificates) { if (includeIdentity) { eidData.certs = new EIdCertsData(); eidData.certs.authn = message.authnCert; eidData.certs.ca = message.citizenCaCert; eidData.certs.root = message.rootCaCert; eidData.certs.sign = message.signCert; } session.setAttribute(IdentityDataMessageHandler.AUTHN_CERT_SESSION_ATTRIBUTE, message.authnCert); session.setAttribute(IdentityDataMessageHandler.CA_CERT_SESSION_ATTRIBUTE, message.citizenCaCert); session.setAttribute(IdentityDataMessageHandler.ROOT_CERT_SESSION_ATTRIBTUE, message.rootCaCert); session.setAttribute(IdentityDataMessageHandler.SIGN_CERT_SESSION_ATTRIBUTE, message.signCert); } if (this.includeDataFiles) { session.setAttribute(IdentityDataMessageHandler.EID_DATA_IDENTITY_SESSION_ATTRIBUTE, message.identityData); session.setAttribute(IdentityDataMessageHandler.EID_DATA_ADDRESS_SESSION_ATTRIBUTE, message.addressData); } AuthenticationSignatureService authenticationSignatureService = this.authenticationSignatureServiceLocator .locateService(); if (null != authenticationSignatureService) { List<X509Certificate> authnCertificateChain; if (null != message.authnCert) { authnCertificateChain = new LinkedList<X509Certificate>(); authnCertificateChain.add(message.authnCert); authnCertificateChain.add(message.citizenCaCert); authnCertificateChain.add(message.rootCaCert); authnCertificateChain.add(message.rrnCertificate); } else { authnCertificateChain = null; } AuthenticationSignatureContext authenticationSignatureContext = new AuthenticationSignatureContextImpl( session); PreSignResult preSignResult = authenticationSignatureService.preSign(authnCertificateChain, authenticationSignatureContext); if (null == preSignResult) { return new FinishedMessage(); } boolean logoff = preSignResult.getLogoff(); byte[] computedDigestValue = preSignResult.getDigestInfo().digestValue; String digestAlgo = preSignResult.getDigestInfo().digestAlgo; String authnMessage = preSignResult.getDigestInfo().description; AuthSignRequestMessage authSignRequestMessage = new AuthSignRequestMessage(computedDigestValue, digestAlgo, authnMessage, logoff); return authSignRequestMessage; } return new FinishedMessage(); }
From source file:org.texai.x509.X509Utils.java
/** Makes a canonical X.509 certificate by serializing it to bytes and reconsituting it. This ensures * that all issuer and subject names have no space following the commas. /*w w w .j a v a2 s . c o m*/ * @param x509Certificate the input certificate * @return the canonical certificate */ public static X509Certificate makeCanonicalX509Certificate(final X509Certificate x509Certificate) { //Preconditions assert x509Certificate != null : "x509Certificate must not be null"; X509Certificate canonicalX509Certificate; try { final byte[] certificateBytes = x509Certificate.getEncoded(); final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(certificateBytes); canonicalX509Certificate = readX509Certificate(byteArrayInputStream); } catch (CertificateException | NoSuchProviderException ex) { throw new TexaiException(ex); } LOGGER.debug("x509Certificate (" + x509Certificate.getClass().getName() + ")...\n" + x509Certificate + "\ncanonicalX509Certificate(" + canonicalX509Certificate.getClass().getName() + ")...\n" + canonicalX509Certificate); //Postconditions assert canonicalX509Certificate.equals( x509Certificate) : "canonicalX509Certificate must equal x509Certificate,\ncanonicalX509Certificate...\n" + canonicalX509Certificate + "\nx509Certificate...\n" + x509Certificate; return canonicalX509Certificate; }
From source file:at.alladin.rmbt.client.RMBTClient.java
public static SSLContext getSSLContext(final String caResource, final String certResource) throws NoSuchAlgorithmException, KeyManagementException { X509Certificate _ca = null;/*from w w w .ja v a2s. co m*/ try { if (caResource != null) { final CertificateFactory cf = CertificateFactory.getInstance("X.509"); _ca = (X509Certificate) cf .generateCertificate(RMBTClient.class.getClassLoader().getResourceAsStream(caResource)); } } catch (final Exception e) { e.printStackTrace(); } final X509Certificate ca = _ca; X509Certificate _cert = null; try { if (certResource != null) { final CertificateFactory cf = CertificateFactory.getInstance("X.509"); _cert = (X509Certificate) cf .generateCertificate(RMBTClient.class.getClassLoader().getResourceAsStream(certResource)); } } catch (final Exception e) { e.printStackTrace(); } final X509Certificate cert = _cert; // TrustManagerFactory tmf = null; // try // { // if (cert != null) // { // final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); // ks.load(null, null); // ks.setCertificateEntry("crt", cert); // // tmf = // TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // tmf.init(ks); // } // } // catch (Exception e) // { // e.printStackTrace(); // } final TrustManager tm; if (cert == null) tm = getTrustingManager(); else tm = new javax.net.ssl.X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { // System.out.println("getAcceptedIssuers"); if (ca == null) return new X509Certificate[] { cert }; else return new X509Certificate[] { ca }; } public void checkClientTrusted(final X509Certificate[] certs, final String authType) throws CertificateException { // System.out.println("checkClientTrusted: " + // Arrays.toString(certs) + " - " + authType); } public void checkServerTrusted(final X509Certificate[] certs, final String authType) throws CertificateException { // System.out.println("checkServerTrusted: " + // Arrays.toString(certs) + " - " + authType); if (certs == null) throw new CertificateException(); for (final X509Certificate c : certs) if (cert.equals(c)) return; throw new CertificateException(); } }; final TrustManager[] trustManagers = new TrustManager[] { tm }; javax.net.ssl.SSLContext sc; sc = javax.net.ssl.SSLContext.getInstance(Config.RMBT_ENCRYPTION_STRING); sc.init(null, trustManagers, new java.security.SecureRandom()); return sc; }
From source file:org.codice.ddf.security.filter.login.LoginFilter.java
private void validateHolderOfKeyConfirmation(SamlAssertionWrapper assertion, X509Certificate[] x509Certs) throws SecurityServiceException { List<String> confirmationMethods = assertion.getConfirmationMethods(); boolean hasHokMethod = false; for (String method : confirmationMethods) { if (OpenSAMLUtil.isMethodHolderOfKey(method)) { hasHokMethod = true;/*w ww. j av a 2 s . c om*/ } } if (hasHokMethod) { if (x509Certs != null && x509Certs.length > 0) { List<SubjectConfirmation> subjectConfirmations = assertion.getSaml2().getSubject() .getSubjectConfirmations(); for (SubjectConfirmation subjectConfirmation : subjectConfirmations) { if (OpenSAMLUtil.isMethodHolderOfKey(subjectConfirmation.getMethod())) { Element dom = subjectConfirmation.getSubjectConfirmationData().getDOM(); Node keyInfo = dom.getFirstChild(); Node x509Data = keyInfo.getFirstChild(); Node dataNode = x509Data.getFirstChild(); Node dataText = dataNode.getFirstChild(); X509Certificate tlsCertificate = x509Certs[0]; if (dataNode.getLocalName().equals("X509Certificate")) { String textContent = dataText.getTextContent(); byte[] byteValue = Base64.getMimeDecoder().decode(textContent); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(byteValue)); //check that the certificate is still valid cert.checkValidity(); //HoK spec section 2.5: //relying party MUST ensure that the certificate bound to the assertion matches the X.509 certificate in its possession. //Matching is done by comparing the base64-decoded certificates, or the hash values of the base64-decoded certificates, byte-for-byte. //if the certs aren't the same, verify if (!tlsCertificate.equals(cert)) { //verify that the cert was signed by the same private key as the TLS cert cert.verify(tlsCertificate.getPublicKey()); } } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | SignatureException | NoSuchProviderException e) { throw new SecurityServiceException( "Unable to validate Holder of Key assertion with certificate."); } } else if (dataNode.getLocalName().equals("X509SubjectName")) { String textContent = dataText.getTextContent(); //HoK spec section 2.5: //relying party MUST ensure that the subject distinguished name (DN) bound to the assertion matches the DN bound to the X.509 certificate. //If, however, the relying party does not trust the certificate issuer to issue such a DN, the attesting entity is not confirmed and the relying party SHOULD disregard the assertion. if (!tlsCertificate.getSubjectDN().getName().equals(textContent)) { throw new SecurityServiceException( "Unable to validate Holder of Key assertion with subject DN."); } } else if (dataNode.getLocalName().equals("X509IssuerSerial")) { //we have no way to support this confirmation type so we have to throw an error throw new SecurityServiceException( "Unable to validate Holder of Key assertion with issuer serial. NOT SUPPORTED"); } else if (dataNode.getLocalName().equals("X509SKI")) { String textContent = dataText.getTextContent(); byte[] tlsSKI = tlsCertificate.getExtensionValue("2.5.29.14"); byte[] assertionSKI = Base64.getMimeDecoder().decode(textContent); if (tlsSKI != null && tlsSKI.length > 0) { ASN1OctetString tlsOs = ASN1OctetString.getInstance(tlsSKI); ASN1OctetString assertionOs = ASN1OctetString.getInstance(assertionSKI); SubjectKeyIdentifier tlsSubjectKeyIdentifier = SubjectKeyIdentifier .getInstance(tlsOs.getOctets()); SubjectKeyIdentifier assertSubjectKeyIdentifier = SubjectKeyIdentifier .getInstance(assertionOs.getOctets()); //HoK spec section 2.5: //relying party MUST ensure that the value bound to the assertion matches the Subject Key Identifier (SKI) extension bound to the X.509 certificate. //Matching is done by comparing the base64-decoded SKI values byte-for-byte. If the X.509 certificate does not contain an SKI extension, //the attesting entity is not confirmed and the relying party SHOULD disregard the assertion. if (!Arrays.equals(tlsSubjectKeyIdentifier.getKeyIdentifier(), assertSubjectKeyIdentifier.getKeyIdentifier())) { throw new SecurityServiceException( "Unable to validate Holder of Key assertion with subject key identifier."); } } else { throw new SecurityServiceException( "Unable to validate Holder of Key assertion with subject key identifier."); } } } } } else { throw new SecurityServiceException("Holder of Key assertion, must be used with 2-way TLS."); } } }
From source file:org.wildfly.security.x500.cert.acme.AcmeClientSpiTest.java
@Test public void testChangeAccountKey() throws Exception { server = setupTestChangeAccountKey(); AcmeAccount account = populateAccount(ACCOUNT_6); X509Certificate oldCertificate = account.getCertificate(); X500Principal oldDn = account.getDn(); acmeClient.changeAccountKey(account, false); assertTrue(!oldCertificate.equals(account.getCertificate())); assertEquals(oldDn, account.getDn()); assertEquals(Acme.VALID, acmeClient.queryAccountStatus(account, false)); }
From source file:org.apache.rampart.PolicyBasedResultsValidator.java
/** * Evaluate whether a given certificate should be trusted. Hook to allow subclasses to implement * custom validation methods however they see fit. * <p/>/*from ww w.j a va 2s . c om*/ * Policy used in this implementation: 1. Search the keystore for the transmitted certificate 2. * Search the keystore for a connection to the transmitted certificate (that is, search for * certificate(s) of the issuer of the transmitted certificate 3. Verify the trust path for * those certificates found because the search for the issuer might be fooled by a phony DN * (String!) * * @param cert the certificate that should be validated against the keystore * @return true if the certificate is trusted, false if not (AxisFault is thrown for exceptions * during CertPathValidation) * @throws WSSecurityException */ protected boolean verifyTrust(X509Certificate cert, RampartMessageData rmd) throws RampartException { // If no certificate was transmitted, do not trust the signature if (cert == null) { return false; } String[] aliases = null; String alias = null; X509Certificate[] certs; String subjectString = cert.getSubjectDN().getName(); String issuerString = cert.getIssuerDN().getName(); BigInteger issuerSerial = cert.getSerialNumber(); boolean doDebug = log.isDebugEnabled(); if (doDebug) { log.debug("WSHandler: Transmitted certificate has subject " + subjectString); log.debug("WSHandler: Transmitted certificate has issuer " + issuerString + " (serial " + issuerSerial + ")"); } // FIRST step // Search the keystore for the transmitted certificate // Search the keystore for the alias of the transmitted certificate try { alias = RampartUtil .getSignatureCrypto(rmd.getPolicyData().getRampartConfig(), rmd.getCustomClassLoader()) .getAliasForX509Cert(issuerString, issuerSerial); } catch (WSSecurityException ex) { throw new RampartException("cannotFindAliasForCert", new String[] { subjectString }, ex); } if (alias != null) { // Retrieve the certificate for the alias from the keystore try { certs = RampartUtil .getSignatureCrypto(rmd.getPolicyData().getRampartConfig(), rmd.getCustomClassLoader()) .getCertificates(alias); } catch (WSSecurityException ex) { throw new RampartException("noCertForAlias", new String[] { alias }, ex); } // If certificates have been found, the certificates must be compared // to ensure against phony DNs (compare encoded form including signature) if (certs != null && certs.length > 0 && cert.equals(certs[0])) { if (doDebug) { log.debug("Direct trust for certificate with " + subjectString); } // Set the alias of the cert used for the msg. sig. as a msg. cxt. property rmd.getMsgContext().setProperty(RampartMessageData.SIGNATURE_CERT_ALIAS, alias); return true; } } else { if (doDebug) { log.debug("No alias found for subject from issuer with " + issuerString + " (serial " + issuerSerial + ")"); } } // SECOND step // Search for the issuer of the transmitted certificate in the keystore // Search the keystore for the alias of the transmitted certificates issuer try { aliases = RampartUtil .getSignatureCrypto(rmd.getPolicyData().getRampartConfig(), rmd.getCustomClassLoader()) .getAliasesForDN(issuerString); } catch (WSSecurityException ex) { throw new RampartException("cannotFindAliasForCert", new String[] { issuerString }, ex); } // If the alias has not been found, the issuer is not in the keystore // As a direct result, do not trust the transmitted certificate if (aliases == null || aliases.length < 1) { if (doDebug) { log.debug("No aliases found in keystore for issuer " + issuerString + " of certificate for " + subjectString); } return false; } // THIRD step // Check the certificate trust path for every alias of the issuer found in the keystore for (int i = 0; i < aliases.length; i++) { alias = aliases[i]; if (doDebug) { log.debug("Preparing to validate certificate path with alias " + alias + " for issuer " + issuerString); } // Retrieve the certificate(s) for the alias from the keystore try { certs = RampartUtil .getSignatureCrypto(rmd.getPolicyData().getRampartConfig(), rmd.getCustomClassLoader()) .getCertificates(alias); } catch (WSSecurityException ex) { throw new RampartException("noCertForAlias", new String[] { alias }, ex); } // If no certificates have been found, there has to be an error: // The keystore can find an alias but no certificate(s) if (certs == null || certs.length < 1) { throw new RampartException("noCertForAlias", new String[] { alias }); } // Form a certificate chain from the transmitted certificate // and the certificate(s) of the issuer from the keystore // First, create new array X509Certificate[] x509certs = new X509Certificate[certs.length + 1]; // Then add the first certificate ... x509certs[0] = cert; // ... and the other certificates for (int j = 0; j < certs.length; j++) { cert = certs[j]; x509certs[j + 1] = cert; } certs = x509certs; // Use the validation method from the crypto to check whether the subjects certificate // was really signed by the issuer stated in the certificate try { if (RampartUtil .getSignatureCrypto(rmd.getPolicyData().getRampartConfig(), rmd.getCustomClassLoader()) .validateCertPath(certs)) { if (doDebug) { log.debug("WSHandler: Certificate path has been verified for certificate with subject " + subjectString); } return true; } } catch (WSSecurityException ex) { throw new RampartException("certPathVerificationFailed", new String[] { subjectString }, ex); } } if (doDebug) { log.debug("WSHandler: Certificate path could not be verified for certificate with subject " + subjectString); } return false; }