List of usage examples for org.bouncycastle.asn1 ASN1InputStream readObject
public ASN1Primitive readObject() throws IOException
From source file:org.ejbca.core.protocol.cmp.CmpResponseMessage.java
License:Open Source License
@Override public boolean create() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException { boolean ret = false; // Some general stuff, common for all types of messages String issuer = null;/* ww w .ja v a2 s . c om*/ String subject = null; if (cert != null) { X509Certificate x509cert = (X509Certificate) cert; issuer = x509cert.getIssuerDN().getName(); subject = x509cert.getSubjectDN().getName(); } else if ((signCertChain != null) && (signCertChain.size() > 0)) { issuer = ((X509Certificate) signCertChain.iterator().next()).getSubjectDN().getName(); subject = "CN=fooSubject"; } else { issuer = "CN=fooIssuer"; subject = "CN=fooSubject"; } final GeneralName issuerName = new GeneralName(new X500Name(issuer)); final GeneralName subjectName = new GeneralName(new X500Name(subject)); final PKIHeaderBuilder myPKIHeader = CmpMessageHelper.createPKIHeaderBuilder(issuerName, subjectName, senderNonce, recipientNonce, transactionId); PKIBody myPKIBody = null; final PKIMessage myPKIMessage; try { if (status.equals(ResponseStatus.SUCCESS)) { if (cert != null) { if (log.isDebugEnabled()) { log.debug("Creating a CertRepMessage 'accepted'"); } PKIStatusInfo myPKIStatusInfo = new PKIStatusInfo(PKIStatus.granted); // 0 = accepted ASN1InputStream certASN1InputStream = new ASN1InputStream( new ByteArrayInputStream(cert.getEncoded())); ASN1InputStream cacertASN1InputStream = new ASN1InputStream( new ByteArrayInputStream(cacert.getEncoded())); try { try { CMPCertificate cmpcert = CMPCertificate.getInstance(certASN1InputStream.readObject()); CertOrEncCert retCert = new CertOrEncCert(cmpcert); CertifiedKeyPair myCertifiedKeyPair = new CertifiedKeyPair(retCert); CertResponse myCertResponse = new CertResponse(new ASN1Integer(requestId), myPKIStatusInfo, myCertifiedKeyPair, null); CertResponse[] certRespos = { myCertResponse }; CMPCertificate[] caPubs = { CMPCertificate.getInstance(cacertASN1InputStream.readObject()) }; CertRepMessage myCertRepMessage = new CertRepMessage(caPubs, certRespos); int respType = requestType + 1; // 1 = intitialization response, 3 = certification response etc if (log.isDebugEnabled()) { log.debug("Creating response body of type " + respType); } myPKIBody = new PKIBody(respType, myCertRepMessage); } finally { certASN1InputStream.close(); cacertASN1InputStream.close(); } } catch (IOException e) { throw new IllegalStateException("Unexpected IOException caught.", e); } } } else if (status.equals(ResponseStatus.FAILURE)) { if (log.isDebugEnabled()) { log.debug("Creating a CertRepMessage 'rejected'"); } // Create a failure message ASN1EncodableVector statusInfoV = new ASN1EncodableVector(); statusInfoV.add(ASN1Integer.getInstance(PKIStatus.rejection.toASN1Primitive())); if (failText != null) { statusInfoV.add(new PKIFreeText(new DERUTF8String(failText))); } statusInfoV.add(CmpMessageHelper.getPKIFailureInfo(failInfo.intValue())); PKIStatusInfo myPKIStatusInfo = PKIStatusInfo .getInstance(ASN1Sequence.getInstance(new DERSequence(statusInfoV))); myPKIBody = CmpMessageHelper.createCertRequestRejectBody(myPKIStatusInfo, requestId, requestType); } else { if (log.isDebugEnabled()) { log.debug("Creating a 'waiting' message?"); } // Not supported, lets create a PKIError failure instead // Create a failure message ASN1EncodableVector statusInfoV = new ASN1EncodableVector(); statusInfoV.add(PKIStatus.rejection); // 2 = rejection if (failText != null) { statusInfoV.add(new PKIFreeText(new DERUTF8String(failText))); } statusInfoV.add(CmpMessageHelper.getPKIFailureInfo(failInfo.intValue())); PKIStatusInfo myPKIStatusInfo = PKIStatusInfo.getInstance(new DERSequence(statusInfoV)); ErrorMsgContent myErrorContent = new ErrorMsgContent(myPKIStatusInfo); myPKIBody = new PKIBody(23, myErrorContent); // 23 = error } if ((pbeKeyId != null) && (pbeKey != null) && (pbeDigestAlg != null) && (pbeMacAlg != null)) { myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(CMPObjectIdentifiers.passwordBasedMac)); PKIHeader header = myPKIHeader.build(); myPKIMessage = new PKIMessage(header, myPKIBody); responseMessage = CmpMessageHelper.protectPKIMessageWithPBE(myPKIMessage, pbeKeyId, pbeKey, pbeDigestAlg, pbeMacAlg, pbeIterationCount); } else { myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(digest)); PKIHeader header = myPKIHeader.build(); myPKIMessage = new PKIMessage(header, myPKIBody); responseMessage = CmpMessageHelper.signPKIMessage(myPKIMessage, signCertChain, signKey, digest, provider); } ret = true; } catch (CertificateEncodingException e) { log.error("Error creating CertRepMessage: ", e); } catch (InvalidKeyException e) { log.error("Error creating CertRepMessage: ", e); } catch (NoSuchProviderException e) { log.error("Error creating CertRepMessage: ", e); } catch (NoSuchAlgorithmException e) { log.error("Error creating CertRepMessage: ", e); } catch (SecurityException e) { log.error("Error creating CertRepMessage: ", e); } catch (SignatureException e) { log.error("Error creating CertRepMessage: ", e); } return ret; }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
License:Open Source License
protected static PKIMessage genCertReq(String issuerDN, X500Name userDN, String altNames, KeyPair keys, Certificate cacert, byte[] nonce, byte[] transid, boolean raVerifiedPopo, Extensions extensions, Date notBefore, Date notAfter, BigInteger customCertSerno, AlgorithmIdentifier pAlg, DEROctetString senderKID) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, InvalidKeyException, SignatureException { ASN1EncodableVector optionalValidityV = new ASN1EncodableVector(); org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time( new DERGeneralizedTime("20030211002120Z")); if (notBefore != null) { nb = new org.bouncycastle.asn1.x509.Time(notBefore); }/*from www. ja v a 2 s .com*/ optionalValidityV.add(new DERTaggedObject(true, 0, nb)); org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date()); if (notAfter != null) { na = new org.bouncycastle.asn1.x509.Time(notAfter); } optionalValidityV.add(new DERTaggedObject(true, 1, na)); OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV)); CertTemplateBuilder myCertTemplate = new CertTemplateBuilder(); myCertTemplate.setValidity(myOptionalValidity); if (issuerDN != null) { myCertTemplate.setIssuer(new X500Name(issuerDN)); } myCertTemplate.setSubject(userDN); byte[] bytes = keys.getPublic().getEncoded(); ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); ASN1InputStream dIn = new ASN1InputStream(bIn); SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject()); dIn.close(); myCertTemplate.setPublicKey(keyInfo); // If we did not pass any extensions as parameter, we will create some of our own, standard ones Extensions exts = extensions; if (exts == null) { // SubjectAltName // Some altNames ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream dOut = new ASN1OutputStream(bOut); ExtensionsGenerator extgen = new ExtensionsGenerator(); if (altNames != null) { GeneralNames san = CertTools.getGeneralNamesFromAltName(altNames); dOut.writeObject(san); byte[] value = bOut.toByteArray(); extgen.addExtension(Extension.subjectAlternativeName, false, value); } // KeyUsage int bcku = 0; bcku = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation; KeyUsage ku = new KeyUsage(bcku); extgen.addExtension(Extension.keyUsage, false, new DERBitString(ku)); // Make the complete extension package exts = extgen.generate(); } myCertTemplate.setExtensions(exts); if (customCertSerno != null) { // Add serialNumber to the certTemplate, it is defined as a MUST NOT be used in RFC4211, but we will use it anyway in order // to request a custom certificate serial number (something not standard anyway) myCertTemplate.setSerialNumber(new ASN1Integer(customCertSerno)); } CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null); // POPO /* * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8, * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 })); * * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new * byte[] { 44 }), 2); //take choice pos tag 2 * * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput( * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2, * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 })); */ ProofOfPossession myProofOfPossession = null; if (raVerifiedPopo) { // raVerified POPO (meaning there is no POPO) myProofOfPossession = new ProofOfPossession(); } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DEROutputStream mout = new DEROutputStream(baos); mout.writeObject(myCertRequest); mout.close(); byte[] popoProtectionBytes = baos.toByteArray(); String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm()) .getId(); Signature sig = Signature.getInstance(sigalg, "BC"); sig.initSign(keys.getPrivate()); sig.update(popoProtectionBytes); DERBitString bs = new DERBitString(sig.sign()); POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null, new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs); myProofOfPossession = new ProofOfPossession(myPOPOSigningKey); } 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(userDN), new GeneralName( new X500Name(issuerDN != null ? issuerDN : ((X509Certificate) cacert).getSubjectDN().getName()))); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); myPKIHeader.setProtectionAlg(pAlg); myPKIHeader.setSenderKID(senderKID); PKIBody myPKIBody = new PKIBody(0, myCertReqMessages); // initialization // request PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); return myPKIMessage; }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
License:Open Source License
protected static PKIMessage genRenewalReq(X500Name userDN, Certificate cacert, byte[] nonce, byte[] transid, KeyPair keys, boolean raVerifiedPopo, X500Name reqSubjectDN, String reqIssuerDN, AlgorithmIdentifier pAlg, DEROctetString senderKID) throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, CertificateEncodingException { CertTemplateBuilder myCertTemplate = new CertTemplateBuilder(); ASN1EncodableVector optionalValidityV = new ASN1EncodableVector(); org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time( new DERGeneralizedTime("20030211002120Z")); org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date()); optionalValidityV.add(new DERTaggedObject(true, 0, nb)); optionalValidityV.add(new DERTaggedObject(true, 1, na)); OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV)); myCertTemplate.setValidity(myOptionalValidity); if (reqSubjectDN != null) { myCertTemplate.setSubject(reqSubjectDN); }//from w ww . j a v a2 s . co m if (reqIssuerDN != null) { myCertTemplate.setIssuer(new X500Name(reqIssuerDN)); } byte[] bytes = keys.getPublic().getEncoded(); ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); ASN1InputStream dIn = new ASN1InputStream(bIn); try { SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject()); myCertTemplate.setPublicKey(keyInfo); } finally { dIn.close(); } CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null); // POPO /* * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8, * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 })); * * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new * byte[] { 44 }), 2); //take choice pos tag 2 * * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput( * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2, * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 })); */ ProofOfPossession myProofOfPossession = null; if (raVerifiedPopo) { // raVerified POPO (meaning there is no POPO) myProofOfPossession = new ProofOfPossession(); } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DEROutputStream mout = new DEROutputStream(baos); mout.writeObject(myCertRequest); mout.close(); byte[] popoProtectionBytes = baos.toByteArray(); String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm()) .getId(); Signature sig = Signature.getInstance(sigalg); sig.initSign(keys.getPrivate()); sig.update(popoProtectionBytes); DERBitString bs = new DERBitString(sig.sign()); POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null, new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs); myProofOfPossession = new ProofOfPossession(myPOPOSigningKey); } // myCertReqMsg.addRegInfo(new AttributeTypeAndValue(new // ASN1ObjectIdentifier("1.3.6.2.2.2.2.3.1"), new // DERInteger(1122334455))); AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken, new DERUTF8String("foo123")); AttributeTypeAndValue[] avs = { av }; CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs); CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg); PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(new JcaX509CertificateHolder((X509Certificate) cacert).getSubject())); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); myPKIHeader.setProtectionAlg(pAlg); myPKIHeader.setSenderKID(senderKID); PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_KEY_UPDATE_REQ, myCertReqMessages); // Key Update Request PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); return myPKIMessage; }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
License:Open Source License
protected static void checkCmpResponseGeneral(byte[] retMsg, String issuerDN, X500Name userDN, Certificate cacert, byte[] senderNonce, byte[] transId, boolean signed, String pbeSecret, String expectedSignAlg)//from w ww. j a v a2 s . c o m throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException { assertNotNull("No response from server.", retMsg); assertTrue("Response was of 0 length.", retMsg.length > 0); boolean pbe = (pbeSecret != null); // // Parse response message // ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg)); PKIMessage respObject = null; try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); // The signer, i.e. the CA, check it's the right CA PKIHeader header = respObject.getHeader(); // Check that the message is signed with the correct digest alg if (StringUtils.isEmpty(expectedSignAlg)) { expectedSignAlg = PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(); } // if cacert is ECDSA we should expect an ECDSA signature alg //if (AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECDSA")) { // expectedSignAlg = X9ObjectIdentifiers.ecdsa_with_SHA1.getId(); //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECGOST3410")) { // expectedSignAlg = CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001.getId(); //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("DSTU4145")) { // expectedSignAlg = (new ASN1ObjectIdentifier(CesecoreConfiguration.getOidDstu4145())).getId(); //} if (signed) { AlgorithmIdentifier algId = header.getProtectionAlg(); assertNotNull( "Protection algorithm was null when expecting a signed response, this was propably an unprotected error message: " + header.getFreeText(), algId); assertEquals(expectedSignAlg, algId.getAlgorithm().getId()); } if (pbe) { AlgorithmIdentifier algId = header.getProtectionAlg(); assertNotNull( "Protection algorithm was null when expecting a pbe protected response, this was propably an unprotected error message: " + header.getFreeText(), algId); assertEquals("Protection algorithm id: " + algId.getAlgorithm().getId(), CMPObjectIdentifiers.passwordBasedMac.getId(), algId.getAlgorithm().getId()); // 1.2.840.113549.1.1.5 - SHA-1 with RSA Encryption } // Check that the signer is the expected CA assertEquals(header.getSender().getTagNo(), 4); X500Name expissuer = new X500Name(issuerDN); X500Name actissuer = new X500Name(header.getSender().getName().toString()); assertEquals(expissuer, actissuer); if (signed) { // Verify the signature byte[] protBytes = CmpMessageHelper.getProtectedBytes(respObject); DERBitString bs = respObject.getProtection(); Signature sig; try { sig = Signature.getInstance(expectedSignAlg, "BC"); sig.initVerify(cacert); sig.update(protBytes); boolean ret = sig.verify(bs.getBytes()); assertTrue(ret); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); assertTrue(false); } catch (NoSuchProviderException e) { e.printStackTrace(); assertTrue(false); } catch (InvalidKeyException e) { e.printStackTrace(); assertTrue(false); } catch (SignatureException e) { e.printStackTrace(); assertTrue(false); } } if (pbe) { ASN1OctetString os = header.getSenderKID(); assertNotNull(os); String keyId = CmpMessageHelper.getStringFromOctets(os); log.debug("Found a sender keyId: " + keyId); // Verify the PasswordBased protection of the message byte[] protectedBytes = CmpMessageHelper.getProtectedBytes(respObject); DERBitString protection = respObject.getProtection(); AlgorithmIdentifier pAlg = header.getProtectionAlg(); log.debug("Protection type is: " + pAlg.getAlgorithm().getId()); PBMParameter pp = PBMParameter.getInstance(pAlg.getParameters()); int iterationCount = pp.getIterationCount().getPositiveValue().intValue(); log.debug("Iteration count is: " + iterationCount); AlgorithmIdentifier owfAlg = pp.getOwf(); // Normal OWF alg is 1.3.14.3.2.26 - SHA1 log.debug("Owf type is: " + owfAlg.getAlgorithm().getId()); AlgorithmIdentifier macAlg = pp.getMac(); // Normal mac alg is 1.3.6.1.5.5.8.1.2 - HMAC/SHA1 log.debug("Mac type is: " + macAlg.getAlgorithm().getId()); byte[] salt = pp.getSalt().getOctets(); // log.info("Salt is: "+new String(salt)); byte[] raSecret = pbeSecret != null ? pbeSecret.getBytes() : new byte[0]; byte[] basekey = new byte[raSecret.length + salt.length]; System.arraycopy(raSecret, 0, basekey, 0, raSecret.length); for (int i = 0; i < salt.length; i++) { basekey[raSecret.length + i] = salt[i]; } // Construct the base key according to rfc4210, section 5.1.3.1 MessageDigest dig = MessageDigest.getInstance(owfAlg.getAlgorithm().getId(), BouncyCastleProvider.PROVIDER_NAME); for (int i = 0; i < iterationCount; i++) { basekey = dig.digest(basekey); dig.reset(); } // HMAC/SHA1 os normal 1.3.6.1.5.5.8.1.2 or 1.2.840.113549.2.7 String macOid = macAlg.getAlgorithm().getId(); Mac mac = Mac.getInstance(macOid, BouncyCastleProvider.PROVIDER_NAME); SecretKey key = new SecretKeySpec(basekey, macOid); mac.init(key); mac.reset(); mac.update(protectedBytes, 0, protectedBytes.length); byte[] out = mac.doFinal(); // My out should now be the same as the protection bits byte[] pb = protection.getBytes(); boolean ret = Arrays.equals(out, pb); assertTrue(ret); } // --SenderNonce // SenderNonce is something the server came up with, but it should be 16 // chars byte[] nonce = header.getSenderNonce().getOctets(); assertEquals(nonce.length, 16); // --Recipient Nonce // recipient nonce should be the same as we sent away as sender nonce nonce = header.getRecipNonce().getOctets(); assertEquals(new String(nonce), new String(senderNonce)); // --Transaction ID // transid should be the same as the one we sent nonce = header.getTransactionID().getOctets(); assertEquals(new String(nonce), new String(transId)); }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
License:Open Source License
protected X509Certificate checkCmpCertRepMessage(X500Name userDN, Certificate cacert, byte[] retMsg, int requestId) throws Exception { ///*from w w w . j a va 2s. co m*/ // Parse response message // assertTrue(cacert instanceof X509Certificate); PKIMessage respObject = null; ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg)); try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); // Verify body type PKIBody body = respObject.getBody(); int tag = body.getType(); assertEquals(1, tag); // Verify the response CertRepMessage c = (CertRepMessage) body.getContent(); assertNotNull(c); CertResponse resp = c.getResponse()[0]; assertNotNull(resp); assertEquals(resp.getCertReqId().getValue().intValue(), requestId); // Verify response status PKIStatusInfo info = resp.getStatus(); assertNotNull(info); assertEquals(0, info.getStatus().intValue()); // Verify response certificate CertifiedKeyPair kp = resp.getCertifiedKeyPair(); assertNotNull(kp); CertOrEncCert cc = kp.getCertOrEncCert(); assertNotNull(cc); final CMPCertificate cmpcert = cc.getCertificate(); assertNotNull(cmpcert); final X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(cmpcert.getEncoded()); checkDN(userDN, new JcaX509CertificateHolder(cert).getSubject()); assertArrayEquals(cert.getIssuerX500Principal().getEncoded(), ((X509Certificate) cacert).getSubjectX500Principal().getEncoded()); // Verify the issuer of cert CMPCertificate respCmpCaCert = c.getCaPubs()[0]; final X509Certificate respCaCert = (X509Certificate) CertTools .getCertfromByteArray(respCmpCaCert.getEncoded()); assertEquals(CertTools.getFingerprintAsString(cacert), CertTools.getFingerprintAsString(respCaCert)); Collection<Certificate> cacerts = new ArrayList<Certificate>(); cacerts.add(cacert); assertTrue(CertTools.verify(cert, cacerts)); cacerts = new ArrayList<Certificate>(); cacerts.add(respCaCert); assertTrue(CertTools.verify(cert, cacerts)); return cert; }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
License:Open Source License
protected static void checkCmpPKIConfirmMessage(X500Name userDN, Certificate cacert, byte[] retMsg) throws IOException { ////from ww w . ja v a 2 s.c o m // Parse response message // PKIMessage respObject = null; ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg)); try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); PKIHeader header = respObject.getHeader(); assertEquals(header.getSender().getTagNo(), 4); X509Principal responseDN = new X509Principal(header.getSender().getName().toString()); X509Principal expectedDN = new X509Principal( ((X509Certificate) cacert).getSubjectDN().getName().toString()); assertEquals(expectedDN.getName(), responseDN.getName()); responseDN = new X509Principal(header.getRecipient().getName().toString()); expectedDN = new X509Principal(userDN); assertEquals(expectedDN.getName(), responseDN.getName()); PKIBody body = respObject.getBody(); int tag = body.getType(); assertEquals(19, tag); PKIConfirmContent n = (PKIConfirmContent) body.getContent(); assertNotNull(n); assertEquals(DERNull.INSTANCE, n.toASN1Primitive()); }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
License:Open Source License
protected static void checkCmpRevokeConfirmMessage(String issuerDN, X500Name userDN, BigInteger serno, Certificate cacert, byte[] retMsg, boolean success) throws IOException { ///*www .java 2s .c o m*/ // Parse response message // PKIMessage respObject = null; ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg)); try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); PKIHeader header = respObject.getHeader(); assertEquals(header.getSender().getTagNo(), 4); X509Principal responseDN = new X509Principal(header.getSender().getName().toString()); X509Principal expectedDN = new X509Principal(issuerDN); assertEquals(expectedDN.getName(), responseDN.getName()); responseDN = new X509Principal(header.getRecipient().getName().toString()); expectedDN = new X509Principal(userDN); assertEquals(expectedDN.getName(), responseDN.getName()); PKIBody body = respObject.getBody(); int tag = body.getType(); assertEquals(tag, 12); RevRepContent n = (RevRepContent) body.getContent(); assertNotNull(n); PKIStatusInfo info = n.getStatus()[0]; if (success) { assertEquals("If the revocation was successful, status should be 0.", 0, info.getStatus().intValue()); } else { assertEquals("If the revocation was unsuccessful, status should be 2.", 2, info.getStatus().intValue()); } }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
License:Open Source License
/** * //from w ww. j a va 2 s . c o m * @param retMsg * @param failMsg expected fail message * @param tag 1 is answer to initialisation resp, 3 certification resp etc, 23 is error * @param err a number from FailInfo * @throws IOException */ protected static void checkCmpFailMessage(byte[] retMsg, String failMsg, int exptag, int requestId, int err, int expectedPKIFailInfo) throws IOException { // // Parse response message // PKIMessage respObject = null; ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg)); try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); final PKIBody body = respObject.getBody(); final int tag = body.getType(); assertEquals(exptag, tag); final PKIStatusInfo info; if (exptag == CmpPKIBodyConstants.ERRORMESSAGE) { ErrorMsgContent c = (ErrorMsgContent) body.getContent(); assertNotNull(c); info = c.getPKIStatusInfo(); assertNotNull(info); assertEquals(ResponseStatus.FAILURE.getValue(), info.getStatus().intValue()); int i = info.getFailInfo().intValue(); assertEquals(err, i); } else if (exptag == CmpPKIBodyConstants.REVOCATIONRESPONSE) { RevRepContent rrc = (RevRepContent) body.getContent(); assertNotNull(rrc); info = rrc.getStatus()[0]; assertNotNull(info); assertEquals(ResponseStatus.FAILURE.getValue(), info.getStatus().intValue()); assertEquals(PKIFailureInfo.badRequest, info.getFailInfo().intValue()); } else { CertRepMessage c = null; if (exptag == CmpPKIBodyConstants.INITIALIZATIONRESPONSE || exptag == CmpPKIBodyConstants.CERTIFICATIONRESPONSE) { c = (CertRepMessage) body.getContent(); } assertNotNull(c); CertResponse resp = c.getResponse()[0]; assertNotNull(resp); assertEquals(resp.getCertReqId().getValue().intValue(), requestId); info = resp.getStatus(); assertNotNull(info); int error = info.getStatus().intValue(); assertEquals(ResponseStatus.FAILURE.getValue(), error); // 2 is // rejection assertEquals(expectedPKIFailInfo, info.getFailInfo().intValue()); } log.debug("expected fail message: '" + failMsg + "'. received fail message: '" + info.getStatusString().getStringAt(0).getString() + "'."); assertEquals(failMsg, info.getStatusString().getStringAt(0).getString()); }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
License:Open Source License
protected static void checkCmpPKIErrorMessage(byte[] retMsg, String sender, X500Name recipient, int errorCode, String errorMsg) throws IOException { ////from ww w . j a v a2 s. c om // Parse response message // PKIMessage respObject = null; ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg)); try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); PKIHeader header = respObject.getHeader(); assertEquals(header.getSender().getTagNo(), 4); { final X500Name name = X500Name.getInstance(header.getSender().getName()); assertEquals(name.toString(), sender); } { final X500Name name = X500Name.getInstance(header.getRecipient().getName()); assertArrayEquals(name.getEncoded(), recipient.getEncoded()); } PKIBody body = respObject.getBody(); int tag = body.getType(); assertEquals(tag, 23); ErrorMsgContent n = (ErrorMsgContent) body.getContent(); assertNotNull(n); PKIStatusInfo info = n.getPKIStatusInfo(); assertNotNull(info); BigInteger i = info.getStatus(); assertEquals(i.intValue(), 2); DERBitString b = info.getFailInfo(); assertEquals("Return wrong error code.", errorCode, b.intValue()); if (errorMsg != null) { PKIFreeText freeText = info.getStatusString(); DERUTF8String utf = freeText.getStringAt(0); assertEquals(errorMsg, utf.getString()); } }
From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateTest.java
License:Open Source License
/** * Sends a KeyUpdateRequest for a certificate that belongs to an end entity whose status is not NEW and the configurations is * NOT to allow changing the end entity status automatically. A CMP error message is expected and no certificate renewal. * //from w w w . jav a2 s .c o m * - Pre-configuration: Sets the operational mode to client mode (cmp.raoperationalmode=normal) * - Pre-configuration: Sets cmp.allowautomaticrenewal to 'false' and tests that the resetting of configuration has worked. * - Pre-configuration: Sets cmp.allowupdatewithsamekey to 'true' * - Creates a new user and obtains a certificate, cert, for this user. Tests whether obtaining the certificate was successful. * - Generates a CMP KeyUpdate Request and tests that such request has been created. * - Signs the CMP request using cert and attaches cert to the CMP request. Tests that the CMP request is still not null * - Sends the request using HTTP and receives a response. * - Examines the response: * - Checks that the response is not empty or null * - Checks that the protection algorithm is sha1WithRSAEncryption * - Checks that the signer is the expected CA * - Verifies the response signature * - Checks that the response's senderNonce is 16 bytes long * - Checks that the request's senderNonce is the same as the response's recipientNonce * - Checks that the request and the response has the same transactionID * - Parses the response and checks that the parsing did not result in a 'null' * - Checks that the CMP response message tag number is '23', indicating a CMP error message * - Checks that the CMP response message contains the expected error details text * * @throws Exception */ @Test public void test02AutomaticUpdateNotAllowed() throws Exception { if (log.isTraceEnabled()) { log.trace(">test02AutomaticUpdateNotAllowed"); } this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, false); this.cmpConfiguration.setKurAllowSameKey(this.cmpAlias, true); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); //--------------- create the user and issue his first certificate ----------------- createUser(this.username, this.userDN.toString(), "foo123"); KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); final Certificate certificate; try { certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123", new PublicKeyWrapper(keys.getPublic())); } catch (ObjectNotFoundException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (CADoesntExistsException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (EjbcaException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (AuthorizationDeniedException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (CesecoreException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } assertNotNull("Failed to create a test certificate", certificate); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, null, null, pAlg, new DEROctetString(this.nonce)); assertNotNull("Failed to generate a CMP renewal request", req); CMPCertificate[] extraCert = getCMPCert(certificate); req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, keys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(req); 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, this.cmpAlias); checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, 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); final PKIBody body = respObject.getBody(); assertEquals(23, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); final String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); final String expectedErrMsg = "Got request with status GENERATED (40), NEW, FAILED or INPROCESS required: " + this.username + "."; assertEquals(expectedErrMsg, errMsg); if (log.isTraceEnabled()) { log.trace("<test02AutomaticUpdateNotAllowed"); } }