List of usage examples for org.bouncycastle.asn1 ASN1InputStream readObject
public ASN1Primitive readObject() throws IOException
From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessageTest.java
License:Open Source License
private PKIMessage createPKIMessage(final String issuerDN, final String subjectDN) throws InvalidAlgorithmParameterException, IOException { KeyPair keys = KeyTools.genKeys("1024", "RSA"); 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)); CertTemplateBuilder myCertTemplate = new CertTemplateBuilder(); myCertTemplate.setValidity(myOptionalValidity); myCertTemplate.setIssuer(new X500Name(issuerDN)); myCertTemplate.setSubject(new X500Name(subjectDN)); byte[] bytes = keys.getPublic().getEncoded(); ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); ASN1InputStream dIn = new ASN1InputStream(bIn); try {/*from w w w . j av a 2 s.co m*/ SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject()); myCertTemplate.setPublicKey(keyInfo); } finally { dIn.close(); } ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); ExtensionsGenerator extgen = new ExtensionsGenerator(); int 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)); myCertTemplate.setExtensions(extgen.generate()); 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(new X500Name("CN=bogusSubject")), new GeneralName(new X500Name("CN=bogusIssuer"))); myPKIHeader.setMessageTime(new DERGeneralizedTime(new Date())); myPKIHeader.setSenderNonce(new DEROctetString(CmpMessageHelper.createSenderNonce())); myPKIHeader.setTransactionID(new DEROctetString(CmpMessageHelper.createSenderNonce())); PKIBody myPKIBody = new PKIBody(0, myCertReqMessages); PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); return myPKIMessage; }
From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessageTest.java
License:Open Source License
@Test public void testNovosecRARequest() throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException, CertificateEncodingException, SignatureException, IllegalStateException { // Check that we can parse a request from Novosec (patched by EJBCA). // Read an initialization request with RAVerifiedPOP and PBE protection to see that we can process it ASN1InputStream in = new ASN1InputStream(novosecrapopir); try {//from www . jav a2s .c om ASN1Primitive derObject = in.readObject(); PKIMessage req = PKIMessage.getInstance(derObject); //log.info(req.toString()); // Verify should be false if we do not allow RA verify POP here, since we don't have any normal POP CrmfRequestMessage msg = new CrmfRequestMessage(req, "CN=AdminCA1", false, "CN"); assertFalse(msg.verify()); // Verify should be ok when we allow RA verified POP msg = new CrmfRequestMessage(req, "CN=AdminCA1", true, "CN"); assertTrue(msg.verify()); assertEquals("CN=AdminCA1,O=EJBCA Sample,C=SE", msg.getIssuerDN()); assertEquals("CN=abc123rry-4371939543913639881,O=PrimeKey Solutions AB,C=SE", msg.getRequestDN()); assertEquals("abc123rry-4371939543913639881", msg.getUsername()); assertEquals("foo123", msg.getPassword()); // Verify PBE protection PKIHeader head = msg.getHeader(); final ASN1OctetString os = head.getSenderKID(); String keyId = CmpMessageHelper.getStringFromOctets(os); assertEquals("mykeyid", keyId); final CmpPbeVerifyer verifyer = new CmpPbeVerifyer(msg.getMessage()); assertTrue(verifyer.verify("foo123")); assertFalse(verifyer.verify("bar123")); } finally { in.close(); } }
From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessageTest.java
License:Open Source License
private void doNovosecClientRequest(final String sigAlg, final String digestAlg, final String expectedAlgOid) throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException, SignatureException, IllegalStateException, OperatorCreationException, CertificateException { // Check that we can parse a request from Novosec (patched by EJBCA). // Read an initialization request with a signature POP and signature protection to see that we can process it {//from ww w . j a va 2 s . c o m ASN1InputStream in = new ASN1InputStream(novosecsigpopir); try { ASN1Primitive derObject = in.readObject(); PKIMessage req = PKIMessage.getInstance(derObject); //log.info(req.toString()); // Verify should be ok if we do not allow RA verify POP here CrmfRequestMessage msg = new CrmfRequestMessage(req, "CN=AdminCA1", false, "CN"); assertTrue(msg.verify()); // Since we don't have RA POP we can't test for that... assertEquals("CN=AdminCA1,O=EJBCA Sample,C=SE", msg.getIssuerDN()); assertEquals("CN=abc123rry2942812801980668853,O=PrimeKey Solutions AB,C=SE", msg.getRequestDN()); assertEquals("abc123rry2942812801980668853", msg.getUsername()); assertEquals("foo123", msg.getPassword()); // Verify signature protection AlgorithmIdentifier algId = msg.getMessage().getHeader().getProtectionAlg(); String oid = algId.getAlgorithm().getId(); assertEquals(PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(), oid); // Check that this is an old message, created before ECA-2104, using null instead of DERNull as algorithm parameters. ASN1Encodable pp = algId.getParameters(); assertNull(pp); // Try to verify, it should work good even though the small bug in ECA-2104, since we don't use algorithm parameters for RSA-PKCS signatures PublicKey pubKey = msg.getRequestPublicKey(); assertTrue(CmpMessageHelper.verifyCertBasedPKIProtection(msg.getMessage(), pubKey)); // Verify that our verification routine does not give positive result for any other keys KeyPair keys = KeyTools.genKeys("512", "RSA"); assertFalse(CmpMessageHelper.verifyCertBasedPKIProtection(msg.getMessage(), keys.getPublic())); } finally { in.close(); } } // Re-protect the message, now fixed by ECA-2104 { ASN1InputStream in = new ASN1InputStream(novosecsigpopir); try { ASN1Primitive derObject = in.readObject(); PKIMessage myPKIMessage = PKIMessage.getInstance(derObject); KeyPair keys = KeyTools.genKeys("512", "RSA"); X509Certificate signCert = CertTools.genSelfCert("CN=CMP Sign Test", 3650, null, keys.getPrivate(), keys.getPublic(), sigAlg, false); // Re-sign the message Collection<Certificate> signCertChain = new ArrayList<Certificate>(); signCertChain.add(signCert); byte[] newmsg = CmpMessageHelper.signPKIMessage(myPKIMessage, signCertChain, keys.getPrivate(), digestAlg, "BC"); in.close(); in = new ASN1InputStream(newmsg); derObject = in.readObject(); PKIMessage pkimsg = PKIMessage.getInstance(derObject); // We have to do this twice, because Novosec caches ProtectedBytes in the PKIMessage object, so we need to // encode it and re-decode it again to get the changes from ECA-2104 encoded correctly. // Not needed when simply signing a new message that you create, only when re-signing newmsg = CmpMessageHelper.signPKIMessage(pkimsg, signCertChain, keys.getPrivate(), digestAlg, "BC"); in.close(); in = new ASN1InputStream(newmsg); derObject = in.readObject(); pkimsg = PKIMessage.getInstance(derObject); AlgorithmIdentifier algId = pkimsg.getHeader().getProtectionAlg(); String oid = algId.getAlgorithm().getId(); assertEquals(expectedAlgOid, oid); // Check that we have DERNull and not plain java null as algorithm parameters. ASN1Encodable pp = algId.getParameters(); assertNotNull(pp); assertEquals(DERNull.class.getName(), pp.getClass().getName()); // Try to verify, also verify at the same time that encoding decoding of the signature works assertTrue(CmpMessageHelper.verifyCertBasedPKIProtection(pkimsg, keys.getPublic())); // Verify that our verification routine does not give positive result for any other keys CrmfRequestMessage msg = new CrmfRequestMessage(pkimsg, "CN=AdminCA1", false, "CN"); assertTrue(msg.verify()); PublicKey pubKey = msg.getRequestPublicKey(); assertFalse(CmpMessageHelper.verifyCertBasedPKIProtection(pkimsg, pubKey)); } finally { in.close(); } } }
From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessageTest.java
License:Open Source License
private void internalBcRARequestTest(byte[] message) throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException { // Check that we can parse request from BouncyCastle version 1.46. // Read an initialization request with RAVerifiedPOP with PBE protection to see that we can process it ASN1InputStream in = new ASN1InputStream(message); try {/*from www . j a v a2s . c o m*/ ASN1Primitive derObject = in.readObject(); PKIMessage req = PKIMessage.getInstance(derObject); //log.info(req.toString()); // Verify should be false if we do not allow RA verify POP here, since we don't have any normal POP CrmfRequestMessage msg = new CrmfRequestMessage(req, "CN=AdminCA1", false, "CN"); assertFalse(msg.verify()); // Verify should be ok when we allow RA verified POP msg = new CrmfRequestMessage(req, "CN=AdminCA1", true, "CN"); assertTrue(msg.verify()); assertEquals("CN=AdminCA1", msg.getIssuerDN()); assertEquals("CN=user", msg.getRequestDN()); assertEquals("user", msg.getUsername()); // We should want a password assertEquals("foo123", msg.getPassword()); // Verify PBE protection PKIHeader head = msg.getHeader(); final ASN1OctetString os = head.getSenderKID(); String keyId = CmpMessageHelper.getStringFromOctets(os); assertEquals("KeyId", keyId); final CmpPbeVerifyer verifyer = new CmpPbeVerifyer(msg.getMessage()); assertTrue(verifyer.verify("password")); assertFalse(verifyer.verify("foo123")); } finally { in.close(); } }
From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessageTest.java
License:Open Source License
private void internalBcClientRequestTest(byte[] message) throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException { // Check that we can parse request from BouncyCastle version 1.46. // Read an initialization request with a signature POP, and signature protection, to see that we can process it ASN1InputStream in = new ASN1InputStream(message); try {//from ww w . ja v a 2s. co m ASN1Primitive derObject = in.readObject(); PKIMessage req = PKIMessage.getInstance(derObject); //log.info(req.toString()); // Verify should be ok if we do not allow RA verify POP here CrmfRequestMessage msg = new CrmfRequestMessage(req, "CN=AdminCA1", false, "CN"); // BC messages in BC1.46 uses POPOSigningKeyInput for POPO, not the 3rd case in RFC4211 section 4.1, like everyone else... // BC messages in BC1.47 should use normal POPO, 3rd case assertTrue(msg.verify()); // Since we don't have RA POP we can't test for that... assertEquals("CN=AdminCA1", msg.getIssuerDN()); assertEquals("CN=user", msg.getRequestDN()); assertEquals("user", msg.getUsername()); assertEquals("foo123", msg.getPassword()); // Check signature protection AlgorithmIdentifier algId = msg.getMessage().getHeader().getProtectionAlg(); String oid = algId.getAlgorithm().getId(); assertEquals(PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(), oid); // Check that we have DERNull and not plain java null as algorithm parameters. ASN1Encodable pp = algId.getParameters(); assertNotNull(pp); assertEquals(DERNull.class.getName(), pp.getClass().getName()); // Try to verify the protection signature assertTrue(CmpMessageHelper.verifyCertBasedPKIProtection(msg.getMessage(), msg.getRequestPublicKey())); } finally { in.close(); } }
From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessageTest.java
License:Open Source License
@Test public void testHuaweiEnodeBClientRequest() throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException { // Read an initialization request to see that we can process it ASN1InputStream in = new ASN1InputStream(huaweiir); try {/*from ww w. j av a 2s. co m*/ ASN1Primitive derObject = in.readObject(); PKIMessage req = PKIMessage.getInstance(derObject); //log.info(req.toString()); CrmfRequestMessage msg = new CrmfRequestMessage(req, null, false, "CN"); // This message does not have an issuerDN in the cert template assertNull(msg.getIssuerDN()); // Use a default CA instead msg = new CrmfRequestMessage(req, "CN=AdminCA1", false, "CN"); assertTrue(msg.verify()); assertEquals("CN=AdminCA1", msg.getIssuerDN()); assertEquals("CN=21030533610000000012 eNodeB", msg.getRequestDN()); assertEquals("21030533610000000012 eNodeB", msg.getUsername()); // We would like a password here... assertNull(msg.getPassword()); AlgorithmIdentifier algId = msg.getMessage().getHeader().getProtectionAlg(); String oid = algId.getAlgorithm().getId(); assertEquals(PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(), oid); // Check that we have DERNull and not plain java null as algorithm parameters. ASN1Encodable pp = algId.getParameters(); assertNotNull(pp); assertEquals(DERNull.class.getName(), pp.getClass().getName()); // Try to verify message protection // Does not work for this Huawei message, is it signed by the same key as in the request at all? // We will wait for another huawei message to test //PublicKey pubKey = msg.getRequestPublicKey(); //assertTrue(CmpMessageHelper.verifyCertBasedPKIProtection(msg.getMessage(), pubKey)); // Read the CertConf (certificate confirmation) CMP message that the client sends to // the CA after receiving the certificate. RFC4210 section "5.3.18. Certificate Confirmation Content". in.close(); in = new ASN1InputStream(huaweicertconf); derObject = in.readObject(); PKIMessage certconf = PKIMessage.getInstance(derObject); //log.info(certconf.toString()); GeneralCmpMessage conf = new GeneralCmpMessage(certconf); algId = conf.getMessage().getHeader().getProtectionAlg(); oid = algId.getAlgorithm().getId(); assertEquals(PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(), oid); // Check that we have DERNull and not plain java null as algorithm parameters. pp = algId.getParameters(); assertNotNull(pp); assertEquals(DERNull.class.getName(), pp.getClass().getName()); // Try to verify message protection // Does not work for this Huawei message, is it signed by the same key as in the request at all? // We will wait for another huawei message to test //PublicKey pubKey = msg.getRequestPublicKey(); //assertTrue(CmpMessageHelper.verifyCertBasedPKIProtection(msg.getMessage(), pubKey)); } finally { in.close(); } }
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 w w w . ja va2s. 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.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 ww w . j a v a2 s . co m * @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 * /* ww w. ja v a 2s . c o 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); } }