List of usage examples for org.bouncycastle.asn1.x500 X500Name X500Name
public X500Name(String dirName)
From source file:org.ejbca.core.protocol.cmp.CrmfRequestTest.java
License:Open Source License
@Test public void test11IncludingCertChainInSignedCMPResponse() throws Exception { //---------- Create SubCA signed by testx509ca (rootCA) ------------- // String subcaDN = "CN=SubTestCA"; int subcaID = subcaDN.hashCode(); int cryptoTokenId = CryptoTokenTestUtils.createCryptoTokenForCA(ADMIN, null, true, false, subcaDN, "1024"); final String username = "cmptest"; try {/*from www . j av a2s. c o m*/ final CAToken catoken = CaTestUtils.createCaToken(cryptoTokenId, AlgorithmConstants.SIGALG_SHA256_WITH_RSA, AlgorithmConstants.SIGALG_SHA256_WITH_RSA); final List<ExtendedCAServiceInfo> extendedCaServices = new ArrayList<ExtendedCAServiceInfo>(2); extendedCaServices.add(new KeyRecoveryCAServiceInfo(ExtendedCAServiceInfo.STATUS_ACTIVE)); String caname = CertTools.getPartFromDN(subcaDN, "CN"); boolean ldapOrder = !CertTools.isDNReversed(subcaDN); X509CAInfo cainfo = new X509CAInfo(subcaDN, caname, CAConstants.CA_ACTIVE, CertificateProfileConstants.CERTPROFILE_FIXED_SUBCA, 3650, this.caid, this.testx509ca.getCertificateChain(), catoken); cainfo.setDescription("JUnit RSA SubCA"); cainfo.setExtendedCAServiceInfos(extendedCaServices); cainfo.setUseLdapDnOrder(ldapOrder); cainfo.setCmpRaAuthSecret("foo123"); CAAdminSessionRemote caAdminSession = EjbRemoteHelper.INSTANCE .getRemoteSession(CAAdminSessionRemote.class); caAdminSession.createCA(ADMIN, cainfo); assertTrue(this.caSession.existsCa(subcaID)); cainfo = (X509CAInfo) this.caSession.getCAInfo(ADMIN, subcaID); X509Certificate subcaCert = (X509Certificate) cainfo.getCertificateChain().iterator().next(); // --------- Create a user ----------------- // boolean userExists = false; final X500Name userDN = new X500Name("C=SE,O=PrimeKey,CN=cmptest"); EndEntityInformation user = new EndEntityInformation("cmptest", userDN.toString(), subcaID, null, "cmptest@primekey.se", new EndEntityType(EndEntityTypes.ENDUSER), // SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, this.eepDnOverrideId, this.cpDnOverrideId, SecConst.TOKEN_SOFT_PEM, 0, null); user.setPassword("foo123"); try { this.endEntityManagementSession.addUser(ADMIN, user, true); log.debug("created user: cmptest, foo123, " + userDN); } catch (Exception e) { userExists = true; } if (userExists) { log.debug("User cmptest already exists."); this.endEntityManagementSession.changeUser(ADMIN, user, true); this.endEntityManagementSession.setUserStatus(ADMIN, "cmptest", EndEntityConstants.STATUS_NEW); log.debug("Reset status to NEW"); } assertTrue(this.endEntityManagementSession.existsUser("cmptest")); EndEntityAccessSessionRemote eeAccessSession = EjbRemoteHelper.INSTANCE .getRemoteSession(EndEntityAccessSessionRemote.class); EndEntityInformation ee = eeAccessSession.findUser(ADMIN, "cmptest"); assertEquals(subcaID, ee.getCAId()); // -------- generate and send a CMP request -------------- // byte[] nonce = CmpMessageHelper.createSenderNonce(); byte[] transid = CmpMessageHelper.createSenderNonce(); PKIMessage req = genCertReq(subcaDN, userDN, this.keys, subcaCert, nonce, transid, false, null, null, null, null, null, null); assertNotNull(req); CertReqMessages ir = (CertReqMessages) req.getBody().getContent(); int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); byte[] ba = bao.toByteArray(); // Send request and receive response byte[] resp = sendCmpHttp(ba, 200, cmpAlias); checkCmpResponseGeneral(resp, subcaDN, userDN, subcaCert, nonce, transid, true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); final X509Certificate cert = checkCmpCertRepMessage(userDN, subcaCert, resp, reqId); assertNotNull(cert); // ------- Check that the entire certificate chain is in the extraCerts field in the response PKIMessage respMsg = null; ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); try { respMsg = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respMsg); CMPCertificate[] certChain = respMsg.getExtraCerts(); assertEquals(2, certChain.length); assertEquals(subcaDN, certChain[0].getX509v3PKCert().getSubject().toString()); assertEquals(ISSUER_DN, certChain[1].getX509v3PKCert().getSubject().toString()); } finally { try { this.endEntityManagementSession.deleteUser(ADMIN, username); } catch (NotFoundException e) { // A test probably failed before creating the entity log.debug("Failed to delete user: " + username); } CryptoTokenTestUtils.removeCryptoToken(null, cryptoTokenId); // Remove CA certificate of CA that we will remove Collection<Certificate> certs = this.caSession.getCAInfo(ADMIN, subcaID).getCertificateChain(); this.internalCertStoreSession.removeCertificate(certs.iterator().next()); // Remove the CA itself this.caSession.removeCA(ADMIN, subcaID); } }
From source file:org.ejbca.core.protocol.cmp.CrmfRequestTest.java
License:Open Source License
private X500Name createCmpUser(String username, String dn, boolean useDnOverride) throws AuthorizationDeniedException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, EjbcaException, FinderException, CADoesntExistsException { // Make USER that we know... boolean userExists = false; final int cpID; final int eepID; final X500Name userDN; if (useDnOverride) { cpID = this.cpDnOverrideId; eepID = this.eepDnOverrideId; userDN = new X500Name(dn); } else {/*from www . j a va 2 s .c om*/ cpID = CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER; eepID = SecConst.EMPTY_ENDENTITYPROFILE; userDN = new X500Name(StringTools.strip(CertTools.stringToBCDNString(dn))); } final EndEntityInformation user = new EndEntityInformation(username, dn, this.caid, null, username + "@primekey.se", new EndEntityType(EndEntityTypes.ENDUSER), eepID, cpID, SecConst.TOKEN_SOFT_PEM, 0, null); user.setPassword("foo123"); log.debug("Trying to add/edit USER: " + user.getUsername() + ", foo123, " + userDN); try { this.endEntityManagementSession.addUser(ADMIN, user, true); } catch (Exception e) { userExists = true; } if (userExists) { log.debug("USER already exists: " + user.getUsername() + ", foo123, " + userDN); this.endEntityManagementSession.changeUser(ADMIN, user, true); this.endEntityManagementSession.setUserStatus(ADMIN, user.getUsername(), EndEntityConstants.STATUS_NEW); log.debug("Reset status to NEW"); } return userDN; }
From source file:org.ejbca.core.protocol.cmp.EndEntityCertAuthModuleTest.java
License:Open Source License
/** * 1- Sends a CRMF request signed by RA1Admin to RA1. Expected: Success * 2- Sends a CRMF request signed by RA2Admin to RA2. Expected: Success * //from ww w . jav a 2s .c o m * @throws Exception */ @Test public void test01RA1SuccessfullCRMF() throws Exception { // Send CRMF message signed by RA1Admin to RA1 String testUsername = "ra1testuser"; String fingerprintCert = null; try { final X500Name testUserDN = new X500Name("CN=" + testUsername); KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genCertReq(ca1.getSubjectDN(), testUserDN, keys, ca1.getCACertificate(), nonce, transid, false, null, null, null, null, pAlg, new DEROctetString(nonce)); assertNotNull("Generating CrmfRequest failed.", msg); CMPCertificate[] extraCert = getCMPCert(ra1admincert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra1adminkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull("Signing CMP message failed", msg); //******************************************'''''' final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(ra1admincert.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(msg)); boolean verified = sig.verify(msg.getProtection().getBytes()); assertTrue("Signing the message failed.", verified); //*************************************************** final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(msg); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, RA1_ALIAS); checkCmpResponseGeneral(resp, ca1.getSubjectDN(), testUserDN, ca1.getCACertificate(), msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); CertReqMessages ir = (CertReqMessages) msg.getBody().getContent(); Certificate cert = checkCmpCertRepMessage(testUserDN, (X509Certificate) ca1.getCACertificate(), resp, ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue()); assertNotNull("CrmfRequest did not return a certificate", cert); fingerprintCert = CertTools.getFingerprintAsString(cert); } finally { internalCertStoreSession.removeCertificate(fingerprintCert); endEntityManagementSession.revokeAndDeleteUser(ADMIN, testUsername, ReasonFlags.unused); } // Send CRMF message signed by RA2Admin to RA2 testUsername = "ra2testuser"; try { final X500Name testUserDN = new X500Name("CN=" + testUsername); KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genCertReq(ca2.getSubjectDN(), testUserDN, keys, ca2.getCACertificate(), nonce, transid, false, null, null, null, null, pAlg, new DEROctetString(nonce)); assertNotNull("Generating CrmfRequest failed.", msg); CMPCertificate[] extraCert = getCMPCert(ra2admincert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra2adminkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull("Signing CMP message failed.", msg); //******************************************'''''' final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(ra2admincert.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(msg)); boolean verified = sig.verify(msg.getProtection().getBytes()); assertTrue("Signing the message failed.", verified); //*************************************************** final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(msg); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, RA2_ALIAS); checkCmpResponseGeneral(resp, ca2.getSubjectDN(), testUserDN, ca2.getCACertificate(), msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); CertReqMessages ir = (CertReqMessages) msg.getBody().getContent(); Certificate cert = checkCmpCertRepMessage(testUserDN, (X509Certificate) ca2.getCACertificate(), resp, ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue()); assertNotNull("CrmfRequest did not return a certificate", cert); fingerprintCert = CertTools.getFingerprintAsString(cert); } finally { internalCertStoreSession.removeCertificate(fingerprintCert); endEntityManagementSession.revokeAndDeleteUser(ADMIN, testUsername, ReasonFlags.unused); } }
From source file:org.ejbca.core.protocol.cmp.EndEntityCertAuthModuleTest.java
License:Open Source License
/** * 1- Sends a CRMF request signed by RA2Admin to RA1. Expected: Fail * 2- Sends a CRMF request signed by RA1Admin to RA2. Expected: Fail * //from w w w . ja v a2s .com * @throws Exception */ @Test public void test01RA1FailedCRMF() throws Exception { // Send CRMF message signed by RA2Admin to RA1 String testUsername = "ra1testuser"; X500Name testUserDN = new X500Name("CN=" + testUsername); KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genCertReq(ca1.getSubjectDN(), testUserDN, keys, ca1.getCACertificate(), nonce, transid, false, null, null, null, null, pAlg, new DEROctetString(nonce)); assertNotNull("Generating CrmfRequest failed.", msg); CMPCertificate[] extraCert = getCMPCert(ra2admincert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra2adminkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull("Signing CMP message failed.", msg); //******************************************'''''' Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(ra2admincert.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(msg)); boolean verified = sig.verify(msg.getProtection().getBytes()); assertTrue("Signing the message failed.", verified); //*************************************************** ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(msg); byte[] ba = bao.toByteArray(); // Send request and receive response byte[] resp = sendCmpHttp(ba, 200, RA1_ALIAS); checkCmpResponseGeneral(resp, ca1.getSubjectDN(), testUserDN, ca1.getCACertificate(), msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false, null, null); ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); PKIMessage respObject = null; try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull("Reading CMP response failed.", respObject); PKIBody body = respObject.getBody(); assertEquals(PKIBody.TYPE_ERROR, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); String expectedErrMsg = "'CN=" + RA2_ADMIN + "' is not an authorized administrator."; assertEquals(expectedErrMsg, errMsg); // Send CRMF message signed by RA1Admin to RA2 testUsername = "ra2testuser"; testUserDN = new X500Name("CN=" + testUsername); keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); msg = genCertReq(ca2.getSubjectDN(), testUserDN, keys, ca2.getCACertificate(), nonce, transid, false, null, null, null, null, pAlg, new DEROctetString(nonce)); assertNotNull("Generating CrmfRequest failed.", msg); extraCert = getCMPCert(ra1admincert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra1adminkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull("Signing CMP message failed.", msg); //******************************************'''''' sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(ra1admincert.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(msg)); verified = sig.verify(msg.getProtection().getBytes()); assertTrue("Signing the message failed.", verified); //*************************************************** bao = new ByteArrayOutputStream(); out = new DEROutputStream(bao); out.writeObject(msg); ba = bao.toByteArray(); // Send request and receive response resp = sendCmpHttp(ba, 200, RA2_ALIAS); checkCmpResponseGeneral(resp, ca2.getSubjectDN(), testUserDN, ca2.getCACertificate(), msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false, null, null); asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull("Reading CMP response failed.", respObject); body = respObject.getBody(); assertEquals(PKIBody.TYPE_ERROR, body.getType()); err = (ErrorMsgContent) body.getContent(); errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); expectedErrMsg = "'CN=" + RA1_ADMIN + "' is not an authorized administrator."; assertEquals(expectedErrMsg, errMsg); }
From source file:org.ejbca.core.protocol.cmp.EndEntityCertAuthModuleTest.java
License:Open Source License
/** * 1- Sends a revocation request signed by RA2Admin to RA1. Expected: Fail * 2- Sends a revocation request signed by RA1Admin to RA1. Expected: Success * /*from ww w .j a v a 2s . c om*/ * @throws Exception */ @Test public void test03RevocationRequest() throws Exception { String username = "ra1testuser"; String fingerprintCert = null; try { // Issue a cert by CA1 String userDN = "CN=" + username; createUser(username, userDN, "foo123", true, ca1.getCAId(), endEntityProfileSession.getEndEntityProfileId(EEP1), certProfileSession.getCertificateProfileId(CP1)); KeyPair userkeys = KeyTools.genKeys("1024", "RSA"); Certificate cert = signSession.createCertificate(ADMIN, username, "foo123", new PublicKeyWrapper(userkeys.getPublic())); assertNotNull("No certificate to revoke.", cert); fingerprintCert = CertTools.getFingerprintAsString(cert); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genRevReq(ca1.getSubjectDN(), new X500Name(userDN), CertTools.getSerialNumber(cert), ca1.getCACertificate(), nonce, transid, false, pAlg, null); assertNotNull("Generating revocation request failed.", msg); // Sign the revocation request with RA2 Admin CMPCertificate[] extraCert = getCMPCert(ra2admincert); PKIMessage protectedMsg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra2adminkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull("Signing CMP message failed.", protectedMsg); // Send the CMP request to RA1. Expected: Fail ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(protectedMsg); byte[] ba = bao.toByteArray(); byte[] resp = sendCmpHttp(ba, 200, RA1_ALIAS); checkCmpResponseGeneral(resp, ca1.getSubjectDN(), new X500Name(userDN), ca1.getCACertificate(), msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false, null, null); ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); final PKIMessage respObject; try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull("Reading CMP response failed.", respObject); PKIBody body = respObject.getBody(); assertEquals(PKIBody.TYPE_ERROR, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); String expectedErrMsg = "'CN=" + RA2_ADMIN + "' is not an authorized administrator."; assertEquals(expectedErrMsg, errMsg); // Sign the revocation request with RA1 Admin extraCert = getCMPCert(ra1admincert); protectedMsg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra1adminkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull("Signing CMP message failed.", protectedMsg); // Send the CMP request to RA1. Expected: Success bao = new ByteArrayOutputStream(); out = new DEROutputStream(bao); out.writeObject(protectedMsg); ba = bao.toByteArray(); resp = sendCmpHttp(ba, 200, RA1_ALIAS); checkCmpResponseGeneral(resp, ca1.getSubjectDN(), new X500Name(userDN), ca1.getCACertificate(), msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); int revStatus = checkRevokeStatus(ca1.getSubjectDN(), CertTools.getSerialNumber(cert)); assertNotEquals("Revocation request failed to revoke the certificate", RevokedCertInfo.NOT_REVOKED, revStatus); } finally { internalCertStoreSession.removeCertificate(fingerprintCert); endEntityManagementSession.revokeAndDeleteUser(ADMIN, username, ReasonFlags.unused); } }
From source file:org.ejbca.core.protocol.cmp.EndEntityCertAuthModuleTest.java
License:Open Source License
/** * Sends a revocation request signed by RA2Admin to revoke a certificate issued by a CA RA2Admin is not authorized to. Expected: Fail * /*from www. j av a 2 s . co m*/ * @throws Exception */ @Test public void test04RevocationRequest() throws Exception { String username = "ra1testuser"; String fingerprintCert = null; try { // Issue a cert by CA1 String userDN = "CN=" + username; createUser(username, userDN, "foo123", true, ca1.getCAId(), endEntityProfileSession.getEndEntityProfileId(EEP1), certProfileSession.getCertificateProfileId(CP1)); KeyPair userkeys = KeyTools.genKeys("1024", "RSA"); Certificate cert = signSession.createCertificate(ADMIN, username, "foo123", new PublicKeyWrapper(userkeys.getPublic())); assertNotNull("No certificate to revoke.", cert); fingerprintCert = CertTools.getFingerprintAsString(cert); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genRevReq(ca1.getSubjectDN(), new X500Name(userDN), CertTools.getSerialNumber(cert), ca1.getCACertificate(), nonce, transid, false, pAlg, null); assertNotNull("Generating revocation request failed.", msg); // Sign the revocation request with RA2 Admin CMPCertificate[] extraCert = getCMPCert(ra2admincert); PKIMessage protectedMsg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra2adminkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull("Signing CMP message failed", protectedMsg); // Send the CMP request to RA2. Expected: Fail ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(protectedMsg); byte[] ba = bao.toByteArray(); byte[] resp = sendCmpHttp(ba, 200, RA2_ALIAS); checkCmpResponseGeneral(resp, ca1.getSubjectDN(), new X500Name(userDN), ca1.getCACertificate(), msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false, null, null); ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); final PKIMessage respObject; try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull("Reading CMP response failed.", respObject); PKIBody body = respObject.getBody(); assertEquals(PKIBody.TYPE_ERROR, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); String expectedErrMsg = "'CN=" + RA2_ADMIN + "' is not an authorized administrator."; assertEquals(expectedErrMsg, errMsg); } finally { internalCertStoreSession.removeCertificate(fingerprintCert); endEntityManagementSession.revokeAndDeleteUser(ADMIN, username, ReasonFlags.unused); } }
From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java
License:Open Source License
@Test public void test01CrmfReq() throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException, EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception { //-----------------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);//ww w.java 2 s. c om 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)); String adminName = "cmpTestAdmin"; KeyPair admkeys = KeyTools.genKeys("1024", "RSA"); AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE"); Certificate admCert = getCertFromCredentials(adminToken); CMPCertificate[] cmpcert = getCMPCert(admCert); crmfMsg = CmpMessageHelper.buildCertBasedPKIProtection(crmfMsg, cmpcert, admkeys.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"); assertEquals( "RACertPath is suppose to be '" + this.raCertsPath + "', instead it is '" + this.cmpConfiguration.getRACertPath(cmpAlias) + "'.", this.cmpConfiguration.getRACertPath(cmpAlias), this.raCertsPath); 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); // 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); assertTrue(cert instanceof X509Certificate); log.debug("Subject DN of created certificate: " + X500Name.getInstance(((X509Certificate) cert).getSubjectX500Principal().getEncoded())); assertNotNull("CrmfRequest did not return a certificate", cert); removeAuthenticationToken(adminToken, admCert, adminName); }
From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java
License:Open Source License
@Test public void test02Verify() throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException, EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, 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);/*from w ww .j av a 2s. 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 ---------------------- 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)); //myPKIHeader.addGeneralInfo(new InfoTypeAndValue(ASN1Sequence.getInstance(crmfMsg))); PKIBody myPKIBody = new PKIBody(20, crmfMsg); // NestedMessageContent PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); KeyPair raKeys = KeyTools.genKeys("1024", "RSA"); createRACertificate("raSignerVerify", "foo123", this.raCertsPath, cmpAlias, raKeys, null, null, CMPTESTPROFILE, this.caid); 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); NestedMessageContent nestedMsg = new NestedMessageContent(myPKIMessage, cmpAlias, this.globalConfigurationSession); boolean verify = nestedMsg.verify(); assertTrue("NestedMessageVerification failed.", verify); }
From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java
License:Open Source License
@Test public void test03RevReq() throws NoSuchAlgorithmException, AuthorizationDeniedException, EjbcaException, IOException, InvalidAlgorithmParameterException, RoleNotFoundException, InvalidKeyException, NoSuchProviderException, SecurityException, SignatureException, ObjectNotFoundException, CertificateException, CADoesntExistsException, IllegalKeyException, CertificateCreateException, IllegalNameException, CertificateRevokeException, CertificateSerialNumberException, CryptoTokenOfflineException, IllegalValidityException, CAOfflineException, InvalidAlgorithmException, CustomCertificateSerialNumberException, UserDoesntFullfillEndEntityProfile, RemoveException, WaitingForApprovalException, FinderException { Collection<Certificate> certs = this.certificateStoreSession .findCertificatesBySubjectAndIssuer(SUBJECT_DN.toString(), this.issuerDN); log.debug("Found " + certs.size() + " certificates for userDN \"" + SUBJECT_DN + "\""); Certificate cert = null;//from w w w . j av a 2 s.c o m for (Certificate tmp : certs) { if (!this.certificateStoreSession.isRevoked(this.issuerDN, CertTools.getSerialNumber(tmp))) { cert = tmp; break; } } assertNotNull("Could not find a suitable certificate to revoke.", cert); //----------- creating the revocation signed request------------------- final byte[] nonce = CmpMessageHelper.createSenderNonce(); final byte[] transid = CmpMessageHelper.createSenderNonce(); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage revMsg = genRevReq(this.issuerDN, SUBJECT_DN, CertTools.getSerialNumber(cert), this.cacert, nonce, transid, false, pAlg, new DEROctetString(nonce)); assertNotNull("Generating CrmfRequest failed." + revMsg); String adminName = "cmpTestAdmin"; KeyPair admkeys = KeyTools.genKeys("1024", "RSA"); AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE"); Certificate admCert = getCertFromCredentials(adminToken); CMPCertificate[] cmpcert = getCMPCert(admCert); revMsg = CmpMessageHelper.buildCertBasedPKIProtection(revMsg, cmpcert, admkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(revMsg); //----------------- Creating the nested PKIMessage ----------------------- String reqSubjectDN = "CN=bogusSubjectNested"; final byte[] reqNonce = CmpMessageHelper.createSenderNonce(); final byte[] reqTransid = 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(reqNonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(reqTransid)); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(revMsg); DERSequence seq = new DERSequence(v); PKIBody myPKIBody = new PKIBody(20, seq); // NestedMessageContent PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); KeyPair raKeys = KeyTools.genKeys("1024", "RSA"); createRACertificate("raRevSigner", "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); checkCmpResponseGeneral(resp, this.issuerDN, SUBJECT_DN, this.cacert, nonce, transid, false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); int revStatus = checkRevokeStatus(this.issuerDN, CertTools.getSerialNumber(cert)); assertNotEquals("Revocation request failed to revoke the certificate", Integer.valueOf(RevokedCertInfo.NOT_REVOKED), Integer.valueOf(revStatus)); removeAuthenticationToken(adminToken, admCert, adminName); }
From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java
License:Open Source License
@Test public void test04CrmfRACertExist() throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException, EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, 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);//ww w . jav a 2s . c om assertNotNull(na); KeyPair keys = null; keys = KeyTools.genKeys("1024", "RSA"); PKIMessage crmfReqMsg = genCertReq(this.issuerDN, SUBJECT_DN, keys, this.cacert, senderNonce, transactionID, false, null, nb, na, null, null, null); assertNotNull("Failed to create crmfMsg.", crmfReqMsg); PKIMessage crmfMsg = protectPKIMessage(crmfReqMsg, false, "foo123", 567); CertReqMessages ir = (CertReqMessages) crmfMsg.getBody().getContent(); int reqID = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); // ---------------- Creating the NestedMessageContent ---------------------- 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)); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(crmfMsg); DERSequence seq = new DERSequence(v); PKIBody myPKIBody = new PKIBody(20, seq); // NestedMessageContent PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); KeyPair raKeys = KeyTools.genKeys("1024", "RSA"); createRACertificate("raSignerTest04", "foo123", this.raCertsPath, cmpAlias, raKeys, null, null, CMPTESTPROFILE, this.caid); 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, 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())); NestedMessageContent nestedContent = new NestedMessageContent(myPKIMessage, cmpAlias, this.globalConfigurationSession); boolean ret = nestedContent.verify(); assertTrue("The message verification failed, yet the a certificate was returned.", ret); }