List of usage examples for org.bouncycastle.asn1 ASN1InputStream readObject
public ASN1Primitive readObject() throws IOException
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 w ww . jav a 2s. c om*/ assertNotNull(na); KeyPair keys = null; keys = KeyTools.genKeys("1024", "RSA"); PKIMessage crmfMsg = genCertReq(this.issuerDN, SUBJECT_DN, keys, this.cacert, senderNonce, transactionID, false, null, nb, na, null, null, null); assertNotNull("Failed to create crmfMsg.", crmfMsg); // ---------------- Creating the NestedMessageContent ---------------------- String reqSubjectDN = "CN=bogusSubjectNested"; final byte[] nonce = CmpMessageHelper.createSenderNonce(); final byte[] transid = CmpMessageHelper.createSenderNonce(); PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(new X500Name(reqSubjectDN)), new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName()))); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // nonce DEROctetString dernonce = new DEROctetString(nonce); myPKIHeader.setSenderNonce(dernonce); myPKIHeader.setRecipNonce(dernonce); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); PKIBody myPKIBody = new PKIBody(20, crmfMsg); // NestedMessageContent PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); KeyPair raKeys = KeyTools.genKeys("1024", "RSA"); // Don't create a certificate, so there is no RA cert authorized on the server side. myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(), null, "BC"); assertNotNull("Failed to create myPKIHeader", myPKIHeader); assertNotNull("myPKIBody is null", myPKIBody); assertNotNull("myPKIMessage is null", myPKIMessage); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(myPKIMessage); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, cmpAlias); PKIMessage respObject = null; ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); PKIBody body = respObject.getBody(); assertEquals(23, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); assertEquals("Wrong error message", "Could not verify the RA, signature verification on NestedMessageContent failed.", errMsg); NestedMessageContent nestedContent = new NestedMessageContent(myPKIMessage, cmpAlias, this.globalConfigurationSession); boolean ret = nestedContent.verify(); assertFalse("The message verification failed, yet the a certificate was returned.", ret); }
From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java
License:Open Source License
@Test public void test06NotNestedMessage() throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException, EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception { ASN1EncodableVector optionaValidityV = new ASN1EncodableVector(); org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time( new DERGeneralizedTime("20030211002120Z")); org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date()); optionaValidityV.add(new DERTaggedObject(true, 0, nb)); optionaValidityV.add(new DERTaggedObject(true, 1, na)); OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionaValidityV)); KeyPair keys = KeyTools.genKeys("1024", "RSA"); CertTemplateBuilder myCertTemplate = new CertTemplateBuilder(); myCertTemplate.setValidity(myOptionalValidity); myCertTemplate.setIssuer(new X500Name(this.issuerDN)); myCertTemplate.setSubject(SUBJECT_DN); byte[] bytes = keys.getPublic().getEncoded(); ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); ASN1InputStream dIn = new ASN1InputStream(bIn); try {/* w w w. j av a2 s .c om*/ 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);/*w w w .ja v a 2 s. 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);/* www. j av a2s . 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()"); }
From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java
License:Open Source License
private static CMPCertificate[] getCMPCert(Certificate cert) throws CertificateEncodingException, IOException { ASN1InputStream ins = new ASN1InputStream(cert.getEncoded()); try {/*from w w w .j av a 2s . c om*/ ASN1Primitive pcert = ins.readObject(); org.bouncycastle.asn1.x509.Certificate c = org.bouncycastle.asn1.x509.Certificate .getInstance(pcert.toASN1Primitive()); CMPCertificate[] res = { new CMPCertificate(c) }; return res; } finally { ins.close(); } }
From source file:org.ejbca.core.protocol.cmp.RevocationMessageHandler.java
License:Open Source License
public ResponseMessage handleMessage(final BaseCmpMessage msg, boolean authenticated) { if (LOG.isTraceEnabled()) { LOG.trace(">handleMessage"); }/* w ww . j a v a 2 s . com*/ CA ca = null; try { final String caDN = msg.getHeader().getRecipient().getName().toString(); final int caId = CertTools.stringToBCDNString(caDN).hashCode(); if (LOG.isDebugEnabled()) { LOG.debug("CA DN is '" + caDN + "' and resulting caId is " + caId + ", after CertTools.stringToBCDNString conversion."); } ca = caSession.getCA(admin, caId); } catch (CADoesntExistsException e) { final String errMsg = "CA with DN '" + msg.getHeader().getRecipient().getName().toString() + "' is unknown"; LOG.info(errMsg); return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST, errMsg); } catch (AuthorizationDeniedException e) { LOG.info(INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage()), e); return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.INCORRECT_DATA, e.getMessage()); } ResponseMessage resp = null; // if version == 1 it is cmp1999 and we should not return a message back // Try to find a HMAC/SHA1 protection key final String keyId = CmpMessageHelper.getStringFromOctets(msg.getHeader().getSenderKID()); ResponseStatus status = ResponseStatus.FAILURE; FailInfo failInfo = FailInfo.BAD_MESSAGE_CHECK; String failText = null; //Verify the authenticity of the message final VerifyPKIMessage messageVerifyer = new VerifyPKIMessage(ca.getCAInfo(), this.confAlias, admin, caSession, endEntityAccessSession, certificateStoreSession, authorizationSession, endEntityProfileSession, authenticationProviderSession, endEntityManagementSession, this.cmpConfiguration); ICMPAuthenticationModule authenticationModule = messageVerifyer .getUsedAuthenticationModule(msg.getMessage(), null, authenticated); if (authenticationModule == null) { LOG.info(messageVerifyer.getErrorMessage()); return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_MESSAGE_CHECK, messageVerifyer.getErrorMessage()); } // If authentication was correct, we will now try to find the certificate to revoke final PKIMessage pkimsg = msg.getMessage(); final PKIBody body = pkimsg.getBody(); final RevReqContent rr = (RevReqContent) body.getContent(); RevDetails rd; try { rd = rr.toRevDetailsArray()[0]; } catch (Exception e) { LOG.debug("Could not parse the revocation request. Trying to parse it as novosec generated message."); rd = CmpMessageHelper.getNovosecRevDetails(rr); LOG.debug("Succeeded in parsing the novosec generated request."); } final CertTemplate ct = rd.getCertDetails(); final ASN1Integer serno = ct.getSerialNumber(); final X500Name issuer = ct.getIssuer(); // Get the revocation reason. // For CMPv1 this can be a simple DERBitString or it can be a requested CRL Entry Extension // If there exists CRL Entry Extensions we will use that, because it's the only thing allowed in CMPv2 int reason = RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED; final ASN1OctetString reasonoctets = rd.getCrlEntryDetails().getExtension(Extension.reasonCode) .getExtnValue(); DERBitString reasonbits; try { reasonbits = new DERBitString(reasonoctets.getEncoded()); } catch (IOException e1) { LOG.info(INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e1.getMessage()), e1); return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.INCORRECT_DATA, e1.getMessage()); } if (reasonbits != null) { reason = CertTools.bitStringToRevokedCertInfo(reasonbits); if (LOG.isDebugEnabled()) { LOG.debug("CMPv1 revocation reason: " + reason); } } final Extensions crlExt = rd.getCrlEntryDetails(); if (crlExt != null) { final Extension ext = crlExt.getExtension(Extension.reasonCode); if (ext != null) { try { final ASN1InputStream ai = new ASN1InputStream(ext.getExtnValue().getOctets()); final ASN1Primitive obj = ai.readObject(); final ASN1Enumerated crlreason = ASN1Enumerated.getInstance(obj); // RevokedCertInfo.REVOCATION_REASON_AACOMPROMISE are the same integer values as the CRL reason extension code reason = crlreason.getValue().intValue(); if (LOG.isDebugEnabled()) { LOG.debug("CRLReason extension: " + reason); } ai.close(); } catch (IOException e) { LOG.info("Exception parsin CRL reason extension: ", e); } } else { if (LOG.isDebugEnabled()) { LOG.debug("No CRL reason code extension present."); } } } else { if (LOG.isDebugEnabled()) { LOG.debug("No CRL entry extensions present"); } } if ((serno != null) && (issuer != null)) { final String iMsg = INTRES.getLocalizedMessage("cmp.receivedrevreq", issuer.toString(), serno.getValue().toString(16)); LOG.info(iMsg); try { endEntityManagementSession.revokeCert(admin, serno.getValue(), issuer.toString(), reason); status = ResponseStatus.SUCCESS; } catch (AuthorizationDeniedException e) { failInfo = FailInfo.NOT_AUTHORIZED; final String errMsg = INTRES.getLocalizedMessage("cmp.errornotauthrevoke", issuer.toString(), serno.getValue().toString(16)); failText = errMsg; LOG.info(failText); } catch (FinderException e) { failInfo = FailInfo.BAD_CERTIFICATE_ID; final String errMsg = INTRES.getLocalizedMessage("cmp.errorcertnofound", issuer.toString(), serno.getValue().toString(16)); failText = errMsg; // This is already info logged in endEntityManagementSession.revokeCert // LOG.info(failText); } catch (WaitingForApprovalException e) { status = ResponseStatus.GRANTED_WITH_MODS; } catch (ApprovalException e) { failInfo = FailInfo.BAD_REQUEST; final String errMsg = INTRES.getLocalizedMessage("cmp.erroralreadyrequested"); failText = errMsg; LOG.info(failText); } catch (AlreadyRevokedException e) { failInfo = FailInfo.BAD_REQUEST; final String errMsg = INTRES.getLocalizedMessage("cmp.erroralreadyrevoked"); failText = errMsg; // This is already info logged in endEntityManagementSession.revokeCert // LOG.info(failText); } } else { failInfo = FailInfo.BAD_CERTIFICATE_ID; final String errMsg = INTRES.getLocalizedMessage("cmp.errormissingissuerrevoke", issuer.toString(), serno.getValue().toString(16)); failText = errMsg; LOG.info(failText); } if (LOG.isDebugEnabled()) { LOG.debug("Creating a PKI revocation message response"); } final CmpRevokeResponseMessage rresp = new CmpRevokeResponseMessage(); rresp.setRecipientNonce(msg.getSenderNonce()); rresp.setSenderNonce(new String(Base64.encode(CmpMessageHelper.createSenderNonce()))); rresp.setSender(msg.getRecipient()); rresp.setRecipient(msg.getSender()); rresp.setTransactionId(msg.getTransactionId()); rresp.setFailInfo(failInfo); rresp.setFailText(failText); rresp.setStatus(status); if (StringUtils.equals(responseProtection, "pbe")) { final HMACAuthenticationModule hmacmodule = (HMACAuthenticationModule) authenticationModule; final String owfAlg = hmacmodule.getCmpPbeVerifyer().getOwfOid(); final String macAlg = hmacmodule.getCmpPbeVerifyer().getMacOid(); final int iterationCount = 1024; final String cmpRaAuthSecret = hmacmodule.getAuthenticationString(); if ((owfAlg != null) && (macAlg != null) && (keyId != null) && (cmpRaAuthSecret != null)) { // Set all protection parameters if (LOG.isDebugEnabled()) { LOG.debug(responseProtection + ", " + owfAlg + ", " + macAlg + ", " + keyId + ", " + cmpRaAuthSecret); } rresp.setPbeParameters(keyId, cmpRaAuthSecret, owfAlg, macAlg, iterationCount); } } else if (StringUtils.equals(responseProtection, "signature")) { try { final CryptoToken cryptoToken = cryptoTokenSession .getCryptoToken(ca.getCAToken().getCryptoTokenId()); final String aliasCertSign = ca.getCAToken() .getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN); rresp.setSignKeyInfo(ca.getCertificateChain(), cryptoToken.getPrivateKey(aliasCertSign), cryptoToken.getSignProviderName()); if (msg.getHeader().getProtectionAlg() != null) { rresp.setPreferredDigestAlg(AlgorithmTools .getDigestFromSigAlg(msg.getHeader().getProtectionAlg().getAlgorithm().getId())); } } catch (CryptoTokenOfflineException e) { LOG.error(e.getLocalizedMessage(), e); } } resp = rresp; try { resp.create(); } catch (InvalidKeyException e) { String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral"); LOG.error(errMsg, e); } catch (NoSuchAlgorithmException e) { String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral"); LOG.error(errMsg, e); } catch (NoSuchProviderException e) { String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral"); LOG.error(errMsg, e); } catch (CertificateEncodingException e) { String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral"); LOG.error(errMsg, e); } catch (CRLException e) { String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral"); LOG.error(errMsg, e); } return resp; }
From source file:org.ejbca.core.protocol.MSPKCS10RequestMessage.java
License:Open Source License
/** * Returns the name of the Certificate Template or null if not available or not known. *///from w w w. j ava 2s.c o m public String getMSRequestInfoTemplateName() { if (pkcs10 == null) { log.error("PKCS10 not inited!"); return null; } // Get attributes Attribute[] attributes = pkcs10.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); if (attributes.length == 0) { log.error("Cannot find request extension."); return null; } ASN1Set set = attributes[0].getAttrValues(); DERSequence seq = (DERSequence) DERSequence.getInstance(set.getObjectAt(0)); Enumeration<?> enumeration = seq.getObjects(); while (enumeration.hasMoreElements()) { DERSequence seq2 = (DERSequence) DERSequence.getInstance(enumeration.nextElement()); ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) seq2.getObjectAt(0); if (szOID_ENROLL_CERTTYPE_EXTENSION.equals(oid.getId())) { try { DEROctetString dos = (DEROctetString) seq2.getObjectAt(1); ASN1InputStream dosAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(dos.getOctets())); try { ASN1String derobj = (ASN1String) dosAsn1InputStream.readObject(); return derobj.getString(); } finally { dosAsn1InputStream.close(); } } catch (IOException e) { log.error(e); } } } return null; }
From source file:org.ejbca.core.protocol.MSPKCS10RequestMessage.java
License:Open Source License
/** * Returns a String vector with known subject altnames: * [0] Requested GUID//from w w w .ja v a 2 s . co m * [1] Requested DNS */ public String[] getMSRequestInfoSubjectAltnames() { String[] ret = new String[2]; // GUID, DNS so far.. if (pkcs10 == null) { log.error("PKCS10 not inited!"); return ret; } // Get attributes Attribute[] attributes = pkcs10.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); if (attributes.length != 0) { ASN1Set set = attributes[0].getAttrValues(); DERSequence seq = (DERSequence) DERSequence.getInstance(set.getObjectAt(0)); Enumeration<?> enumeration = seq.getObjects(); while (enumeration.hasMoreElements()) { DERSequence seq2 = (DERSequence) DERSequence.getInstance(enumeration.nextElement()); ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) seq2.getObjectAt(0); if ("2.5.29.17".equals(oid.getId())) { //SubjectAN try { DEROctetString dos = (DEROctetString) seq2.getObjectAt(2); ASN1InputStream ais = new ASN1InputStream(new ByteArrayInputStream(dos.getOctets())); while (ais.available() > 0) { DERSequence seq3 = (DERSequence) ais.readObject(); Enumeration<?> enum1 = seq3.getObjects(); while (enum1.hasMoreElements()) { DERTaggedObject dto = (DERTaggedObject) enum1.nextElement(); if (dto.getTagNo() == 0) { // Sequence of OIDs and tagged objects DERSequence ds = (DERSequence) dto.getObject(); ASN1ObjectIdentifier doid = (ASN1ObjectIdentifier) ds.getObjectAt(0); if (OID_GUID.equals((doid).getId())) { DEROctetString dos3 = (DEROctetString) ((DERTaggedObject) ds.getObjectAt(1)) .getObject(); ret[0] = dos3.toString().substring(1); // Removes the initial #-sign } } else if (dto.getTagNo() == 2) { // DNS DEROctetString dos3 = (DEROctetString) dto.getObject(); ret[1] = new String(dos3.getOctets()); } } } ais.close(); } catch (IOException e) { log.error(e); } } } } return ret; }
From source file:org.ejbca.core.protocol.ocsp.OcspJunitHelper.java
License:Open Source License
/** * * @param ocspPackage//www. ja va 2 s . c o m * @param nonce * @param respCode expected response code, OK = 0, if not 0, response checking will not continue after response code is checked. * @param httpCode, normally 200 for OK or OCSP error. Can be 400 is more than 1 million bytes is sent for example * @return a SingleResp or null if respCode != 0 * @throws IOException * @throws OCSPException * @throws NoSuchProviderException * @throws CertificateException on parsing errors. * @throws OperatorCreationException */ protected SingleResp[] sendOCSPPost(byte[] ocspPackage, String nonce, int respCode, int httpCode) throws IOException, OCSPException, NoSuchProviderException, OperatorCreationException, CertificateException { // POST the OCSP request URL url = new URL(this.sBaseURL + this.urlEnding); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // we are going to do a POST con.setDoOutput(true); con.setRequestMethod("POST"); // POST it con.setRequestProperty("Content-Type", "application/ocsp-request"); OutputStream os = con.getOutputStream(); os.write(ocspPackage); os.close(); assertEquals("Response code", httpCode, con.getResponseCode()); if (con.getResponseCode() != 200) { return null; // if it is an http error code we don't need to test any more } // Some appserver (Weblogic) responds with "application/ocsp-response; charset=UTF-8" assertNotNull("No Content-Type in reply.", con.getContentType()); assertTrue(con.getContentType().startsWith("application/ocsp-response")); OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream())); assertEquals("Response status not the expected.", respCode, response.getStatus()); if (respCode != 0) { assertNull("According to RFC 2560, responseBytes are not set on error.", response.getResponseObject()); return null; // it messes up testing of invalid signatures... but is needed for the unsuccessful responses } BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject(); X509CertificateHolder[] chain = brep.getCerts(); assertNotNull( "No certificate chain returned in response (chain == null), is ocsp.includesignercert=false in ocsp.properties?. It should be set to default value for test to run.", chain); boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(chain[0])); assertTrue("Response failed to verify.", verify); // Check nonce (if we sent one) if (nonce != null) { byte[] noncerep = brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnValue() .getEncoded(); assertNotNull(noncerep); ASN1InputStream ain = new ASN1InputStream(noncerep); ASN1OctetString oct = ASN1OctetString.getInstance(ain.readObject()); ain.close(); assertEquals(nonce, new String(oct.getOctets())); } SingleResp[] singleResps = brep.getResponses(); return singleResps; }
From source file:org.ejbca.core.protocol.ocsp.OcspJunitHelper.java
License:Open Source License
/** * * @param ocspPackage//from ww w. j a va2 s.c o m * @param nonce * @param respCode expected response code, OK = 0, if not 0, response checking will not continue after response code is checked. * @param httpCode, normally 200 for OK or OCSP error. Can be 400 is more than 1 million bytes is sent for example * @return a BasicOCSPResp or null if not found * @throws IOException * @throws OCSPException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws CertificateException on parsing errors. * @throws OperatorCreationException */ protected BasicOCSPResp sendOCSPGet(byte[] ocspPackage, String nonce, int respCode, int httpCode, boolean shouldIncludeSignCert, X509Certificate signCert) throws IOException, OCSPException, NoSuchProviderException, NoSuchAlgorithmException, OperatorCreationException, CertificateException { // GET the OCSP request String b64 = new String(Base64.encode(ocspPackage, false)); //String urls = URLEncoder.encode(b64, "UTF-8"); // JBoss/Tomcat will not accept escaped '/'-characters by default URL url = new URL(this.sBaseURL + '/' + b64 + this.urlEnding); HttpURLConnection con = (HttpURLConnection) url.openConnection(); if (con.getResponseCode() != httpCode) { log.info("URL when request gave unexpected result: " + url.toString() + " Message was: " + con.getResponseMessage()); } assertEquals("Response code did not match. ", httpCode, con.getResponseCode()); if (con.getResponseCode() != 200) { return null; // if it is an http error code we don't need to test any more } // Some appserver (Weblogic) responds with "application/ocsp-response; charset=UTF-8" assertNotNull(con.getContentType()); assertTrue(con.getContentType().startsWith("application/ocsp-response")); OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream())); assertNotNull("Response should not be null.", response); assertEquals("Response status not the expected.", respCode, response.getStatus()); if (respCode != 0) { assertNull("According to RFC 2560, responseBytes are not set on error.", response.getResponseObject()); return null; // it messes up testing of invalid signatures... but is needed for the unsuccessful responses } BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject(); final X509CertificateHolder signCertHolder; if (!shouldIncludeSignCert) { assertEquals("The signing certificate should not be included in the OCSP response ", 0, brep.getCerts().length); signCertHolder = new JcaX509CertificateHolder(signCert); } else { X509CertificateHolder[] chain = brep.getCerts(); signCertHolder = chain[0]; } boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(signCertHolder)); assertTrue("Response failed to verify.", verify); // Check nonce (if we sent one) if (nonce != null) { byte[] noncerep = brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnValue() .getEncoded(); assertNotNull(noncerep); ASN1InputStream ain = new ASN1InputStream(noncerep); ASN1OctetString oct = ASN1OctetString.getInstance(ain.readObject()); ain.close(); assertEquals(nonce, new String(oct.getOctets())); } return brep; }