List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java
private AuthenticationToken createTokenWithCert(String adminName, AuthenticationSubject subject, KeyPair keys) { // A small check if we have added a "fail" credential to the subject. // If we have we will return null, so we can test authentication failure. Set<?> usercredentials = subject.getCredentials(); if ((usercredentials != null) && (usercredentials.size() > 0)) { Object o = usercredentials.iterator().next(); if (o instanceof String) { String str = (String) o; if (StringUtils.equals("fail", str)) { return null; }/*from www . jav a 2s . c o m*/ } } X509Certificate certificate = null; // If we have a certificate as input, use that, otherwise generate a self signed certificate Set<X509Certificate> credentials = new HashSet<X509Certificate>(); // If there was no certificate input, create a self signed String dn = "C=SE,O=Test,CN=Test"; // default // If we have created a subject with an X500Principal we will use this DN to create the dummy certificate. { final Set<Principal> principals = subject.getPrincipals(); if ((principals != null) && (principals.size() > 0)) { final Principal p = principals.iterator().next(); if (p instanceof X500Principal) { X500Principal xp = (X500Principal) p; dn = xp.getName(); } } } try { createUser(adminName, dn, "foo123", this.caid); } catch (AuthorizationDeniedException e1) { throw new CertificateCreationException("Error encountered when creating this.admin user", e1); } catch (UserDoesntFullfillEndEntityProfile e1) { throw new CertificateCreationException("Error encountered when creating this.admin user", e1); } catch (WaitingForApprovalException e1) { throw new CertificateCreationException("Error encountered when creating this.admin user", e1); } catch (EjbcaException e1) { throw new CertificateCreationException("Error encountered when creating this.admin user", e1); } catch (Exception e1) { throw new CertificateCreationException("Error encountered when creating this.admin user", e1); } try { certificate = (X509Certificate) this.signSession.createCertificate(this.admin, adminName, "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); } catch (javax.ejb.ObjectNotFoundException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } // Add the credentials and new principal credentials.add(certificate); Set<X500Principal> principals = new HashSet<X500Principal>(); principals.add(certificate.getSubjectX500Principal()); // We cannot use the X509CertificateAuthenticationToken here, since it can only be used internally in a JVM. AuthenticationToken result = new TestX509CertificateAuthenticationToken(principals, credentials); return result; }
From source file:com.netscape.ca.CertificateAuthority.java
/** * Create a new lightweight authority signed by this authority. * * This method DOES NOT add the new CA to caMap; it is the * caller's responsibility./*from w w w .j ava2 s .c om*/ */ public ICertificateAuthority createSubCA(IAuthToken authToken, String subjectDN, String description) throws EBaseException { ensureReady(); // check requested DN X500Name subjectX500Name = null; try { subjectX500Name = new X500Name(subjectDN); } catch (IOException e) { throw new IllegalArgumentException("Invalid Subject DN: " + subjectDN); } ensureAuthorityDNAvailable(subjectX500Name); // generate authority ID and nickname AuthorityID aid = new AuthorityID(); String aidString = aid.toString(); String nickname = hostCA.getNickname() + " " + aidString; // build database entry String dn = "cn=" + aidString + "," + authorityBaseDN(); logger.debug("createSubCA: DN = " + dn); String parentDNString = null; try { parentDNString = mName.toLdapDNString(); } catch (IOException e) { throw new EBaseException("Failed to convert issuer DN to string: " + e); } String thisClone = CMS.getEEHost() + ":" + CMS.getEESSLPort(); LDAPAttribute[] attrs = { new LDAPAttribute("objectclass", "authority"), new LDAPAttribute("cn", aidString), new LDAPAttribute("authorityID", aidString), new LDAPAttribute("authorityKeyNickname", nickname), new LDAPAttribute("authorityKeyHost", thisClone), new LDAPAttribute("authorityEnabled", "TRUE"), new LDAPAttribute("authorityDN", subjectDN), new LDAPAttribute("authorityParentDN", parentDNString) }; LDAPAttributeSet attrSet = new LDAPAttributeSet(attrs); if (this.authorityID != null) attrSet.add(new LDAPAttribute("authorityParentID", this.authorityID.toString())); if (description != null) attrSet.add(new LDAPAttribute("description", description)); LDAPEntry ldapEntry = new LDAPEntry(dn, attrSet); addAuthorityEntry(aid, ldapEntry); X509CertImpl cert = null; try { // Generate signing key CryptoManager cryptoManager = CryptoManager.getInstance(); // TODO read PROP_TOKEN_NAME config CryptoToken token = cryptoManager.getInternalKeyStorageToken(); // TODO algorithm parameter KeyPairGenerator gen = token.getKeyPairGenerator(KeyPairAlgorithm.RSA); gen.initialize(2048); KeyPair keypair = gen.genKeyPair(); PublicKey pub = keypair.getPublic(); X509Key x509key = CryptoUtil.convertPublicKeyToX509Key(pub); // Create pkcs10 request logger.debug("createSubCA: creating pkcs10 request"); PKCS10 pkcs10 = new PKCS10(x509key); Signature signature = Signature.getInstance("SHA256withRSA"); signature.initSign(keypair.getPrivate()); pkcs10.encodeAndSign(new X500Signer(signature, subjectX500Name)); ByteArrayOutputStream out = new ByteArrayOutputStream(); pkcs10.print(new PrintStream(out)); String pkcs10String = out.toString(); // Sign certificate Locale locale = Locale.getDefault(); String profileId = "caCACert"; IProfileSubsystem ps = (IProfileSubsystem) CMS.getSubsystem(IProfileSubsystem.ID); IProfile profile = ps.getProfile(profileId); ArgBlock argBlock = new ArgBlock(); argBlock.set("cert_request_type", "pkcs10"); argBlock.set("cert_request", pkcs10String); CertEnrollmentRequest certRequest = CertEnrollmentRequestFactory.create(argBlock, profile, locale); EnrollmentProcessor processor = new EnrollmentProcessor("createSubCA", locale); Map<String, Object> resultMap = processor.processEnrollment(certRequest, null, authorityID, null, authToken); IRequest requests[] = (IRequest[]) resultMap.get(CAProcessor.ARG_REQUESTS); IRequest request = requests[0]; Integer result = request.getExtDataInInteger(IRequest.RESULT); if (result != null && !result.equals(IRequest.RES_SUCCESS)) throw new EBaseException( "createSubCA: certificate request submission resulted in error: " + result); RequestStatus requestStatus = request.getRequestStatus(); if (requestStatus != RequestStatus.COMPLETE) { // The request did not complete. Inference: something // incorrect in the request (e.g. profile constraint // violated). String msg = "Failed to issue CA certificate. Final status: " + requestStatus + "."; String errorMsg = request.getExtDataInString(IRequest.ERROR); if (errorMsg != null) msg += " Additional info: " + errorMsg; throw new BadRequestDataException(msg); } // Add certificate to nssdb cert = request.getExtDataInCert(IEnrollProfile.REQUEST_ISSUED_CERT); cryptoManager.importCertPackage(cert.getEncoded(), nickname); } catch (Exception e) { // something went wrong; delete just-added entry logger.error("Error creating lightweight CA certificate: " + e.getMessage(), e); try { deleteAuthorityEntry(aid); } catch (ELdapException e2) { // we are about to throw ECAException, so just // log this error. logger.error("Error deleting new authority entry after failure during certificate generation: " + e2.getMessage(), e2); } if (e instanceof BadRequestDataException) throw (BadRequestDataException) e; // re-throw else throw new ECAException("Error creating lightweight CA certificate: " + e, e); } CertificateAuthority ca = new CertificateAuthority(hostCA, subjectX500Name, aid, this.authorityID, cert.getSerialNumber(), nickname, Collections.singleton(thisClone), description, true); // Update authority record with serial of issued cert LDAPModificationSet mods = new LDAPModificationSet(); mods.add(LDAPModification.REPLACE, new LDAPAttribute("authoritySerial", cert.getSerialNumber().toString())); ca.modifyAuthorityEntry(mods); return ca; }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
/** * Method that import CA token keys from a P12 file. Was originally used when upgrading from old EJBCA versions. Only supports SHA1 and SHA256 * with RSA or ECDSA and SHA1 with DSA./*www . j a v a 2s. c o m*/ * @throws OperatorCreationException * @throws AuthorizationDeniedException */ private CAToken importKeysToCAToken(AuthenticationToken authenticationToken, String authenticationCode, Properties caTokenProperties, PrivateKey privatekey, PublicKey publickey, PrivateKey privateEncryptionKey, PublicKey publicEncryptionKey, Certificate[] caSignatureCertChain, int caId) throws CryptoTokenAuthenticationFailedException, IllegalCryptoTokenException, OperatorCreationException, AuthorizationDeniedException { // If we don't give an authentication code, perhaps we have autoactivation enabled if (StringUtils.isEmpty(authenticationCode)) { String msg = intres.getLocalizedMessage("token.authcodemissing", Integer.valueOf(caId)); log.info(msg); throw new CryptoTokenAuthenticationFailedException(msg); } if (caTokenProperties == null) { caTokenProperties = new Properties(); } try { // Currently only RSA keys are supported KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(null, null); // The CAs certificate is first in chain Certificate cacert = caSignatureCertChain[0]; // Assume that the same hash algorithm is used for signing that was used to sign this CA cert String signatureAlgorithm = AlgorithmTools.getSignatureAlgorithm(cacert); String keyAlg = AlgorithmTools.getKeyAlgorithm(publickey); if (keyAlg == null) { throw new IllegalCryptoTokenException( "Unknown public key type: " + publickey.getAlgorithm() + " (" + publickey.getClass() + ")"); } // import sign keys. final Certificate[] certchain = new Certificate[1]; certchain[0] = CertTools.genSelfCert("CN=dummy", 36500, null, privatekey, publickey, signatureAlgorithm, true); keystore.setKeyEntry(CAToken.SOFTPRIVATESIGNKEYALIAS, privatekey, null, certchain); // generate enc keys. // Encryption keys must be RSA still final String encryptionAlgorithm = AlgorithmTools.getEncSigAlgFromSigAlg(signatureAlgorithm); keyAlg = AlgorithmTools.getKeyAlgorithmFromSigAlg(encryptionAlgorithm); final String enckeyspec = "2048"; KeyPair enckeys = null; if (publicEncryptionKey == null || privateEncryptionKey == null) { enckeys = KeyTools.genKeys(enckeyspec, keyAlg); } else { enckeys = new KeyPair(publicEncryptionKey, privateEncryptionKey); } // generate dummy certificate certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, enckeys.getPrivate(), enckeys.getPublic(), encryptionAlgorithm, true); keystore.setKeyEntry(CAToken.SOFTPRIVATEDECKEYALIAS, enckeys.getPrivate(), null, certchain); // Set the token properties caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING, CAToken.SOFTPRIVATESIGNKEYALIAS); caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING, CAToken.SOFTPRIVATESIGNKEYALIAS); caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING, CAToken.SOFTPRIVATEDECKEYALIAS); // Write the keystore to byte[] that we can feed to crypto token factory final char[] authCode = authenticationCode.toCharArray(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); keystore.store(baos, authCode); // Now we have the PKCS12 keystore, from this we can create the CAToken final Properties cryptoTokenProperties = new Properties(); int cryptoTokenId; try { cryptoTokenId = createCryptoTokenWithUniqueName(authenticationToken, "ImportedCryptoToken" + caId, SoftCryptoToken.class.getName(), cryptoTokenProperties, baos.toByteArray(), authCode); } catch (NoSuchSlotException e1) { throw new RuntimeException( "Attempte to define a slot for a soft crypto token. This should not happen."); } final CAToken catoken = new CAToken(cryptoTokenId, caTokenProperties); // If this is a CVC CA we need to find out the sequence String sequence = CAToken.DEFAULT_KEYSEQUENCE; if (cacert instanceof CardVerifiableCertificate) { CardVerifiableCertificate cvccacert = (CardVerifiableCertificate) cacert; log.debug("Getting sequence from holderRef in CV certificate."); try { sequence = cvccacert.getCVCertificate().getCertificateBody().getHolderReference().getSequence(); } catch (NoSuchFieldException e) { log.error("Can not get sequence from holderRef in CV certificate, using default sequence."); } } log.debug("Setting sequence " + sequence); catoken.setKeySequence(sequence); log.debug("Setting default sequence format " + StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); catoken.setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); catoken.setSignatureAlgorithm(signatureAlgorithm); catoken.setEncryptionAlgorithm(encryptionAlgorithm); return catoken; } catch (KeyStoreException e) { throw new IllegalCryptoTokenException(e); } catch (NoSuchProviderException e) { throw new IllegalCryptoTokenException(e); } catch (NoSuchAlgorithmException e) { throw new IllegalCryptoTokenException(e); } catch (CertificateException e) { throw new IllegalCryptoTokenException(e); } catch (IOException e) { throw new IllegalCryptoTokenException(e); } catch (IllegalStateException e) { throw new IllegalCryptoTokenException(e); } catch (InvalidAlgorithmParameterException e) { throw new IllegalCryptoTokenException(e); } catch (CryptoTokenOfflineException e) { throw new IllegalCryptoTokenException(e); } }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
private PKCS10CertificationRequest getP10Request() throws Exception { final KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); // Make a PKCS10 request with extensions ASN1EncodableVector attributes = new ASN1EncodableVector(); // Add a custom extension (dummy) ASN1EncodableVector attr = new ASN1EncodableVector(); attr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); ExtensionsGenerator extgen = new ExtensionsGenerator(); extgen.addExtension(new ASN1ObjectIdentifier("1.2.3.4"), false, new DEROctetString("foo123".getBytes())); Extensions exts = extgen.generate(); attr.add(new DERSet(exts)); attributes.add(new DERSequence(attr)); PKCS10CertificationRequest pkcs10 = CertTools.genPKCS10CertificationRequest("SHA1WithRSA", CertTools.stringToBcX500Name("CN=NOUSED"), keys.getPublic(), new DERSet(attributes), keys.getPrivate(), null);//from www . ja va 2 s . c om return pkcs10; }
From source file:com.trsst.Command.java
public int doPost(Client client, CommandLine commands, LinkedList<String> arguments, PrintStream out, InputStream in) {//from w w w .j a v a 2s . c om String id = null; if (arguments.size() == 0 && commands.getArgList().size() == 0) { printPostUsage(); return 127; // "command not found" } if (arguments.size() > 0) { id = arguments.removeFirst(); System.err.println("Obtaining keys for feed id: " + id); } else { System.err.println("Generating new feed id... "); } // read input text String subject = commands.getOptionValue("s"); String verb = commands.getOptionValue("v"); String base = commands.getOptionValue("b"); String body = commands.getOptionValue("c"); String name = commands.getOptionValue("n"); String email = commands.getOptionValue("m"); String uri = commands.getOptionValue("uri"); String title = commands.getOptionValue("t"); String subtitle = commands.getOptionValue("subtitle"); String icon = commands.getOptionValue("i"); if (icon == null && commands.hasOption("i")) { icon = "-"; } String logo = commands.getOptionValue("l"); if (logo == null && commands.hasOption("l")) { logo = "-"; } String attach = commands.getOptionValue("a"); if (attach == null && commands.hasOption("a")) { attach = "-"; } String[] recipients = commands.getOptionValues("e"); String[] mentions = commands.getOptionValues("r"); String[] tags = commands.getOptionValues("g"); String url = commands.getOptionValue("u"); String vanity = commands.getOptionValue("vanity"); // obtain password char[] password = null; String pass = commands.getOptionValue("p"); if (pass != null) { password = pass.toCharArray(); } else { try { Console console = System.console(); if (console != null) { password = console.readPassword("Password: "); } else { log.info("No console detected for password input."); } } catch (Throwable t) { log.error("Unexpected error while reading password", t); } } if (password == null) { log.error("Password is required to post."); return 127; // "command not found" } if (password.length < 6) { System.err.println("Password must be at least six characters in length."); return 127; // "command not found" } // obtain keys KeyPair signingKeys = null; KeyPair encryptionKeys = null; String keyPath = commands.getOptionValue("k"); // if id was not specified from the command line if (id == null) { // if password was not specified from command line if (pass == null) { try { // verify password char[] verify = null; Console console = System.console(); if (console != null) { verify = console.readPassword("Re-type Password: "); } else { log.info("No console detected for password verification."); } if (verify == null || verify.length != password.length) { System.err.println("Passwords do not match."); return 127; // "command not found" } for (int i = 0; i < verify.length; i++) { if (verify[i] != password[i]) { System.err.println("Passwords do not match."); return 127; // "command not found" } verify[i] = 0; } } catch (Throwable t) { log.error("Unexpected error while verifying password: " + t.getMessage(), t); } } // create new account if (base == null) { // default to trsst hub base = "https://home.trsst.com/feed"; } // generate vanity id if required if (vanity != null) { System.err.println("Searching for vanity feed id prefix: " + vanity); switch (vanity.length()) { case 0: case 1: break; case 2: System.err.println("This may take several minutes."); break; case 3: System.err.println("This may take several hours."); break; case 4: System.err.println("This may take several days."); break; case 5: System.err.println("This may take several months."); break; default: System.err.println("This may take several years."); break; } System.err.println("Started: " + new Date()); System.err.println("^C to exit"); } do { signingKeys = Common.generateSigningKeyPair(); id = Common.toFeedId(signingKeys.getPublic()); } while (vanity != null && !id.startsWith(vanity)); if (vanity != null) { System.err.println("Finished: " + new Date()); } encryptionKeys = Common.generateEncryptionKeyPair(); System.err.println("New feed id created: " + id); File keyFile; if (keyPath != null) { keyFile = new File(keyPath, id + Common.KEY_EXTENSION); } else { keyFile = new File(Common.getClientRoot(), id + Common.KEY_EXTENSION); } // persist to keystore writeSigningKeyPair(signingKeys, id, keyFile, password); writeEncryptionKeyPair(encryptionKeys, id, keyFile, password); } else { File keyFile; if (keyPath != null) { keyFile = new File(Common.getClientRoot(), keyPath); } else { keyFile = new File(Common.getClientRoot(), id + Common.KEY_EXTENSION); } if (keyFile.exists()) { System.err.println("Using existing account id: " + id); } else { System.err.println("Cannot locate keys for account id: " + id); return 78; // "configuration error" } signingKeys = readSigningKeyPair(id, keyFile, password); if (signingKeys != null) { encryptionKeys = readEncryptionKeyPair(id, keyFile, password); if (encryptionKeys == null) { encryptionKeys = signingKeys; } } } // clear password chars for (int i = 0; i < password.length; i++) { password[i] = 0; } if (signingKeys == null) { System.err.println("Could not obtain keys for signing."); return 73; // "can't create output error" } String[] recipientIds = null; if (recipients != null) { LinkedList<String> keys = new LinkedList<String>(); for (int i = 0; i < recipients.length; i++) { if ("-".equals(recipients[i])) { // "-" is shorthand for encrypt for mentioned ids if (mentions != null) { for (String mention : mentions) { if (Common.isFeedId(mention)) { keys.add(mention); } } } } else if (Common.isFeedId(recipients[i])) { keys.add(recipients[i]); } else { log.warn("Could not parse recipient id: " + recipients[i]); } } recipientIds = keys.toArray(new String[0]); } // handle binary attachment String mimetype = null; byte[] attachment = null; if (attach != null) { InputStream input = null; try { if ("-".equals(attach)) { input = new BufferedInputStream(in); } else { File file = new File(attach); input = new BufferedInputStream(new FileInputStream(file)); System.err.println("Attaching: " + file.getCanonicalPath()); } attachment = Common.readFully(input); mimetype = new Tika().detect(attachment); System.err.println("Detected type: " + mimetype); } catch (Throwable t) { log.error("Could not read attachment: " + attach, t); return 73; // "can't create output error" } finally { try { input.close(); } catch (IOException ioe) { // suppress any futher error on closing } } } Object result; try { EntryOptions options = new EntryOptions(); options.setStatus(subject); options.setVerb(verb); if (mentions != null) { options.setMentions(mentions); } if (tags != null) { options.setTags(tags); } options.setBody(body); if (attachment != null) { options.addContentData(attachment, mimetype); } else if (url != null) { options.setContentUrl(url); } FeedOptions feedOptions = new FeedOptions(); feedOptions.setAuthorEmail(email); feedOptions.setAuthorName(name); feedOptions.setAuthorUri(uri); feedOptions.setTitle(title); feedOptions.setSubtitle(subtitle); feedOptions.setBase(base); if (icon != null) { if ("-".equals(icon)) { feedOptions.setAsIcon(true); } else { feedOptions.setIconURL(icon); } } if (logo != null) { if ("-".equals(logo)) { feedOptions.setAsLogo(true); } else { feedOptions.setLogoURL(logo); } } if (recipientIds != null) { EntryOptions publicEntry = new EntryOptions().setStatus("Encrypted content").setVerb("encrypt"); // TODO: add duplicate mentions to outside of envelope options.encryptFor(recipientIds, publicEntry); } result = client.post(signingKeys, encryptionKeys, options, feedOptions); } catch (IllegalArgumentException e) { log.error("Invalid request: " + id + " : " + e.getMessage(), e); return 76; // "remote error" } catch (IOException e) { log.error("Error connecting to service for id: " + id, e); return 76; // "remote error" } catch (org.apache.abdera.security.SecurityException e) { log.error("Error generating signatures for id: " + id, e); return 73; // "can't create output error" } catch (Exception e) { log.error("General security error for id: " + id, e); return 74; // "general io error" } if (result != null) { if (format) { out.println(Common.formatXML(result.toString())); } else { out.println(result.toString()); } } return 0; // "OK" }
From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateTest.java
private AuthenticationToken createTokenWithCert(String adminName, AuthenticationSubject subject, KeyPair keys) { // A small check if we have added a "fail" credential to the subject. // If we have we will return null, so we can test authentication failure. Set<?> usercredentials = subject.getCredentials(); if ((usercredentials != null) && (usercredentials.size() > 0)) { Object o = usercredentials.iterator().next(); if (o instanceof String) { String str = (String) o; if (StringUtils.equals("fail", str)) { return null; }//from w ww . j a va 2 s . c o m } } final X509Certificate certificate; // If we have a certificate as input, use that, otherwise generate a self signed certificate Set<X509Certificate> credentials = new HashSet<X509Certificate>(); // If there was no certificate input, create a self signed String dn = "C=SE,O=Test,CN=Test"; // default // If we have created a subject with an X500Principal we will use this DN to create the dummy certificate. { final Set<Principal> principals = subject.getPrincipals(); if ((principals != null) && (principals.size() > 0)) { Principal p = principals.iterator().next(); if (p instanceof X500Principal) { X500Principal xp = (X500Principal) p; dn = xp.getName(); } } } try { createUser(adminName, dn, "foo123"); } catch (AuthorizationDeniedException e1) { throw new CertificateCreationException("Error encountered when creating admin user", e1); } catch (UserDoesntFullfillEndEntityProfile e1) { throw new CertificateCreationException("Error encountered when creating admin user", e1); } catch (WaitingForApprovalException e1) { throw new CertificateCreationException("Error encountered when creating admin user", e1); } catch (EjbcaException e1) { throw new CertificateCreationException("Error encountered when creating admin user", e1); } catch (Exception e1) { throw new CertificateCreationException("Error encountered when creating admin user", e1); } try { certificate = (X509Certificate) this.signSession.createCertificate(ADMIN, adminName, "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); } // Add the credentials and new principal credentials.add(certificate); Set<X500Principal> principals = new HashSet<X500Principal>(); principals.add(certificate.getSubjectX500Principal()); // We cannot use the X509CertificateAuthenticationToken here, since it can only be used internally in a JVM. AuthenticationToken result = new TestX509CertificateAuthenticationToken(principals, credentials); return result; }
From source file:org.ejbca.core.protocol.ws.EjbcaWS.java
@Override public List<TokenCertificateResponseWS> genTokenCertificates(UserDataVOWS userDataWS, List<TokenCertificateRequestWS> tokenRequests, HardTokenDataWS hardTokenDataWS, boolean overwriteExistingSN, boolean revokePreviousCards) throws CADoesntExistsException, AuthorizationDeniedException, WaitingForApprovalException, HardTokenExistsException, UserDoesntFullfillEndEntityProfile, ApprovalException, EjbcaException, ApprovalRequestExpiredException, ApprovalRequestExecutionException { final ArrayList<TokenCertificateResponseWS> retval = new ArrayList<TokenCertificateResponseWS>(); final EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession, caSession, certificateProfileSession, certificateStoreSession, endEntityAccessSession, endEntityProfileSession, hardTokenSession, endEntityManagementSession, webAuthenticationSession, cryptoTokenManagementSession); AuthenticationToken admin = ejbhelper.getAdmin(true); int endEntityProfileId = 0; boolean hardTokenExists = false; boolean userExists = false; boolean approvalSuccessfullStep1 = false; boolean isRejectedStep1 = false; // Get Significant user Id final CAInfo significantcAInfo; final ArrayList<java.security.cert.Certificate> genCertificates = new ArrayList<java.security.cert.Certificate>(); final IPatternLogger logger = TransactionLogger.getPatternLogger(); logAdminName(admin, logger);/*from ww w . j av a2s. com*/ final AuthenticationToken intAdmin = new AlwaysAllowLocalAuthenticationToken( new UsernamePrincipal("EJBCAWS.genTokenCertificates")); try { significantcAInfo = caSession.getCAInfo(intAdmin, userDataWS.getCaName()); if (significantcAInfo == null) { throw EjbcaWSHelper.getEjbcaException( "Error the given CA : " + userDataWS.getCaName() + " could not be found.", logger, ErrorCode.CA_NOT_EXISTS, null); } EndEntityInformation endEntityInformation = endEntityAccessSession.findUser(intAdmin, userDataWS.getUsername()); if (endEntityInformation != null) { endEntityProfileId = endEntityInformation.getEndEntityProfileId(); userExists = true; } else { try { endEntityProfileId = endEntityProfileSession .getEndEntityProfileId(userDataWS.getEndEntityProfileName()); } catch (EndEntityProfileNotFoundException e) { throw EjbcaWSHelper.getEjbcaException("Error given end entity profile : " + userDataWS.getEndEntityProfileName() + " could not be found", logger, ErrorCode.EE_PROFILE_NOT_EXISTS, null); } } // Approval request if we require approvals to generate token certificates ApprovalRequest ar = null; if (ejbhelper.isAdmin()) { final List<String> rules = new ArrayList<String>(); rules.add(StandardRules.CREATECERT.resource()); rules.add(AccessRulesConstants.HARDTOKEN_ISSUEHARDTOKENS); rules.add(StandardRules.CAACCESS.resource() + significantcAInfo.getCAId()); if (overwriteExistingSN) { rules.add(AccessRulesConstants.REGULAR_REVOKEENDENTITY); rules.add(AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId + AccessRulesConstants.REVOKE_END_ENTITY); } if (userExists) { rules.add(AccessRulesConstants.REGULAR_EDITENDENTITY); rules.add(AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId + AccessRulesConstants.EDIT_END_ENTITY); } else { rules.add(AccessRulesConstants.REGULAR_CREATEENDENTITY); rules.add(AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId + AccessRulesConstants.CREATE_END_ENTITY); } String[] rulesArray = rules.toArray(new String[rules.size()]); if (!authorizationSession.isAuthorizedNoLogging(admin, rulesArray)) { final String msg = intres.getLocalizedMessage("authorization.notuathorizedtoresource", Arrays.toString(rulesArray), null); throw new AuthorizationDeniedException(msg); } } else { if (WebServiceConfiguration.getApprovalForGenTokenCertificates()) { ar = new GenerateTokenApprovalRequest(userDataWS.getUsername(), userDataWS.getSubjectDN(), hardTokenDataWS.getLabel(), admin, null, WebServiceConfiguration.getNumberOfRequiredApprovals(), significantcAInfo.getCAId(), endEntityProfileId); int status = ApprovalDataVO.STATUS_REJECTED; try { status = approvalSession.isApproved(admin, ar.generateApprovalId(), 1); approvalSuccessfullStep1 = (status == ApprovalDataVO.STATUS_APPROVED); isRejectedStep1 = (status == ApprovalDataVO.STATUS_REJECTED); if (status == ApprovalDataVO.STATUS_APPROVED) { ApprovalDataVO approvalDataVO = approvalSession.findNonExpiredApprovalRequest(intAdmin, ar.generateApprovalId()); String originalDN = ((GenerateTokenApprovalRequest) approvalDataVO.getApprovalRequest()) .getDN(); userDataWS.setSubjectDN(originalDN); // replace requested DN with original DN to make sure nothing have changed. } else if (status == ApprovalDataVO.STATUS_REJECTED) { throw new ApprovalRequestExecutionException( "The approval for id " + ar.generateApprovalId() + " has been rejected."); } else if (status == ApprovalDataVO.STATUS_EXPIREDANDNOTIFIED || status == ApprovalDataVO.STATUS_EXPIRED) { throw new ApprovalException( "The approval for id " + ar.generateApprovalId() + " has expired."); } else { throw new WaitingForApprovalException("The approval for id " + ar.generateApprovalId() + " have not yet been approved", ar.generateApprovalId()); } } catch (ApprovalException e) { approvalSession.addApprovalRequest(admin, ar); throw new WaitingForApprovalException("Approval request with id " + ar.generateApprovalId() + " have been added for approval.", ar.generateApprovalId()); } } else { throw new AuthorizationDeniedException(); } } if (ar != null && isRejectedStep1) { throw new ApprovalRequestExecutionException( "The approval for id " + ar.generateApprovalId() + " has been rejected."); } if (ar != null && !approvalSuccessfullStep1) { throw new WaitingForApprovalException( "The approval for id " + ar.generateApprovalId() + " has not yet been approved", ar.generateApprovalId()); } if (ar != null) { // We need to create a new AuthenticationToken here that has the "name" of the admin making the request, but that // behaves like an "AlwaysAllowedAuthenticationToken". This is because the request admin does not have privileges, // but we want to log as if the requesting admin performed actions below. final Set<? extends Principal> principals = admin.getPrincipals(); Principal p = null; if (!principals.isEmpty()) { p = principals.iterator().next(); } else { final Set<?> credentials = admin.getCredentials(); if (!credentials.isEmpty()) { final Object o = credentials.iterator().next(); if (o instanceof X509Certificate) { final X509Certificate cert = (X509Certificate) o; p = new X500Principal(cert.getSubjectDN().getName()); } } else { log.error("Admin does not have neither Principals nor Credentials"); } } admin = new AlwaysAllowLocalAuthenticationToken(p); } hardTokenExists = hardTokenSession.existsHardToken(hardTokenDataWS.getHardTokenSN()); if (hardTokenExists) { if (overwriteExistingSN) { // fetch all old certificates and revoke them. Collection<java.security.cert.Certificate> currentCertificates = hardTokenSession .findCertificatesInHardToken(hardTokenDataWS.getHardTokenSN()); HardTokenInformation currentHardToken = hardTokenSession.getHardToken(admin, hardTokenDataWS.getHardTokenSN(), false); Iterator<java.security.cert.Certificate> iter = currentCertificates.iterator(); while (iter.hasNext()) { java.security.cert.X509Certificate nextCert = (java.security.cert.X509Certificate) iter .next(); try { endEntityManagementSession.revokeCert(admin, CertTools.getSerialNumber(nextCert), CertTools.getIssuerDN(nextCert), RevokedCertInfo.REVOCATION_REASON_SUPERSEDED); } catch (AlreadyRevokedException e) { // Ignore previously revoked certificates } catch (FinderException e) { throw EjbcaWSHelper.getEjbcaException( "Error revoking old certificate, the user : " + currentHardToken.getUsername() + " of the old certificate couldn't be found in database.", logger, ErrorCode.USER_NOT_FOUND, null); } } } else { throw new HardTokenExistsException( "Error hard token with sn " + hardTokenDataWS.getHardTokenSN() + " already exists."); } } if (revokePreviousCards) { List<HardTokenDataWS> htd = getHardTokenDatas(admin, userDataWS.getUsername(), false, true, logger); Iterator<HardTokenDataWS> htdIter = htd.iterator(); while (htdIter.hasNext()) { HardTokenDataWS toRevoke = htdIter.next(); try { if (hardTokenDataWS.getLabel().equals(HardTokenConstants.LABEL_TEMPORARYCARD) && toRevoke.getLabel() != null && !toRevoke.getLabel().equals(HardTokenConstants.LABEL_TEMPORARYCARD)) { // Token have extended key usage MS Logon, don't revoke it Iterator<java.security.cert.Certificate> revokeCerts = hardTokenSession .findCertificatesInHardToken(toRevoke.getHardTokenSN()).iterator(); while (revokeCerts.hasNext()) { X509Certificate next = (X509Certificate) revokeCerts.next(); try { if (WebServiceConfiguration.getSuspendAllCertificates() || next.getExtendedKeyUsage() == null || !next.getExtendedKeyUsage() .contains(KeyPurposeId.id_kp_smartcardlogon.getId())) { endEntityManagementSession.revokeCert(admin, next.getSerialNumber(), CertTools.getIssuerDN(next), RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD); } } catch (CertificateParsingException e) { log.error(e); } catch (FinderException e) { log.error(e); } } } else { revokeToken(admin, toRevoke.getHardTokenSN(), RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED, logger); } } catch (AlreadyRevokedException e) { // Do nothing } } } try { // Check if the userdata exist and edit/add it depending on which String password = PasswordGeneratorFactory .getInstance(PasswordGeneratorFactory.PASSWORDTYPE_ALLPRINTABLE).getNewPassword(8, 8); EndEntityInformation userData = ejbhelper.convertUserDataVOWS(admin, userDataWS); userData.setPassword(password); if (userExists) { endEntityManagementSession.changeUser(admin, userData, true); } else { endEntityManagementSession.addUser(admin, userData, true); } Date bDate = new Date(System.currentTimeMillis() - (10 * 60 * 1000)); Iterator<TokenCertificateRequestWS> iter = tokenRequests.iterator(); while (iter.hasNext()) { TokenCertificateRequestWS next = iter.next(); int certificateProfileId = certificateProfileSession .getCertificateProfileId(next.getCertificateProfileName()); if (certificateProfileId == 0) { EjbcaWSHelper .getEjbcaException( "Error the given Certificate Profile : " + next.getCertificateProfileName() + " couldn't be found.", logger, ErrorCode.CERT_PROFILE_NOT_EXISTS, null); } Date eDate = null; if (next.getValidityIdDays() != null) { try { long validity = Long.parseLong(next.getValidityIdDays()); eDate = new Date(System.currentTimeMillis() + (validity * 3600 * 24 * 1000)); } catch (NumberFormatException e) { EjbcaWSHelper.getEjbcaException("Error : Validity in Days must be a number", logger, ErrorCode.BAD_VALIDITY_FORMAT, null); } } CAInfo cAInfo = caSession.getCAInfo(admin, next.getCAName()); if (cAInfo == null) { throw EjbcaWSHelper.getEjbcaException( "Error the given CA : " + next.getCAName() + " couldn't be found.", logger, ErrorCode.CA_NOT_EXISTS, null); } if (!authorizationSession.isAuthorizedNoLogging(admin, StandardRules.CAACCESS.resource() + cAInfo.getCAId())) { final String msg = intres.getLocalizedMessage("authorization.notuathorizedtoresource", StandardRules.CAACCESS.resource() + cAInfo.getCAId(), null); throw new AuthorizationDeniedException(msg); } if (next.getType() == HardTokenConstants.REQUESTTYPE_PKCS10_REQUEST) { userData.setCertificateProfileId(certificateProfileId); userData.setCAId(cAInfo.getCAId()); userData.setPassword(password); userData.setStatus(EndEntityConstants.STATUS_NEW); endEntityManagementSession.changeUser(admin, userData, false); PKCS10RequestMessage pkcs10req = new PKCS10RequestMessage(next.getPkcs10Data()); java.security.cert.Certificate cert; if (eDate == null) { cert = signSession.createCertificate(admin, userData.getUsername(), password, pkcs10req.getRequestPublicKey()); } else { cert = signSession.createCertificate(admin, userData.getUsername(), password, pkcs10req.getRequestPublicKey(), -1, bDate, eDate); } genCertificates.add(cert); retval.add(new TokenCertificateResponseWS(new Certificate(cert))); } else if (next.getType() == HardTokenConstants.REQUESTTYPE_KEYSTORE_REQUEST) { if (!next.getTokenType().equals(HardTokenConstants.TOKENTYPE_PKCS12)) { throw EjbcaWSHelper.getEjbcaException( "Unsupported Key Store Type : " + next.getTokenType() + " only " + HardTokenConstants.TOKENTYPE_PKCS12 + " is supported", logger, ErrorCode.NOT_SUPPORTED_KEY_STORE, null); } KeyPair keys = KeyTools.genKeys(next.getKeyspec(), next.getKeyalg()); userData.setCertificateProfileId(certificateProfileId); userData.setCAId(cAInfo.getCAId()); userData.setPassword(password); userData.setStatus(EndEntityConstants.STATUS_NEW); endEntityManagementSession.changeUser(admin, userData, true); X509Certificate cert; if (eDate == null) { cert = (X509Certificate) signSession.createCertificate(admin, userData.getUsername(), password, keys.getPublic()); } else { cert = (X509Certificate) signSession.createCertificate(admin, userData.getUsername(), password, keys.getPublic(), -1, bDate, eDate); } genCertificates.add(cert); // Generate Keystore // Fetch CA Cert Chain. Collection<java.security.cert.Certificate> chain = caSession .getCAInfo(admin, cAInfo.getCAId()).getCertificateChain(); String alias = CertTools.getPartFromDN(CertTools.getSubjectDN(cert), "CN"); if (alias == null) { alias = userData.getUsername(); } java.security.KeyStore pkcs12 = KeyTools.createP12(alias, keys.getPrivate(), cert, chain); retval.add(new TokenCertificateResponseWS(new KeyStore(pkcs12, userDataWS.getPassword()))); } else { throw EjbcaWSHelper.getEjbcaException( "Error in request, only REQUESTTYPE_PKCS10_REQUEST and REQUESTTYPE_KEYSTORE_REQUEST are supported token requests.", logger, ErrorCode.NOT_SUPPORTED_REQUEST_TYPE, null); } } } catch (Exception e) { throw EjbcaWSHelper.getInternalException(e, logger); } finally { endEntityManagementSession.setUserStatus(admin, userDataWS.getUsername(), EndEntityConstants.STATUS_GENERATED); } // Add hard token data HardToken hardToken; String signatureInitialPIN = ""; String signaturePUK = ""; String basicInitialPIN = ""; String basicPUK = ""; Iterator<PinDataWS> iter = hardTokenDataWS.getPinDatas().iterator(); while (iter.hasNext()) { PinDataWS pinData = iter.next(); switch (pinData.getType()) { case HardTokenConstants.PINTYPE_BASIC: basicInitialPIN = pinData.getInitialPIN(); basicPUK = pinData.getPUK(); break; case HardTokenConstants.PINTYPE_SIGNATURE: signatureInitialPIN = pinData.getInitialPIN(); signaturePUK = pinData.getPUK(); break; default: throw EjbcaWSHelper.getEjbcaException("Unsupported PIN Type " + pinData.getType(), logger, ErrorCode.NOT_SUPPORTED_PIN_TYPE, null); } } int tokenType = SwedishEIDHardToken.THIS_TOKENTYPE; switch (hardTokenDataWS.getTokenType()) { case HardTokenConstants.TOKENTYPE_SWEDISHEID: hardToken = new SwedishEIDHardToken(basicInitialPIN, basicPUK, signatureInitialPIN, signaturePUK, 0); break; case HardTokenConstants.TOKENTYPE_ENHANCEDEID: hardToken = new EnhancedEIDHardToken(signatureInitialPIN, signaturePUK, basicInitialPIN, basicPUK, false, 0); tokenType = EnhancedEIDHardToken.THIS_TOKENTYPE; break; default: throw EjbcaWSHelper.getEjbcaException("Unsupported Token Type : " + hardTokenDataWS.getTokenType(), logger, ErrorCode.NOT_SUPPORTED_TOKEN_TYPE, null); } hardToken.setLabel(hardTokenDataWS.getLabel()); if (overwriteExistingSN) { if (hardTokenExists) { try { hardTokenSession.removeHardToken(admin, hardTokenDataWS.getHardTokenSN()); } catch (HardTokenDoesntExistsException e) { throw EjbcaWSHelper.getEjbcaException(e, logger, ErrorCode.HARD_TOKEN_NOT_EXISTS, Level.ERROR); } } } hardTokenSession.addHardToken(admin, hardTokenDataWS.getHardTokenSN(), userDataWS.getUsername(), significantcAInfo.getSubjectDN(), tokenType, hardToken, genCertificates, hardTokenDataWS.getCopyOfSN()); if (ar != null) { approvalSession.markAsStepDone(admin, ar.generateApprovalId(), GenerateTokenApprovalRequest.STEP_1_GENERATETOKEN); } } catch (FinderException e) { throw EjbcaWSHelper.getInternalException(e, logger); } catch (RuntimeException e) { // EJBException, ClassCastException, ... throw EjbcaWSHelper.getInternalException(e, logger); } finally { logger.writeln(); logger.flush(); } return retval; }
From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java
private AuthenticationToken createTokenWithCert(String adminName, AuthenticationSubject subject, KeyPair keys, int _caid, int eepid, int cpid) { // A small check if we have added a "fail" credential to the subject. // If we have we will return null, so we can test authentication failure. Set<?> usercredentials = subject.getCredentials(); if ((usercredentials != null) && (usercredentials.size() > 0)) { Object o = usercredentials.iterator().next(); if (o instanceof String) { String str = (String) o; if (StringUtils.equals("fail", str)) { return null; }/*from w w w . jav a2 s. c o m*/ } } X509Certificate certificate = null; // If we have a certificate as input, use that, otherwise generate a self signed certificate Set<X509Certificate> credentials = new HashSet<X509Certificate>(); // If there was no certificate input, create a self signed String dn = "C=SE,O=Test,CN=Test"; // default // If we have created a subject with an X500Principal we will use this DN to create the dummy certificate. { Set<Principal> principals = subject.getPrincipals(); if ((principals != null) && (principals.size() > 0)) { Principal p = principals.iterator().next(); if (p instanceof X500Principal) { X500Principal xp = (X500Principal) p; dn = xp.getName(); } } } try { createUser(adminName, dn, "foo123", true, _caid, eepid, cpid); } catch (AuthorizationDeniedException e1) { throw new CertificateCreationException("Error encountered when creating admin user", e1); } catch (UserDoesntFullfillEndEntityProfile e1) { throw new CertificateCreationException("Error encountered when creating admin user", e1); } catch (WaitingForApprovalException e1) { throw new CertificateCreationException("Error encountered when creating admin user", e1); } catch (EjbcaException e1) { throw new CertificateCreationException("Error encountered when creating admin user", e1); } catch (Exception e1) { throw new CertificateCreationException("Error encountered when creating admin user", e1); } try { certificate = (X509Certificate) this.signSession.createCertificate(ADMIN, adminName, "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(certificate); // Add the credentials and new principal credentials.add(certificate); Set<X500Principal> principals = new HashSet<X500Principal>(); principals.add(certificate.getSubjectX500Principal()); // We cannot use the X509CertificateAuthenticationToken here, since it can only be used internally in a JVM. AuthenticationToken result = new TestX509CertificateAuthenticationToken(principals, credentials); assertNotNull(result); return result; }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void getExpiredCerts() throws Exception { String testUsername = "testUserForExpirationTime"; String testCaName = "testCaForExpirationTime"; if (endEntityManagementSession.existsUser(testUsername)) { endEntityManagementSession.revokeAndDeleteUser(intAdmin, testUsername, RevokedCertInfo.REVOCATION_REASON_PRIVILEGESWITHDRAWN); }//from www . j a va 2 s . co m if (caSession.existsCa(testCaName)) { caSession.removeCA(intAdmin, caSession.getCAInfo(intAdmin, testCaName).getCAId()); } java.security.cert.Certificate cert1 = null; java.security.cert.Certificate cert2 = null; try { // ------------------------------------------------------------------------------- // // Create the end entity and certificate profiles that allow extension ovveride // // ------------------------------------------------------------------------------- // CertificateProfile certProfile = certificateProfileSession.getCertificateProfile(WS_CERTPROF_EI); if (certProfile == null) { certProfile = new CertificateProfile(CertificateConstants.CERTTYPE_ENDENTITY); certProfile.setAllowValidityOverride(true); certificateProfileSession.addCertificateProfile(intAdmin, WS_CERTPROF_EI, certProfile); } else { certProfile.setAllowValidityOverride(true); certificateProfileSession.changeCertificateProfile(intAdmin, WS_CERTPROF_EI, certProfile); } int cpid = certificateProfileSession.getCertificateProfileId(WS_CERTPROF_EI); EndEntityProfile eeprofile = endEntityProfileSession.getEndEntityProfile(WS_EEPROF_EI); if (eeprofile == null) { eeprofile = new EndEntityProfile(true); eeprofile.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, Integer.toString(cpid)); this.endEntityProfileSession.addEndEntityProfile(intAdmin, WS_EEPROF_EI, eeprofile); } else { eeprofile.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, Integer.toString(cpid)); this.endEntityProfileSession.changeEndEntityProfile(intAdmin, WS_EEPROF_EI, eeprofile); } // ------------------------------------------------------------------------------------ // // Test ejbcaraws.getCertificatesByExpirationTime() by creating an end entity // // and issue it a certificate by ManagementCA. // // Expected results: return of all certificates that will expire within the specified // // number of days, including the certificate we just issued // // ------------------------------------------------------------------------------------ // KeyPair key = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA); CAInfo cainfo = caSession.getCAInfo(intAdmin, getAdminCAName()); assertNotNull("No CA with name " + getAdminCAName() + " was found.", cainfo); // Create/update an end entity and issue its certificate EndEntityInformation adminUser = endEntityAccessSession.findUser(intAdmin, testUsername); if (adminUser == null) { adminUser = new EndEntityInformation(); adminUser.setUsername(testUsername); adminUser.setPassword("foo123"); adminUser.setDN("CN=" + testUsername); adminUser.setCAId(cainfo.getCAId()); adminUser.setEmail(null); adminUser.setSubjectAltName(null); adminUser.setStatus(UserDataVOWS.STATUS_NEW); adminUser.setTokenType(SecConst.TOKEN_SOFT_JKS); adminUser.setEndEntityProfileId(endEntityProfileSession.getEndEntityProfileId(WS_EEPROF_EI)); adminUser.setCertificateProfileId(cpid); adminUser.setType(new EndEntityType(EndEntityTypes.ENDUSER, EndEntityTypes.ADMINISTRATOR)); log.info("Adding new user: " + adminUser.getUsername()); endEntityManagementSession.addUser(intAdmin, adminUser, true); } else { adminUser.setStatus(UserDataVOWS.STATUS_NEW); adminUser.setPassword("foo123"); log.info("Changing user: " + adminUser.getUsername()); endEntityManagementSession.changeUser(intAdmin, adminUser, true); } Date certNotAfterDate = new Date((new Date()).getTime() + (12 * 60 * 60 * 1000)); // cert will expire in 12 hours from now signSession.createCertificate(intAdmin, testUsername, "foo123", new PublicKeyWrapper(key.getPublic()), KeyUsage.cRLSign, new Date(), certNotAfterDate); List<java.security.cert.Certificate> genCerts = certificateStoreSession .findCertificatesBySubject("CN=" + testUsername); assertEquals("More than one certificate with subjectDN 'CN=" + testUsername + "' was found. Maybe test clean up should be fixed.", 1, genCerts.size()); cert1 = genCerts.get(0); assertEquals(CertificateStatus.OK, certificateStoreSession.getStatus(CertTools.getIssuerDN(cert1), CertTools.getSerialNumber(cert1))); Date testDate = new Date((new Date()).getTime() + (24 * 60 * 60 * 1000)); // 1 day from now assertTrue(CertTools.getNotAfter(cert1).before(testDate)); List<Certificate> certs = ejbcaraws.getCertificatesByExpirationTime(1, 1000); // get certs that will expire in 1 day log.debug("Found " + certs.size() + " certificates that will expire within one day"); assertTrue(certs.size() > 0); boolean certfound = false; Iterator<Certificate> itr = certs.iterator(); while (itr.hasNext()) { Certificate expirewscert = (Certificate) itr.next(); java.security.cert.Certificate expirecert = (java.security.cert.Certificate) CertificateHelper .getCertificate(expirewscert.getCertificateData()); if (StringUtils.equalsIgnoreCase(CertTools.getSubjectDN(cert1), CertTools.getSubjectDN(expirecert))) { certfound = true; break; } } assertTrue(certfound); // ---------------------------------------------------------------------------------------- // // Test ejbcaraws.getCertificatesByExpirationTimeAndIssuer() by modifying the // // end entity above to issue it another certificate by another CA (testCaForExpirationTime) // // 1. Return all certs that will expire within the specific number of days and are issued // // by testCaForExpirationTime. Verify that the certificate issued by ManagementCA above // // is not among the returned certificates // // 2. Return all certs that will expire within the specific number of days and are issued // // by ManagementCA. Verify that the certificate issued by testCaForExpirationTime // // is not among the returned certificates // // ---------------------------------------------------------------------------------------- // CaTestCase.createTestCA(testCaName); assertTrue("Failed to create test CA: " + testCaName, caSession.existsCa(testCaName)); cainfo = caSession.getCAInfo(intAdmin, testCaName); adminUser.setCAId(cainfo.getCAId()); adminUser.setStatus(UserDataVOWS.STATUS_NEW); adminUser.setPassword("foo123"); log.info("Changing user: " + adminUser.getUsername()); endEntityManagementSession.changeUser(intAdmin, adminUser, true); signSession.createCertificate(intAdmin, testUsername, "foo123", new PublicKeyWrapper(key.getPublic()), KeyUsage.cRLSign, new Date(), certNotAfterDate); genCerts = certificateStoreSession.findCertificatesBySubject("CN=" + testUsername); assertEquals("Failed to issue another certificate for user " + testUsername, 2, genCerts.size()); cert2 = genCerts.get(0); if (!CertTools.getIssuerDN(cert2).equalsIgnoreCase(cainfo.getSubjectDN())) { cert2 = genCerts.get(1); } assertEquals(CertificateStatus.OK, certificateStoreSession.getStatus(CertTools.getIssuerDN(cert2), CertTools.getSerialNumber(cert2))); assertTrue(CertTools.getNotAfter(cert2).before(testDate)); // get certs that will expire in 1 day and were issued by testCaForExpirationTime certs = ejbcaraws.getCertificatesByExpirationTimeAndIssuer(1, cainfo.getSubjectDN(), 1000); log.debug("Found " + certs.size() + " certificates that will expire within one day and are issued by " + cainfo.getSubjectDN()); assertTrue(certs.size() > 0); boolean foundcert1 = false; boolean foundcert2 = false; for (Certificate expirewscert : certs) { java.security.cert.Certificate expirecert = (java.security.cert.Certificate) CertificateHelper .getCertificate(expirewscert.getCertificateData()); if (StringUtils.equalsIgnoreCase(CertTools.getSubjectDN(cert1), CertTools.getSubjectDN(expirecert)) && StringUtils.equalsIgnoreCase(CertTools.getIssuerDN(cert1), CertTools.getIssuerDN(expirecert))) { foundcert1 = true; } if (StringUtils.equalsIgnoreCase(CertTools.getSubjectDN(cert2), CertTools.getSubjectDN(expirecert)) && StringUtils.equalsIgnoreCase(CertTools.getIssuerDN(cert2), CertTools.getIssuerDN(expirecert))) { foundcert2 = true; } } assertFalse(foundcert1); assertTrue(foundcert2); // get certs that will expire in 1 day and were issued by ManagementCA certs = ejbcaraws.getCertificatesByExpirationTimeAndIssuer(1, caSession.getCAInfo(intAdmin, getAdminCAName()).getSubjectDN(), 1000); // get certs that will expire in 1 day log.debug("Found " + certs.size() + " certificates that will expire within one day and are issued by " + cainfo.getSubjectDN()); assertTrue(certs.size() > 0); foundcert1 = false; foundcert2 = false; for (Certificate expirewscert : certs) { java.security.cert.Certificate expirecert = (java.security.cert.Certificate) CertificateHelper .getCertificate(expirewscert.getCertificateData()); if (StringUtils.equalsIgnoreCase(CertTools.getSubjectDN(cert1), CertTools.getSubjectDN(expirecert)) && StringUtils.equalsIgnoreCase(CertTools.getIssuerDN(cert1), CertTools.getIssuerDN(expirecert))) { foundcert1 = true; } if (StringUtils.equalsIgnoreCase(CertTools.getSubjectDN(cert2), CertTools.getSubjectDN(expirecert)) && StringUtils.equalsIgnoreCase(CertTools.getIssuerDN(cert2), CertTools.getIssuerDN(expirecert))) { foundcert2 = true; } } assertTrue(foundcert1); assertFalse(foundcert2); } finally { try { endEntityManagementSession.revokeAndDeleteUser(intAdmin, testUsername, RevokedCertInfo.REVOCATION_REASON_PRIVILEGESWITHDRAWN); } catch (NotFoundException e) { /* The test probably failed before creating the end entity */ } if (cert1 != null) { internalCertStoreSession.removeCertificate(CertTools.getFingerprintAsString(cert1)); } if (cert2 != null) { internalCertStoreSession.removeCertificate(CertTools.getFingerprintAsString(cert2)); } caSession.removeCA(intAdmin, caSession.getCAInfo(intAdmin, testCaName).getCAId()); endEntityProfileSession.removeEndEntityProfile(intAdmin, WS_EEPROF_EI); certificateProfileSession.removeCertificateProfile(intAdmin, WS_CERTPROF_EI); } }