List of usage examples for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream
public ASN1InputStream(byte[] input)
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 w ww . j a v a 2s . c o 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 w w w . j a v a 2s .c o 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 {/*w w w.j av a 2s . co 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 w w w . j av a2 s . c o 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 * /* ww w . j ava 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 va 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 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);//from www .j av a2s .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())); // 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 va2 s . co m 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);//from w ww . j ava2s.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); 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 a 2s . co 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); 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()"); }