List of usage examples for java.security PublicKey equals
public boolean equals(Object obj)
From source file:org.ejbca.core.ejb.ocsp.OcspKeyRenewalSessionBean.java
/** * This method sends a keypair off to be signed by the CA that issued the original keychain. * /*from w ww.ja v a2 s . c o m*/ * @return a certificate that has been signed by the CA. * @throws KeyRenewalFailedException if any error occurs during signing * @throws CryptoTokenOfflineException */ @SuppressWarnings("unchecked") private X509Certificate signCertificateByCa(EjbcaWS ejbcaWS, OcspSigningCacheEntry ocspSigningCacheEntry) throws KeyRenewalFailedException, CryptoTokenOfflineException { /* Construct a certification request in order to have the new keystore certified by the CA. */ //final int caId = CertTools.stringToBCDNString(tokenAndChain.getCaCertificate().getSubjectDN().toString()).hashCode(); final int caId = CertTools.getSubjectDN(ocspSigningCacheEntry.getCaCertificateChain().get(0)).hashCode(); final X509Certificate ocspSigningCertificate = ocspSigningCacheEntry.getOcspSigningCertificate(); final UserDataVOWS userData = getUserDataVOWS(ejbcaWS, ocspSigningCertificate, caId); if (userData == null) { final String msg = "User data for certificate with subject DN '" + CertTools.getSubjectDN(ocspSigningCertificate) + "' was not found."; log.error(msg); throw new KeyRenewalFailedException(msg); } editUser(ejbcaWS, userData); final int internalKeyBindingId = ocspSigningCacheEntry.getOcspKeyBinding().getId(); final byte[] pkcs10CertificationRequest; try { pkcs10CertificationRequest = internalKeyBindingMgmtSession.generateCsrForNextKey(authenticationToken, internalKeyBindingId); } catch (AuthorizationDeniedException e) { throw new KeyRenewalFailedException(e); } CertificateResponse certificateResponse; try { certificateResponse = ejbcaWS.pkcs10Request(userData.getUsername(), userData.getPassword(), new String(Base64.encode(pkcs10CertificationRequest)), null, CertificateHelper.RESPONSETYPE_CERTIFICATE); } catch (Exception e) { //Way too many silly exceptions to handle, wrap instead. throw new KeyRenewalFailedException(e); } if (certificateResponse == null) { throw new KeyRenewalFailedException("Certificate Response was not received"); } Collection<X509Certificate> certificates; try { certificates = (Collection<X509Certificate>) CertificateFactory.getInstance("X.509") .generateCertificates(new ByteArrayInputStream(Base64.decode(certificateResponse.getData()))); } catch (CertificateException e) { throw new KeyRenewalFailedException(e); } final byte[] publicKeyBytes; try { publicKeyBytes = internalKeyBindingMgmtSession .getNextPublicKeyForInternalKeyBinding(authenticationToken, internalKeyBindingId); } catch (AuthorizationDeniedException e) { throw new KeyRenewalFailedException(e); } if (log.isDebugEnabled()) { log.debug("Number of certificates returned from WS: " + certificates.size()); } X509Certificate signedCertificate = null; final X509Certificate caCertificate = ocspSigningCacheEntry.getCaCertificateChain().get(0); final PublicKey caCertificatePublicKey = caCertificate.getPublicKey(); for (X509Certificate certificate : certificates) { if (log.isDebugEnabled()) { log.debug("Verifying certificate with SubjectDN : '" + CertTools.getSubjectDN(certificate) + "' using public key from CA certificate with subject '" + CertTools.getSubjectDN(caCertificate) + "'."); } try { certificate.verify(caCertificatePublicKey); } catch (Exception e) { //Ugly, but inherited from legacy code signedCertificate = null; log.error("Exception was caught when verifying certificate", e); continue; } // Comparing public keys is dependent on provider used, so we must ensure same provider is used for the public keys // Otherwise this will fail, even though it should work // Both certPublicKey and nextPublicKey is obtained using KeyTools.getPublicKeyFromBytes, which uses the BC provider final PublicKey certPublicKey = KeyTools.getPublicKeyFromBytes(certificate.getPublicKey().getEncoded()); final PublicKey nextPublicKey = KeyTools.getPublicKeyFromBytes(publicKeyBytes); if (nextPublicKey.equals(certPublicKey)) { signedCertificate = certificate; break; } else if (log.isDebugEnabled()) { log.debug("Matching public keys failed: "); log.debug("Certificate public key: " + certificate.getPublicKey()); log.debug("Next public key: " + nextPublicKey); } } if (signedCertificate == null) { throw new KeyRenewalFailedException("No certificate signed by correct CA generated."); } return signedCertificate; }
From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateHandler.java
@Override /*/*from w ww .ja va 2 s . co m*/ * Handles the CMP message * * Expects the CMP message to be a CrmfRequestMessage. The message is authenticated using * EndEntityCertificateAuthenticationModule in client mode. It used the attached certificate * to find then End Entity which this certificate belongs to and requesting for a new certificate * to be generated. * * If automatic update of the key (same as certificate renewal), the end entity's status is set to * 'NEW' before processing the request. If using the same old keys in the new certificate is not allowed, * a check is made to insure the the key specified in the request is not the same as the key of the attached * certificate. * * The KeyUpdateRequet is processed only in client mode. */ public ResponseMessage handleMessage(final BaseCmpMessage msg, boolean authenticated) { if (LOG.isTraceEnabled()) { LOG.trace(">handleMessage"); } if (LOG.isDebugEnabled()) { LOG.debug("CMP running on RA mode: " + this.cmpConfiguration.getRAMode(this.confAlias)); } ResponseMessage resp = null; try { CrmfRequestMessage crmfreq = null; if (msg instanceof CrmfRequestMessage) { crmfreq = (CrmfRequestMessage) msg; crmfreq.getMessage(); EndEntityCertificateAuthenticationModule eecmodule = null; X509Certificate oldCert = null; // Find the subjectDN to look for String subjectDN = null; String issuerDN = null; if (this.cmpConfiguration.getRAMode(this.confAlias)) { // Check that EndEntityCertificate authentication module is set if (!cmpConfiguration.isInAuthModule(confAlias, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE)) { String errmsg = "EndEnityCertificate authentication module is not configured. For a KeyUpdate request to be authentication in RA mode, EndEntityCertificate " + "authentication module has to be set and configured"; LOG.info(errmsg); return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST, errmsg); } // Check PKIMessage authentication String authparameter = cmpConfiguration.getAuthenticationParameter( CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE, confAlias); eecmodule = new EndEntityCertificateAuthenticationModule(admin, authparameter, confAlias, cmpConfiguration, authenticated, caSession, certStoreSession, authorizationSession, endEntityProfileSession, endEntityAccessSession, authenticationProviderSession, endEntityManagementSession); if (!eecmodule.verifyOrExtract(crmfreq.getPKIMessage(), null)) { LOG.info(eecmodule.getErrorMessage()); return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST, eecmodule.getErrorMessage()); } else { if (LOG.isDebugEnabled()) { LOG.debug("The CMP KeyUpdate request for SubjectDN '" + crmfreq.getSubjectDN() + "' was verified successfully"); } } oldCert = (X509Certificate) eecmodule.getExtraCert(); CertReqMessages kur = (CertReqMessages) crmfreq.getPKIMessage().getBody().getContent(); CertReqMsg certmsg; try { certmsg = kur.toCertReqMsgArray()[0]; } catch (Exception e) { LOG.debug( "Could not parse the revocation request. Trying to parse it as novosec generated message."); certmsg = CmpMessageHelper.getNovosecCertReqMsg(kur); LOG.debug("Succeeded in parsing the novosec generated request."); } X500Name dn = certmsg.getCertReq().getCertTemplate().getSubject(); if (dn != null) { subjectDN = dn.toString(); } dn = certmsg.getCertReq().getCertTemplate().getIssuer(); if (dn != null) { issuerDN = dn.toString(); } } else { // client mode eecmodule = new EndEntityCertificateAuthenticationModule(admin, null, confAlias, cmpConfiguration, authenticated, caSession, certStoreSession, authorizationSession, endEntityProfileSession, endEntityAccessSession, authenticationProviderSession, endEntityManagementSession); if (!eecmodule.verifyOrExtract(crmfreq.getPKIMessage(), null)) { LOG.info(eecmodule.getErrorMessage()); return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST, eecmodule.getErrorMessage()); } oldCert = (X509Certificate) eecmodule.getExtraCert(); subjectDN = oldCert.getSubjectDN().toString(); issuerDN = oldCert.getIssuerDN().toString(); } if (subjectDN == null) { final String errMsg = "Cannot find a SubjectDN in the request"; LOG.info(errMsg); return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST, errMsg); } // Find the end entity that the certificate belongs to if (LOG.isDebugEnabled()) { LOG.debug("Looking for an end entity with subjectDN: " + subjectDN); } EndEntityInformation userdata = null; if (issuerDN == null) { if (LOG.isDebugEnabled()) { LOG.debug("The CMP KeyUpdateRequest did not specify an issuer"); } List<EndEntityInformation> userdataList = endEntityAccessSession.findUserBySubjectDN(admin, subjectDN); if (userdataList.size() > 0) { userdata = userdataList.get(0); } if (userdataList.size() > 1) { LOG.warn("Multiple end entities with subject DN " + subjectDN + " were found. This may lead to unexpected behavior."); } } else { List<EndEntityInformation> userdataList = endEntityAccessSession .findUserBySubjectAndIssuerDN(admin, subjectDN, issuerDN); if (userdataList.size() > 0) { userdata = userdataList.get(0); } if (userdataList.size() > 1) { LOG.warn("Multiple end entities with subject DN " + subjectDN + " and issuer DN" + issuerDN + " were found. This may lead to unexpected behavior."); } } if (userdata == null) { final String errMsg = INTRES.getLocalizedMessage("cmp.infonouserfordn", subjectDN); LOG.info(errMsg); return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_MESSAGE_CHECK, errMsg); } if (LOG.isDebugEnabled()) { LOG.debug("Found user '" + userdata.getUsername() + "'"); } // The password that should be used to obtain the new certificate String password = StringUtils.isNotEmpty(userdata.getPassword()) ? userdata.getPassword() : eecmodule.getAuthenticationString(); // Set the appropriate parameters in the end entity userdata.setPassword(password); endEntityManagementSession.changeUser(admin, userdata, true); if (this.cmpConfiguration.getKurAllowAutomaticUpdate(this.confAlias)) { if (LOG.isDebugEnabled()) { LOG.debug("Setting the end entity status to 'NEW'. Username: " + userdata.getUsername()); } endEntityManagementSession.setUserStatus(admin, userdata.getUsername(), EndEntityConstants.STATUS_NEW); } // Set the appropriate parameters in the request crmfreq.setUsername(userdata.getUsername()); crmfreq.setPassword(password); if (crmfreq.getHeader().getProtectionAlg() != null) { crmfreq.setPreferredDigestAlg(AlgorithmTools .getDigestFromSigAlg(crmfreq.getHeader().getProtectionAlg().getAlgorithm().getId())); } // Check the public key, whether it is allowed to use the old keys or not. if (!this.cmpConfiguration.getKurAllowSameKey(this.confAlias)) { PublicKey certPublicKey = oldCert.getPublicKey(); PublicKey requestPublicKey = crmfreq.getRequestPublicKey(); if (LOG.isDebugEnabled()) { LOG.debug("Not allowing update with same key, comparing keys."); if (LOG.isTraceEnabled()) { LOG.trace("OldKey: " + certPublicKey.toString()); LOG.trace("NewKey: " + requestPublicKey.toString()); } } if (certPublicKey.equals(requestPublicKey)) { final String errMsg = "Invalid key. The public key in the KeyUpdateRequest is the same as the public key in the existing end entity certificate"; LOG.info(errMsg); return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_MESSAGE_CHECK, errMsg); } } // Process the request resp = signSession.createCertificate(admin, crmfreq, org.ejbca.core.protocol.cmp.CmpResponseMessage.class, userdata); if (resp == null) { final String errMsg = INTRES.getLocalizedMessage("cmp.errornullresp"); LOG.info(errMsg); resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_MESSAGE_CHECK, errMsg); } } else { final String errMsg = INTRES.getLocalizedMessage("cmp.errornocmrfreq"); LOG.info(errMsg); resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_MESSAGE_CHECK, errMsg); } } catch (AuthorizationDeniedException e) { final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage()); LOG.info(errMsg, e); resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST, e.getMessage()); } catch (CADoesntExistsException e) { final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage()); LOG.info(errMsg, e); resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST, e.getMessage()); } catch (UserDoesntFullfillEndEntityProfile e) { final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage()); LOG.info(errMsg, e); resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST, e.getMessage()); } catch (WaitingForApprovalException e) { final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage()); LOG.info(errMsg, e); resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST, e.getMessage()); } catch (EjbcaException e) { final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage()); LOG.info(errMsg, e); resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST, e.getMessage()); } catch (FinderException e) { final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage()); LOG.info(errMsg, e); resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST, e.getMessage()); } catch (CesecoreException e) { final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage()); LOG.info(errMsg, e); resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST, e.getMessage()); } catch (InvalidKeyException e) { final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage()); LOG.info("Error while reading the public key of the extraCert attached to the CMP request"); LOG.info(errMsg, e); resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST, e.getMessage()); } catch (NoSuchAlgorithmException e) { final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage()); LOG.info("Error while reading the public key of the extraCert attached to the CMP request"); LOG.info(errMsg, e); resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST, e.getMessage()); } catch (NoSuchProviderException e) { final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage()); LOG.info("Error while reading the public key of the extraCert attached to the CMP request"); LOG.info(errMsg, e); resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST, e.getMessage()); } catch (CertificateExtensionException e) { final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage()); LOG.info(errMsg, e); resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST, e.getMessage()); } if (LOG.isTraceEnabled()) { LOG.trace("<handleMessage"); } return resp; }
From source file:org.ejbca.util.keystore.KeyStoreContainerBase.java
@Override public void installCertificate(final String fileName) throws Exception { log.info("Installing " + fileName + ": "); final X509Certificate chain[] = ((Collection<?>) CertTools.getCertsFromPEM(new FileInputStream(fileName))) .toArray(new X509Certificate[0]); final Enumeration<String> eAlias = this.keyStore.aliases(); boolean notFound = true; while (eAlias.hasMoreElements() && notFound) { final String alias = eAlias.nextElement(); final PublicKey hsmPublicKey = getCertificate(alias).getPublicKey(); final PublicKey importPublicKey = chain[0].getPublicKey(); if (log.isDebugEnabled()) { log.debug("alias: " + alias + " SHA1 of public hsm key: " + CertTools.getFingerprintAsString(hsmPublicKey.getEncoded()) + " SHA1 of first public key in chain: " + CertTools.getFingerprintAsString(importPublicKey.getEncoded()) + (chain.length == 1 ? "" : ("SHA1 of last public key in chain: " + CertTools.getFingerprintAsString( chain[chain.length - 1].getPublicKey().getEncoded())))); }/* w w w. ja v a 2 s .co m*/ if (hsmPublicKey.equals(importPublicKey)) { log.info("Found a matching public key for alias \"" + alias + "\"."); this.keyStore.setKeyEntry(alias, getPrivateKey(alias), null, chain); notFound = false; } } if (notFound) { final String msg = intres.getLocalizedMessage("token.errorkeynottoken"); throw new Exception(msg); } }