List of usage examples for java.security.cert X509Certificate getPublicKey
public abstract PublicKey getPublicKey();
From source file:org.cesecore.certificates.ocsp.CanLogCache.java
private BasicOCSPResp generateBasicOcspResp(OCSPReq ocspRequest, X509Extensions exts, List<OCSPResponseItem> responses, String sigAlg, X509Certificate signerCert, PrivateKey signerKey, String provider, X509Certificate[] chain, int respIdType) throws NotSupportedException, OCSPException, NoSuchProviderException, CryptoTokenOfflineException { BasicOCSPResp returnval = null;//from w w w. j a v a 2 s . c o m BasicOCSPRespGenerator basicRes = null; basicRes = createOcspResponseGenerator(ocspRequest, signerCert, respIdType); if (responses != null) { for (OCSPResponseItem item : responses) { basicRes.addResponse(item.getCertID(), item.getCertStatus(), item.getThisUpdate(), item.getNextUpdate(), null); } } if (exts != null) { @SuppressWarnings("rawtypes") Enumeration oids = exts.oids(); if (oids.hasMoreElements()) { basicRes.setResponseExtensions(exts); } } /* * The below code breaks the EJB standard by creating its own thread pool and creating a single thread (of the HsmResponseThread * type). The reason for this is that the HSM may deadlock when requesting an OCSP response, which we need to guard against. Since * there is no way of performing this action within the EJB3.0 standard, we are consciously creating threads here. * * Note that this does in no way break the spirit of the EJB standard, which is to not interrupt EJB's transaction handling by * competing with its own thread pool, since these operations have no database impact. */ final ExecutorService service = Executors.newFixedThreadPool(1); final Future<BasicOCSPResp> task = service .submit(new HsmResponseThread(basicRes, sigAlg, signerKey, chain, provider)); try { returnval = task.get(HsmResponseThread.HSM_TIMEOUT_SECONDS, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new Error("OCSP response retrieval was interrupted while running. This should not happen", e); } catch (ExecutionException e) { throw new OcspFailureException("Failure encountered while retrieving OCSP response.", e); } catch (TimeoutException e) { throw new CryptoTokenOfflineException("HSM timed out while trying to get OCSP response", e); } if (log.isDebugEnabled()) { log.debug("Signing OCSP response with OCSP signer cert: " + signerCert.getSubjectDN().getName()); RespID respId = null; if (respIdType == OcspConfiguration.RESPONDERIDTYPE_NAME) { respId = new RespID(signerCert.getSubjectX500Principal()); } else { respId = new RespID(signerCert.getPublicKey()); } if (!returnval.getResponderId().equals(respId)) { log.error("Response responderId does not match signer certificate responderId!"); } boolean verify = returnval.verify(signerCert.getPublicKey(), "BC"); if (verify) { log.debug("The OCSP response is verifying."); } else { log.error("The response is NOT verifying!"); } } return returnval; }
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 w w. ja va 2 s . co m*/ } } 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.codice.ddf.security.idp.client.SimpleSign.java
private java.security.Signature getSignature(X509Certificate certificate, PrivateKey privateKey) throws SignatureException { String jceSigAlgo = "SHA1withRSA"; if ("DSA".equalsIgnoreCase(certificate.getPublicKey().getAlgorithm())) { jceSigAlgo = "SHA1withDSA"; }//from w w w . j a v a 2 s .c o m java.security.Signature signature; try { signature = java.security.Signature.getInstance(jceSigAlgo); } catch (NoSuchAlgorithmException e) { throw new SignatureException(e); } try { signature.initSign(privateKey); } catch (InvalidKeyException e) { throw new SignatureException(e); } return signature; }
From source file:org.codice.ddf.security.idp.client.SimpleSign.java
private String getSignatureAlgorithm(X509Certificate certificate) { String sigAlgo = SSOConstants.RSA_SHA1; String pubKeyAlgo = certificate.getPublicKey().getAlgorithm(); if (pubKeyAlgo.equalsIgnoreCase("DSA")) { sigAlgo = SSOConstants.DSA_SHA1; }//from w ww .ja va 2 s . co m LOGGER.debug("Using Signature algorithm {}", sigAlgo); return sigAlgo; }
From source file:org.digidoc4j.impl.bdoc.BDocSignatureBuilder.java
private boolean isEcdsaCertificate() { X509Certificate certificate = signatureParameters.getSigningCertificate(); String algorithm = certificate.getPublicKey().getAlgorithm(); return algorithm.equals("EC") || algorithm.equals("ECC"); }
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 w w .ja va2 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 /*/* w w w .j a v a2 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.core.protocol.cmp.CrmfKeyUpdateTest.java
/** * A "Happy Path" test. Sends a KeyUpdateRequest and receives a new certificate. * //from ww w . ja v a2 s . co m * - Pre-configuration: Sets the operational mode to client mode (cmp.raoperationalmode=normal) * - Pre-configuration: Sets cmp.allowautomaticrenewal to 'true' and tests that the resetting of configuration has worked. * - Pre-configuration: Sets cmp.allowupdatewithsamekey to 'true' * - Creates a new user and obtains a certificate, cert, for this user. Tests whether obtaining the certificate was successful. * - Generates a CMP KeyUpdate Request and tests that such request has been created. * - Signs the CMP request using cert and attaches cert to the CMP request. Tests that the CMP request is still not null * - Sends the request using HTTP and receives a response. * - Examines the response: * - Checks that the response is not empty or null * - Checks that the protection algorithm is sha1WithRSAEncryption * - Checks that the signer is the expected CA * - Verifies the response signature * - Checks that the response's senderNonce is 16 bytes long * - Checks that the request's senderNonce is the same as the response's recipientNonce * - Checks that the request and the response has the same transactionID * - Obtains the certificate from the response * - Checks that the obtained certificate has the right subjectDN and issuerDN * * @throws Exception */ @Test public void test01KeyUpdateRequestOK() throws Exception { if (log.isTraceEnabled()) { log.trace(">test01KeyUpdateRequestOK"); } this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true); this.cmpConfiguration.setKurAllowSameKey(this.cmpAlias, true); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); //--------------- create the user and issue his first certificate ----------------- createUser(this.username, this.userDN.toString(), "foo123"); KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); final Certificate certificate; try { certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123", new PublicKeyWrapper(keys.getPublic())); } catch (ObjectNotFoundException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (CADoesntExistsException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (EjbcaException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (AuthorizationDeniedException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (CesecoreException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } assertNotNull("Failed to create a test certificate", certificate); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, null, null, pAlg, new DEROctetString(this.nonce)); assertNotNull("Failed to generate a CMP renewal request", req); CertReqMessages kur = (CertReqMessages) req.getBody().getContent(); int reqId = kur.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); CMPCertificate[] extraCert = getCMPCert(certificate); req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, keys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(req); ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); byte[] ba = bao.toByteArray(); // Send request and receive response byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias); checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); X509Certificate cert = checkKurCertRepMessage(this.userDN, this.cacert, resp, reqId); assertNotNull("Failed to renew the certificate", cert); assertTrue("The new certificate's keys are incorrect.", cert.getPublicKey().equals(keys.getPublic())); if (log.isTraceEnabled()) { log.trace("<test01KeyUpdateRequestOK"); } }
From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateTest.java
/** * Sends a KeyUpdateRequest with a different key and the configurations is NOT to allow the use of the same keys. * Successful operation is expected and a new certificate is received. * //from w w w . j av a2 s.c o m * - Pre-configuration: Sets the operational mode to client mode (cmp.raoperationalmode=normal) * - Pre-configuration: Sets cmp.allowautomaticrenewal to 'true' and tests that the resetting of configuration has worked. * - Pre-configuration: Sets cmp.allowupdatewithsamekey to 'false' * - Creates a new user and obtains a certificate, cert, for this user. Tests whether obtaining the certificate was successful. * - Generates a CMP KeyUpdate Request and tests that such request has been created. * - Signs the CMP request using cert and attaches cert to the CMP request. Tests that the CMP request is still not null * - Sends the request using HTTP and receives a response. * - Examines the response: * - Checks that the response is not empty or null * - Checks that the protection algorithm is sha1WithRSAEncryption * - Check that the signer is the expected CA * - Verifies the response signature * - Checks that the response's senderNonce is 16 bytes long * - Checks that the request's senderNonce is the same as the response's recipientNonce * - Checks that the request and the response has the same transactionID * - Obtains the certificate from the response * - Checks that the obtained certificate has the right subjectDN and issuerDN * * @throws Exception */ @Test public void test06UpdateWithDifferentKey() throws Exception { if (log.isTraceEnabled()) { log.trace(">test08UpdateWithDifferentKey"); } this.cmpConfiguration.setRAMode(this.cmpAlias, false); this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true); this.cmpConfiguration.setKurAllowSameKey(this.cmpAlias, false); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); //--------------- create the user and issue his first certificate ----------------- createUser(this.username, this.userDN.toString(), "foo123"); KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); final Certificate certificate; certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123", new PublicKeyWrapper(keys.getPublic())); assertNotNull("Failed to create a test certificate", certificate); KeyPair newkeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, newkeys, false, null, null, pAlg, new DEROctetString(this.nonce)); assertNotNull("Failed to generate a CMP renewal request", req); CertReqMessages kur = (CertReqMessages) req.getBody().getContent(); int reqId = kur.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); CMPCertificate[] extraCert = getCMPCert(certificate); req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, keys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(req); //******************************************'''''' final Signature sig = Signature.getInstance(req.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(certificate.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(req)); boolean verified = sig.verify(req.getProtection().getBytes()); assertTrue("Signing the message failed.", verified); //*************************************************** ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); byte[] ba = bao.toByteArray(); // Send request and receive response byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias); checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); X509Certificate cert = checkKurCertRepMessage(this.userDN, this.cacert, resp, reqId); assertNotNull("Failed to renew the certificate", cert); assertTrue("The new certificate's keys are incorrect.", cert.getPublicKey().equals(newkeys.getPublic())); assertFalse("The new certificate's keys are the same as the old certificate's keys.", cert.getPublicKey().equals(keys.getPublic())); if (log.isTraceEnabled()) { log.trace("<test08UpdateWithDifferentKey"); } }
From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateTest.java
/** * Tests the possibility to use different signature algorithms in CMP requests and responses. * // w w w . j a v a 2 s . com * A KeyUpdate request, signed using ECDSA with SHA256, is sent to a CA that uses RSA with SHA256 as signature algorithm. * The expected response is signed by RSA with SHA256. * * @throws Exception */ @Test public void test15KeyUpdateMixAlgorithms() throws Exception { if (log.isTraceEnabled()) { log.trace(">test15KeyUpdateMixAlgorithms"); } this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true); this.cmpConfiguration.setKurAllowSameKey(this.cmpAlias, true); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); //--------------- create the user and issue his first certificate ----------------- createUser(this.username, this.userDN.toString(), "foo123"); KeyPair keys = KeyTools.genKeys("prime192v1", AlgorithmConstants.KEYALGORITHM_ECDSA); final Certificate certificate; try { certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123", new PublicKeyWrapper(keys.getPublic())); } catch (ObjectNotFoundException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (CADoesntExistsException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (EjbcaException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (AuthorizationDeniedException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (CesecoreException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } assertNotNull("Failed to create a test certificate", certificate); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(X9ObjectIdentifiers.ecdsa_with_SHA256); PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, null, null, pAlg, new DEROctetString(this.nonce)); assertNotNull("Failed to generate a CMP renewal request", req); CertReqMessages kur = (CertReqMessages) req.getBody().getContent(); int reqId = kur.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); CMPCertificate[] extraCert = getCMPCert(certificate); req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, keys.getPrivate(), CMSSignedGenerator.DIGEST_SHA256, "BC"); assertNotNull(req); ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); byte[] ba = bao.toByteArray(); // Send request and receive response byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias); checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, true, null, PKCSObjectIdentifiers.sha256WithRSAEncryption.getId()); X509Certificate cert = checkKurCertRepMessage(this.userDN, this.cacert, resp, reqId); assertNotNull("Failed to renew the certificate", cert); assertTrue("The new certificate's keys are incorrect.", cert.getPublicKey().equals(keys.getPublic())); if (log.isTraceEnabled()) { log.trace("<test15KeyUpdateMixAlgorithms"); } }