List of usage examples for org.bouncycastle.asn1.x500 X500Name X500Name
public X500Name(String dirName)
From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java
License:Open Source License
@Test public void test05CrmfRACertDoesNotExist() throws ObjectNotFoundException, InvalidKeyException, SignatureException, Exception { //------------------- Creating Certificate Request --------------- //PKIMessage crmfMsg = createEESignedCrmfReq(this.subjectDN); byte[] senderNonce = CmpMessageHelper.createSenderNonce(); byte[] transactionID = CmpMessageHelper.createSenderNonce(); Date nb = new Date((new Date()).getTime() - 31536000000L); // not before a year ago Date na = new Date((new Date()).getTime() + 31536000000L); // not afer a yeat from now assertNotNull(nb);//w w w . j a va2s. c om assertNotNull(na); KeyPair keys = null; keys = KeyTools.genKeys("1024", "RSA"); PKIMessage crmfMsg = genCertReq(this.issuerDN, SUBJECT_DN, keys, this.cacert, senderNonce, transactionID, false, null, nb, na, null, null, null); assertNotNull("Failed to create crmfMsg.", crmfMsg); // ---------------- Creating the NestedMessageContent ---------------------- String reqSubjectDN = "CN=bogusSubjectNested"; final byte[] nonce = CmpMessageHelper.createSenderNonce(); final byte[] transid = CmpMessageHelper.createSenderNonce(); PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(new X500Name(reqSubjectDN)), new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName()))); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // nonce DEROctetString dernonce = new DEROctetString(nonce); myPKIHeader.setSenderNonce(dernonce); myPKIHeader.setRecipNonce(dernonce); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); PKIBody myPKIBody = new PKIBody(20, crmfMsg); // NestedMessageContent PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); KeyPair raKeys = KeyTools.genKeys("1024", "RSA"); // Don't create a certificate, so there is no RA cert authorized on the server side. myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(), null, "BC"); assertNotNull("Failed to create myPKIHeader", myPKIHeader); assertNotNull("myPKIBody is null", myPKIBody); assertNotNull("myPKIMessage is null", myPKIMessage); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(myPKIMessage); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, cmpAlias); PKIMessage respObject = null; ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); PKIBody body = respObject.getBody(); assertEquals(23, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); assertEquals("Wrong error message", "Could not verify the RA, signature verification on NestedMessageContent failed.", errMsg); NestedMessageContent nestedContent = new NestedMessageContent(myPKIMessage, cmpAlias, this.globalConfigurationSession); boolean ret = nestedContent.verify(); assertFalse("The message verification failed, yet the a certificate was returned.", ret); }
From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java
License:Open Source License
@Test public void test06NotNestedMessage() throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException, EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception { ASN1EncodableVector optionaValidityV = new ASN1EncodableVector(); org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time( new DERGeneralizedTime("20030211002120Z")); org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date()); optionaValidityV.add(new DERTaggedObject(true, 0, nb)); optionaValidityV.add(new DERTaggedObject(true, 1, na)); OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionaValidityV)); KeyPair keys = KeyTools.genKeys("1024", "RSA"); CertTemplateBuilder myCertTemplate = new CertTemplateBuilder(); myCertTemplate.setValidity(myOptionalValidity); myCertTemplate.setIssuer(new X500Name(this.issuerDN)); myCertTemplate.setSubject(SUBJECT_DN); byte[] bytes = keys.getPublic().getEncoded(); ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); ASN1InputStream dIn = new ASN1InputStream(bIn); try {/*from ww w. j a va2s .com*/ SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject()); myCertTemplate.setPublicKey(keyInfo); // If we did not pass any extensions as parameter, we will create some of our own, standard ones } finally { dIn.close(); } final Extensions exts; { // SubjectAltName ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); ExtensionsGenerator extgen = new ExtensionsGenerator(); // KeyUsage int bcku = 0; bcku = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment | X509KeyUsage.nonRepudiation; X509KeyUsage ku = new X509KeyUsage(bcku); bOut = new ByteArrayOutputStream(); dOut = new DEROutputStream(bOut); dOut.writeObject(ku); byte[] value = bOut.toByteArray(); extgen.addExtension(Extension.keyUsage, false, new DEROctetString(value)); // Make the complete extension package exts = extgen.generate(); } myCertTemplate.setExtensions(exts); CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null); ProofOfPossession myProofOfPossession = new ProofOfPossession(); AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken, new DERUTF8String("foo123")); AttributeTypeAndValue[] avs = { av }; CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs); CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg); PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(SUBJECT_DN), new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName()))); final byte[] nonce = CmpMessageHelper.createSenderNonce(); final byte[] transid = CmpMessageHelper.createSenderNonce(); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); PKIBody myPKIBody = new PKIBody(20, myCertReqMessages); // nestedMessageContent PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); KeyPair raKeys = KeyTools.genKeys("1024", "RSA"); createRACertificate("raSignerTest06", "foo123", this.raCertsPath, cmpAlias, raKeys, null, null, CMPTESTPROFILE, this.caid); myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(), null, "BC"); assertNotNull("Failed to create PKIHeader", myPKIHeader); assertNotNull("Failed to create PKIBody", myPKIBody); assertNotNull("Failed to create PKIMessage", myPKIMessage); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(myPKIMessage); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, cmpAlias); PKIMessage respObject = null; ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); PKIBody body = respObject.getBody(); assertEquals(23, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); assertEquals("unknown object in getInstance: org.bouncycastle.asn1.DERSequence", errMsg); }
From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java
License:Open Source License
@Test public void test07ExpiredRACert() throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException, EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception { log.info(">test07ExpiredRACert()"); //------------------- Creating Certificate Request --------------- //PKIMessage crmfMsg = createEESignedCrmfReq(this.subjectDN); byte[] senderNonce = CmpMessageHelper.createSenderNonce(); byte[] transactionID = CmpMessageHelper.createSenderNonce(); Date nb = new Date((new Date()).getTime() - 31536000000L); // not before a year ago Date na = new Date((new Date()).getTime() + 31536000000L); // not afer a yeat from now assertNotNull(nb);/*ww w . ja v a 2 s.c o m*/ assertNotNull(na); KeyPair keys = null; keys = KeyTools.genKeys("1024", "RSA"); PKIMessage crmfMsg = genCertReq(this.issuerDN, SUBJECT_DN, keys, this.cacert, senderNonce, transactionID, false, null, nb, na, null, null, null); assertNotNull("Failed to create crmfMsg.", crmfMsg); // ---------------- Creating the NestedMessageContent ---------------------- final X500Name reqSubjectDN = new X500Name("CN=bogusSubjectNested"); final byte[] nonce = CmpMessageHelper.createSenderNonce(); final byte[] transid = CmpMessageHelper.createSenderNonce(); PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(reqSubjectDN), new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName()))); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); myPKIHeader.setRecipNonce(new DEROctetString(nonce)); PKIBody myPKIBody = new PKIBody(20, crmfMsg); // NestedMessageContent PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); KeyPair raKeys = KeyTools.genKeys("1024", "RSA"); long nbTime = (new Date()).getTime() - 1000000L; createRACertificate("raExpiredSignerTest07", "foo123", this.raCertsPath, cmpAlias, raKeys, new Date(nbTime), new Date(), CMPTESTPROFILE, this.caid); Thread.sleep(5000); myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(), null, "BC"); assertNotNull("Failed to create myPKIHeader", myPKIHeader); assertNotNull("myPKIBody is null", myPKIBody); assertNotNull("myPKIMessage is null", myPKIMessage); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(myPKIMessage); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, cmpAlias); //final byte[] resp = sendCmpHttp(myPKIMessage.toASN1Primitive().toASN1Object().getEncoded(), 200); // do not check signing if we expect a failure (sFailMessage==null) checkCmpResponseGeneral(resp, this.issuerDN, reqSubjectDN, this.cacert, myPKIMessage.getHeader().getSenderNonce().getOctets(), myPKIMessage.getHeader().getTransactionID().getOctets(), false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); PKIMessage respObject = null; ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); PKIBody body = respObject.getBody(); assertEquals(23, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); assertEquals("Wrong error message", "Could not verify the RA, signature verification on NestedMessageContent failed.", errMsg); log.info("<test07ExpiredRACert()"); }
From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java
License:Open Source License
@Test public void test08MissingSignature() throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException, EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception { log.info(">test07ExpiredRACert()"); //------------------- Creating Certificate Request --------------- byte[] senderNonce = CmpMessageHelper.createSenderNonce(); byte[] transactionID = CmpMessageHelper.createSenderNonce(); Date nb = new Date((new Date()).getTime() - 31536000000L); // not before a year ago Date na = new Date((new Date()).getTime() + 31536000000L); // not afer a yeat from now assertNotNull(nb);/*from ww w. j av a2s. c om*/ assertNotNull(na); KeyPair keys = null; keys = KeyTools.genKeys("1024", "RSA"); PKIMessage crmfMsg = genCertReq(this.issuerDN, SUBJECT_DN, keys, this.cacert, senderNonce, transactionID, false, null, nb, na, null, null, null); assertNotNull("Failed to create crmfMsg.", crmfMsg); // ---------------- Creating the NestedMessageContent ---------------------- final X500Name reqSubjectDN = new X500Name("CN=bogusSubjectNested"); final byte[] nonce = CmpMessageHelper.createSenderNonce(); final byte[] transid = CmpMessageHelper.createSenderNonce(); PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(reqSubjectDN), new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName()))); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); myPKIHeader.setRecipNonce(new DEROctetString(nonce)); PKIBody myPKIBody = new PKIBody(20, crmfMsg); // NestedMessageContent PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); assertNotNull("Failed to create myPKIHeader", myPKIHeader); assertNotNull("myPKIBody is null", myPKIBody); assertNotNull("myPKIMessage is null", myPKIMessage); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(myPKIMessage); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, cmpAlias); //final byte[] resp = sendCmpHttp(myPKIMessage.toASN1Primitive().toASN1Object().getEncoded(), 200); // do not check signing if we expect a failure (sFailMessage==null) checkCmpResponseGeneral(resp, this.issuerDN, reqSubjectDN, this.cacert, myPKIMessage.getHeader().getSenderNonce().getOctets(), myPKIMessage.getHeader().getTransactionID().getOctets(), false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); PKIMessage respObject = null; ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); PKIBody body = respObject.getBody(); assertEquals(23, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); assertEquals("Wrong error message", "Could not verify the RA, signature verification on NestedMessageContent failed.", errMsg); log.info("<test07ExpiredRACert()"); }
From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java
License:Open Source License
@Test public void test09CrmfWrongIssuerAndDoNotCheckAdmin() throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException, EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception { this.cmpConfiguration.setAuthenticationParameters(cmpAlias, "-;foo123"); this.cmpConfiguration.setOmitVerificationsInECC(cmpAlias, true); this.globalConfigurationSession.saveConfiguration(this.admin, this.cmpConfiguration); //-----------------Creating CRMF request //PKIMessage crmfMsg = createEESignedCrmfReq(this.subjectDN); byte[] senderNonce = CmpMessageHelper.createSenderNonce(); byte[] transactionID = CmpMessageHelper.createSenderNonce(); Date nb = new Date((new Date()).getTime() - 31536000000L); // not before a year ago Date na = new Date((new Date()).getTime() + 31536000000L); // not afer a yeat from now assertNotNull(nb);/*from w ww.j a v a 2 s.c o m*/ assertNotNull(na); KeyPair keys = KeyTools.genKeys("1024", "RSA"); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage crmfMsg = genCertReq(this.issuerDN, SUBJECT_DN, keys, this.cacert, senderNonce, transactionID, false, null, nb, na, null, pAlg, new DEROctetString(senderNonce)); KeyPair nonAdminKeys = KeyTools.genKeys("1024", "RSA"); Certificate nonAdminCert = CertTools.genSelfCert("CN=cmpTestAdmin,C=SE", 365, null, nonAdminKeys.getPrivate(), nonAdminKeys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, false); CMPCertificate[] cmpcert = getCMPCert(nonAdminCert); crmfMsg = CmpMessageHelper.buildCertBasedPKIProtection(crmfMsg, cmpcert, nonAdminKeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(crmfMsg); CertReqMessages ir = (CertReqMessages) crmfMsg.getBody().getContent(); int reqID = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); //------------------Creating NestedMessageContent String reqSubjectDN = "CN=bogusSubjectNested"; final byte[] nonce = CmpMessageHelper.createSenderNonce(); final byte[] transid = CmpMessageHelper.createSenderNonce(); PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(new X500Name(reqSubjectDN)), new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName()))); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(crmfMsg); DERSequence seq = new DERSequence(v); PKIBody myPKIBody = new PKIBody(20, seq); // NestedMessageContent assertNotNull("Failed to create nested Message PKIBody", myPKIBody); PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); assertNotNull("Failed to created nested message PKIMessage", myPKIMessage); KeyPair raKeys = KeyTools.genKeys("1024", "RSA"); createRACertificate("raCrmfSigner", "foo123", this.raCertsPath, cmpAlias, raKeys, null, null, CMPTESTPROFILE, this.caid); myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull("Failed to create myPKIHeader", myPKIHeader); assertNotNull("myPKIBody is null", myPKIBody); assertNotNull("myPKIMessage is null", myPKIMessage); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(myPKIMessage); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, cmpAlias); //final byte[] resp = sendCmpHttp(myPKIMessage.toASN1Primitive().toASN1Object().getEncoded(), 200); // do not check signing if we expect a failure (sFailMessage==null) checkCmpResponseGeneral(resp, this.issuerDN, SUBJECT_DN, this.cacert, crmfMsg.getHeader().getSenderNonce().getOctets(), crmfMsg.getHeader().getTransactionID().getOctets(), false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); final Certificate cert = checkCmpCertRepMessage(SUBJECT_DN, this.cacert, resp, reqID); assertNotNull("CrmfRequest did not return a certificate", cert); assertTrue(cert instanceof X509Certificate); log.debug("Subject DN of created certificate: " + X500Name.getInstance(((X509Certificate) cert).getSubjectX500Principal().getEncoded())); }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
License:Open Source License
private CertReqMsg createCrmfRequest(final String issuerDN, final String userDN, final KeyPair keys, final String extensionOid) throws IOException { CertTemplateBuilder myCertTemplate = new CertTemplateBuilder(); myCertTemplate.setIssuer(new X500Name(issuerDN)); myCertTemplate.setSubject(new X500Name(userDN)); byte[] bytes = keys.getPublic().getEncoded(); ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); ASN1InputStream dIn = new ASN1InputStream(bIn); try {//from w w w.ja v a 2s . c o m SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject()); myCertTemplate.setPublicKey(keyInfo); } finally { dIn.close(); } // If we did not pass any extensions as parameter, we will create some of our own, standard ones ExtensionsGenerator extgen = new ExtensionsGenerator(); extgen.addExtension(new ASN1ObjectIdentifier(extensionOid), false, new DEROctetString("foo123".getBytes())); myCertTemplate.setExtensions(extgen.generate()); CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null); CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, null, null); return myCertReqMsg; }
From source file:org.ejbca.ui.cli.ca.CaImportCRLCommand.java
License:Open Source License
@Override public CommandResult execute(ParameterContainer parameters) { log.trace(">execute()"); CryptoProviderTools.installBCProvider(); try {/*w w w .ja v a 2s .c o m*/ // Parse arguments final String caname = parameters.get(CA_NAME_KEY); final String crl_file = parameters.get(CRL_FILE_KEY); final String operationsMode = parameters.get(OPERATION_KEY); final boolean strict = operationsMode.equalsIgnoreCase(STRICT_OP); final boolean adaptive = operationsMode.equalsIgnoreCase(ADAPTIVE_OP); if (!strict && !adaptive && !operationsMode.equalsIgnoreCase(LENIENT_OP)) { //None of the above. log.error("Operations mode must be one of " + STRICT_OP + ", " + LENIENT_OP + " or " + ADAPTIVE_OP + "."); return CommandResult.CLI_FAILURE; } // Fetch CA and related info final CAInfo cainfo = getCAInfo(getAuthenticationToken(), caname); final X509Certificate cacert = (X509Certificate) cainfo.getCertificateChain().iterator().next(); final String issuer = CertTools.stringToBCDNString(cacert.getSubjectDN().toString()); log.info("CA: " + issuer); // Read the supplied CRL and verify that it is issued by the specified CA final X509CRL x509crl = (X509CRL) CertTools.getCertificateFactory() .generateCRL(new FileInputStream(crl_file)); if (!x509crl.getIssuerX500Principal().equals(cacert.getSubjectX500Principal())) { throw new IOException("CRL wasn't issued by this CA"); } x509crl.verify(cacert.getPublicKey()); int crl_no = CrlExtensions.getCrlNumber(x509crl).intValue(); log.info("Processing CRL #" + crl_no); int miss_count = 0; // Number of certs not already in database int revoked = 0; // Number of certs activly revoked by this algorithm int already_revoked = 0; // Number of certs already revoked in database and ignored in non-strict mode final String missing_user_name = MISSING_USERNAME_PREFIX + caname; @SuppressWarnings("unchecked") Set<X509CRLEntry> entries = (Set<X509CRLEntry>) x509crl.getRevokedCertificates(); if (entries != null) { for (final X509CRLEntry entry : entries) { final BigInteger serialNr = entry.getSerialNumber(); final String serialHex = serialNr.toString(16).toUpperCase(); final String username = EjbRemoteHelper.INSTANCE .getRemoteSession(CertificateStoreSessionRemote.class) .findUsernameByCertSerno(serialNr, issuer); // If this certificate exists and has an assigned username, we keep using that. Otherwise we create this coupling to a user. if (username == null) { log.info("Certificate '" + serialHex + "' missing in the database"); if (strict) { throw new IOException( "Aborted! Running in strict mode and is missing certificate in database."); } miss_count++; if (!adaptive) { continue; } final Date time = new Date(); // time from which certificate is valid final KeyPair key_pair = KeyTools.genKeys("2048", AlgorithmConstants.KEYALGORITHM_RSA); final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Primitive.fromByteArray(key_pair.getPublic().getEncoded())); final X500Name dnName = new X500Name( "CN=Dummy Missing in Imported CRL, serialNumber=" + serialHex); final Date notAfter = new Date(time.getTime() + 1000L * 60 * 60 * 24 * 365 * 10); // 10 years of life final X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder( X500Name.getInstance(cacert.getSubjectX500Principal().getEncoded()), serialNr, time, notAfter, dnName, pkinfo); final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder("SHA1withRSA") .setProvider(BouncyCastleProvider.PROVIDER_NAME) .build(key_pair.getPrivate()), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); final X509Certificate certificate = (X509Certificate) CertTools .getCertfromByteArray(certHolder.getEncoded()); final String fingerprint = CertTools.getFingerprintAsString(certificate); // We add all certificates that does not have a user already to "missing_user_name" final EndEntityInformation missingUserEndEntityInformation = EjbRemoteHelper.INSTANCE .getRemoteSession(EndEntityAccessSessionRemote.class) .findUser(getAuthenticationToken(), missing_user_name); if (missingUserEndEntityInformation == null) { // Add the user and change status to REVOKED log.debug("Loading/updating user " + missing_user_name); final EndEntityInformation userdataNew = new EndEntityInformation(missing_user_name, CertTools.getSubjectDN(certificate), cainfo.getCAId(), null, null, EndEntityConstants.STATUS_NEW, new EndEntityType(EndEntityTypes.ENDUSER), SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, null, null, SecConst.TOKEN_SOFT_BROWSERGEN, SecConst.NO_HARDTOKENISSUER, null); userdataNew.setPassword("foo123"); EjbRemoteHelper.INSTANCE.getRemoteSession(EndEntityManagementSessionRemote.class) .addUser(getAuthenticationToken(), userdataNew, false); log.info("User '" + missing_user_name + "' has been added."); EjbRemoteHelper.INSTANCE.getRemoteSession(EndEntityManagementSessionRemote.class) .setUserStatus(getAuthenticationToken(), missing_user_name, EndEntityConstants.STATUS_REVOKED); log.info("User '" + missing_user_name + "' has been updated."); } EjbRemoteHelper.INSTANCE.getRemoteSession(CertificateStoreSessionRemote.class) .storeCertificate(getAuthenticationToken(), certificate, missing_user_name, fingerprint, CertificateConstants.CERT_ACTIVE, CertificateConstants.CERTTYPE_ENDENTITY, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, null, new Date().getTime()); log.info("Dummy certificate '" + serialHex + "' has been stored."); } // This check will not catch a certificate with status CertificateConstants.CERT_ARCHIVED if (!strict && EjbRemoteHelper.INSTANCE.getRemoteSession(CertificateStoreSessionRemote.class) .isRevoked(issuer, serialNr)) { log.info("Certificate '" + serialHex + "' is already revoked"); already_revoked++; continue; } log.info("Revoking '" + serialHex + "' " + "(" + serialNr.toString() + ")"); try { int reason = getCRLReasonValue(entry); log.info("Reason code: " + reason); EjbRemoteHelper.INSTANCE.getRemoteSession(EndEntityManagementSessionRemote.class) .revokeCert(getAuthenticationToken(), serialNr, entry.getRevocationDate(), issuer, reason, false); revoked++; } catch (AlreadyRevokedException e) { already_revoked++; log.warn("Failed to revoke '" + serialHex + "'. (Status might be 'Archived'.) Error message was: " + e.getMessage()); } } } // if (entries != null) if (EjbRemoteHelper.INSTANCE.getRemoteSession(CrlStoreSessionRemote.class).getLastCRLNumber(issuer, false) < crl_no) { EjbRemoteHelper.INSTANCE.getRemoteSession(CrlStoreSessionRemote.class).storeCRL( getAuthenticationToken(), x509crl.getEncoded(), CertTools.getFingerprintAsString(cacert), crl_no, issuer, x509crl.getThisUpdate(), x509crl.getNextUpdate(), -1); } else { if (strict) { throw new IOException("CRL #" + crl_no + " or higher is already in the database"); } } log.info("\nSummary:\nRevoked " + revoked + " certificates"); if (already_revoked > 0) { log.info(already_revoked + " certificates were already revoked"); } if (miss_count > 0) { log.info("There were " + miss_count + (adaptive ? " dummy certificates added to" : " certificates missing in") + " the database"); } log.info("CRL #" + crl_no + " stored in the database"); } catch (Exception e) { //FIXME: This is all kinds of suboptimal. log.info("Error: " + e.getMessage()); return CommandResult.FUNCTIONAL_FAILURE; } log.trace("<execute()"); return CommandResult.SUCCESS; }
From source file:org.ejbca.ui.cmpclient.commands.ConfirmationRequestCommand.java
License:Open Source License
@Override public PKIMessage generatePKIMessage(ParameterContainer parameters) throws Exception { final boolean verbose = parameters.containsKey(VERBOSE_KEY); final X500Name userDN = new X500Name("CN=foo"); String issuer = parameters.get(ISSUERDN_KEY); if (issuer == null) { issuer = "CN=foobar"; log.info("Using default issuerDN: " + issuer); }//from www .j a va 2 s . c o m final X500Name issuerDN = new X500Name(issuer); if (verbose) { log.info("Creating confirmation request with: SubjectDN=" + userDN.toString()); log.info("Creating confirmation request with: IssuerDN=" + issuerDN.toString()); } byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce(); byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce(); byte[] hash = new byte[0]; PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(issuerDN)); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); CertStatus cs = new CertStatus(hash, new BigInteger("0")); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(cs); CertConfirmContent cc = CertConfirmContent.getInstance(new DERSequence(v)); PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_CERT_CONFIRM, cc); // Cert Confirm PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); return myPKIMessage; }
From source file:org.ejbca.ui.cmpclient.commands.CrmfRequestCommand.java
License:Open Source License
@Override public PKIMessage generatePKIMessage(final ParameterContainer parameters) throws Exception { final boolean verbose = parameters.containsKey(VERBOSE_KEY); final X500Name userDN = new X500Name(parameters.get(SUBJECTDN_KEY)); final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY)); String authmodule = parameters.get(AUTHENTICATION_MODULE_KEY); String endentityPassword = ""; if (authmodule != null && StringUtils.equals(authmodule, CmpConfiguration.AUTHMODULE_REG_TOKEN_PWD)) { endentityPassword = parameters.containsKey(AUTHENTICATION_PARAM_KEY) ? parameters.get(AUTHENTICATION_PARAM_KEY) : "foo123"; }/*from w w w . j a v a2 s . co m*/ String altNames = parameters.get(ALTNAME_KEY); String serno = parameters.get(SERNO_KEY); BigInteger customCertSerno = null; if (serno != null) { customCertSerno = new BigInteger(serno, 16); } boolean includePopo = parameters.containsKey(INCLUDE_POPO_KEY); if (verbose) { log.info("Creating CRMF request with: SubjectDN=" + userDN.toString()); log.info("Creating CRMF request with: IssuerDN=" + issuerDN.toString()); log.info("Creating CRMF request with: AuthenticationModule=" + authmodule); log.info("Creating CRMF request with: EndEntityPassword=" + endentityPassword); log.info("Creating CRMF request with: SubjectAltName=" + altNames); log.info("Creating CRMF request with: CustomCertSerno=" + (customCertSerno == null ? "" : customCertSerno.toString(16))); log.info("Creating CRMF request with: IncludePopo=" + includePopo); } final KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA); final byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce(); final byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce(); // We should be able to back date the start time when allow validity // override is enabled in the certificate profile Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_WEEK, -1); cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds // in validity Date notBefore = cal.getTime(); cal.add(Calendar.DAY_OF_WEEK, 3); cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(notBefore); // in validity Date notAfter = cal.getTime(); org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(notAfter); ASN1EncodableVector optionalValidityV = new ASN1EncodableVector(); optionalValidityV.add(new DERTaggedObject(true, 0, nb)); optionalValidityV.add(new DERTaggedObject(true, 1, na)); OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV)); CertTemplateBuilder myCertTemplate = new CertTemplateBuilder(); myCertTemplate.setValidity(myOptionalValidity); if (issuerDN != null) { myCertTemplate.setIssuer(issuerDN); } myCertTemplate.setSubject(userDN); byte[] bytes = keys.getPublic().getEncoded(); ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); ASN1InputStream dIn = new ASN1InputStream(bIn); SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject()); dIn.close(); myCertTemplate.setPublicKey(keyInfo); // Create standard extensions ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream dOut = new ASN1OutputStream(bOut); ExtensionsGenerator extgen = new ExtensionsGenerator(); if (altNames != null) { GeneralNames san = CertTools.getGeneralNamesFromAltName(altNames); dOut.writeObject(san); byte[] value = bOut.toByteArray(); extgen.addExtension(Extension.subjectAlternativeName, false, value); } // KeyUsage int bcku = 0; bcku = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation; KeyUsage ku = new KeyUsage(bcku); extgen.addExtension(Extension.keyUsage, false, new DERBitString(ku)); // Make the complete extension package Extensions exts = extgen.generate(); myCertTemplate.setExtensions(exts); if (customCertSerno != null) { // Add serialNumber to the certTemplate, it is defined as a MUST NOT be used in RFC4211, but we will use it anyway in order // to request a custom certificate serial number (something not standard anyway) myCertTemplate.setSerialNumber(new ASN1Integer(customCertSerno)); } CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null); // POPO /* * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8, * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 })); * * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new * byte[] { 44 }), 2); //take choice pos tag 2 * * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput( * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2, * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 })); */ ProofOfPossession myProofOfPossession = null; if (includePopo) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DEROutputStream mout = new DEROutputStream(baos); mout.writeObject(myCertRequest); mout.close(); byte[] popoProtectionBytes = baos.toByteArray(); String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm()) .getId(); Signature sig = Signature.getInstance(sigalg, "BC"); sig.initSign(keys.getPrivate()); sig.update(popoProtectionBytes); DERBitString bs = new DERBitString(sig.sign()); POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null, new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs); myProofOfPossession = new ProofOfPossession(myPOPOSigningKey); } else { // raVerified POPO (meaning there is no POPO) myProofOfPossession = new ProofOfPossession(); } AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken, new DERUTF8String(endentityPassword)); AttributeTypeAndValue[] avs = { av }; CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs); CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg); PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(issuerDN)); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); myPKIHeader.setProtectionAlg(null); myPKIHeader.setSenderKID(new byte[0]); PKIBody myPKIBody = new PKIBody(0, myCertReqMessages); // initialization // request PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); return myPKIMessage; }
From source file:org.ejbca.ui.cmpclient.commands.KeyUpdateRequestCommand.java
License:Open Source License
@Override public PKIMessage generatePKIMessage(ParameterContainer parameters) throws Exception { boolean verbose = parameters.containsKey(VERBOSE_KEY); final X500Name userDN = new X500Name(parameters.get(SUBJECTDN_KEY)); final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY)); boolean includePopo = parameters.containsKey(INCLUDE_POPO_KEY); if (verbose) { log.info("Creating KeyUpdate request with: SubjectDN=" + userDN.toString()); log.info("Creating KeyUpdate request with: IssuerDN=" + issuerDN.toString()); log.info("Creating KeyUpdate request with: IncludePopo=" + includePopo); }/*from w ww . ja v a2s . c o m*/ byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce(); byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce(); KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA); CertTemplateBuilder myCertTemplate = new CertTemplateBuilder(); ASN1EncodableVector optionalValidityV = new ASN1EncodableVector(); org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time( new DERGeneralizedTime("20030211002120Z")); org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date()); optionalValidityV.add(new DERTaggedObject(true, 0, nb)); optionalValidityV.add(new DERTaggedObject(true, 1, na)); OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV)); myCertTemplate.setValidity(myOptionalValidity); byte[] bytes = keys.getPublic().getEncoded(); ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); ASN1InputStream dIn = new ASN1InputStream(bIn); try { SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject()); myCertTemplate.setPublicKey(keyInfo); } finally { dIn.close(); } myCertTemplate.setSubject(userDN); CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null); // POPO /* * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8, * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 })); * * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new * byte[] { 44 }), 2); //take choice pos tag 2 * * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput( * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2, * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 })); */ ProofOfPossession myProofOfPossession = null; if (includePopo) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DEROutputStream mout = new DEROutputStream(baos); mout.writeObject(myCertRequest); mout.close(); byte[] popoProtectionBytes = baos.toByteArray(); String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm()) .getId(); Signature sig = Signature.getInstance(sigalg); sig.initSign(keys.getPrivate()); sig.update(popoProtectionBytes); DERBitString bs = new DERBitString(sig.sign()); POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null, new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs); myProofOfPossession = new ProofOfPossession(myPOPOSigningKey); } else { // raVerified POPO (meaning there is no POPO) myProofOfPossession = new ProofOfPossession(); } // myCertReqMsg.addRegInfo(new AttributeTypeAndValue(new // ASN1ObjectIdentifier("1.3.6.2.2.2.2.3.1"), new // DERInteger(1122334455))); AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken, new DERUTF8String("")); AttributeTypeAndValue[] avs = { av }; CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs); CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg); PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(issuerDN)); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); myPKIHeader.setProtectionAlg(null); PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_KEY_UPDATE_REQ, myCertReqMessages); // Key Update Request PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); return myPKIMessage; }