List of usage examples for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers pkcs_9_at_extensionRequest
ASN1ObjectIdentifier pkcs_9_at_extensionRequest
To view the source code for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers pkcs_9_at_extensionRequest.
Click Source Link
From source file:org.ejbca.core.ejb.ca.sign.SignSessionWithRsaTest.java
License:Open Source License
@Test public void testExtensionOverride() throws Exception { final String altnames = "dNSName=foo1.bar.com,dNSName=foo2.bar.com,dNSName=foo3.bar.com,dNSName=foo4.bar.com,dNSName=foo5.bar.com,dNSName=foo6.bar.com,dNSName=foo7.bar.com," + "dNSName=foo8.bar.com,dNSName=foo9.bar.com,dNSName=foo10.bar.com,dNSName=foo11.bar.com,dNSName=foo12.bar.com,dNSName=foo13.bar.com,dNSName=foo14.bar.com," + "dNSName=foo15.bar.com,dNSName=foo16.bar.com,dNSName=foo17.bar.com,dNSName=foo18.bar.com,dNSName=foo19.bar.com,dNSName=foo20.bar.com,dNSName=foo21.bar.com"; // Create a good certificate profile (good enough), using QC statement final String profileName = "TESTEXTENSIONOVERRIDE"; certificateProfileSession.removeCertificateProfile(internalAdmin, profileName); final CertificateProfile certprof = new CertificateProfile( CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); // Default profile does not allow Extension override certprof.setValidity(298);//from w ww . j a v a 2 s. co m certificateProfileSession.addCertificateProfile(internalAdmin, profileName, certprof); int cprofile = certificateProfileSession.getCertificateProfileId(profileName); // Create a good end entity profile (good enough), allowing multiple UPN // names endEntityProfileSession.removeEndEntityProfile(internalAdmin, profileName); EndEntityProfile profile = new EndEntityProfile(); profile.addField(DnComponents.COUNTRY); profile.addField(DnComponents.COMMONNAME); profile.setValue(EndEntityProfile.AVAILCAS, 0, Integer.toString(SecConst.ALLCAS)); profile.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, Integer.toString(cprofile)); endEntityProfileSession.addEndEntityProfile(internalAdmin, profileName, profile); try { int eeprofile = endEntityProfileSession.getEndEntityProfileId(profileName); int rsacaid = caSession.getCAInfo(internalAdmin, getTestCAName()).getCAId(); EndEntityInformation user = new EndEntityInformation(RSA_USERNAME, "C=SE,CN=extoverride", rsacaid, null, "foo@anatom.nu", new EndEntityType(EndEntityTypes.ENDUSER), eeprofile, cprofile, SecConst.TOKEN_SOFT_PEM, 0, null); user.setPassword("foo123"); user.setStatus(EndEntityConstants.STATUS_NEW); // Change a user that we know... endEntityManagementSession.changeUser(internalAdmin, user, false); // Create a P10 with extensions, in this case altNames with a lot of DNS // names ASN1EncodableVector extensionattr = new ASN1EncodableVector(); extensionattr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); GeneralNames san = CertTools.getGeneralNamesFromAltName(altnames); ExtensionsGenerator extgen = new ExtensionsGenerator(); extgen.addExtension(Extension.subjectAlternativeName, false, san); Extensions exts = extgen.generate(); extensionattr.add(new DERSet(exts)); // Complete the Attribute section of the request, the set (Attributes) // contains one sequence (Attribute) ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new DERSequence(extensionattr)); DERSet attributes = new DERSet(v); // Create PKCS#10 certificate request PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("SHA256WithRSA", new X500Name("C=SE,CN=extoverride"), rsakeys.getPublic(), attributes, rsakeys.getPrivate(), null); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(req.toASN1Structure()); dOut.close(); byte[] p10bytes = bOut.toByteArray(); PKCS10RequestMessage p10 = new PKCS10RequestMessage(p10bytes); p10.setUsername(RSA_USERNAME); p10.setPassword("foo123"); // See if the request message works... Extensions p10exts = p10.getRequestExtensions(); assertNotNull(p10exts); ResponseMessage resp = signSession.createCertificate(internalAdmin, p10, X509ResponseMessage.class, null); X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(resp.getResponseMessage()); assertNotNull("Failed to create certificate", cert); assertEquals("CN=extoverride,C=SE", cert.getSubjectDN().getName()); // check altNames, should be none Collection<List<?>> c = cert.getSubjectAlternativeNames(); assertNull(c); // Change so that we allow override of validity time CertificateProfile prof = certificateProfileSession.getCertificateProfile(cprofile); prof.setAllowExtensionOverride(true); certificateProfileSession.changeCertificateProfile(internalAdmin, profileName, prof); endEntityManagementSession.changeUser(internalAdmin, user, false); resp = signSession.createCertificate(internalAdmin, p10, X509ResponseMessage.class, null); cert = (X509Certificate) CertTools.getCertfromByteArray(resp.getResponseMessage()); assertNotNull("Failed to create certificate", cert); assertEquals("CN=extoverride,C=SE", cert.getSubjectDN().getName()); // check altNames, should be one altName c = cert.getSubjectAlternativeNames(); assertNotNull(c); assertEquals(21, c.size()); String retAltNames = CertTools.getSubjectAlternativeName(cert); List<String> originalNames = Arrays.asList(altnames.split(",")); List<String> returnNames = Arrays.asList(retAltNames.split(", ")); assertTrue(originalNames.containsAll(returnNames)); } finally { certificateProfileSession.removeCertificateProfile(internalAdmin, profileName); endEntityProfileSession.removeEndEntityProfile(internalAdmin, profileName); } }
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 a v a2 s . com 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//w w w . j a v a 2s . c o 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.PKCS10RequestMessage.java
License:Open Source License
/** * Returns the challenge password from the certificattion request. * * @return challenge password from certification request or null if none exist in the request. *///from w w w . jav a 2s .co m public String getPassword() { if (password != null) { return password; } try { if (pkcs10 == null) { init(); } } catch (IllegalArgumentException e) { log.error("PKCS10 not inited!"); return null; } String ret = null; // Get attributes // The password attribute can be either a pkcs_9_at_challengePassword directly // or // a pkcs_9_at_extensionRequest containing a pkcs_9_at_challengePassword as a // X509Extension. AttributeTable attributes = null; CertificationRequestInfo info = pkcs10.getCertificationRequestInfo(); if (info != null) { ASN1Set attrs = info.getAttributes(); if (attrs != null) { attributes = new AttributeTable(attrs); } } if (attributes == null) { return null; } Attribute attr = attributes.get(PKCSObjectIdentifiers.pkcs_9_at_challengePassword); DEREncodable obj = null; if (attr == null) { // See if we have it embedded in an extension request instead attr = attributes.get(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); if (attr == null) { return null; } if (log.isDebugEnabled()) { log.debug("got extension request"); } ASN1Set values = attr.getAttrValues(); if (values.size() == 0) { return null; } X509Extensions exts = X509Extensions.getInstance(values.getObjectAt(0)); X509Extension ext = exts.getExtension(PKCSObjectIdentifiers.pkcs_9_at_challengePassword); if (ext == null) { if (log.isDebugEnabled()) { log.debug("no challenge password extension"); } return null; } obj = ext.getValue(); } else { // If it is a challengePassword directly, it's just to grab the value ASN1Set values = attr.getAttrValues(); obj = values.getObjectAt(0); } if (obj != null) { DERString str = null; try { str = DERPrintableString.getInstance((obj)); } catch (IllegalArgumentException ie) { // This was not printable string, should be utf8string then according to pkcs#9 v2.0 str = DERUTF8String.getInstance((obj)); } if (str != null) { ret = str.getString(); } } return ret; }
From source file:org.ejbca.core.protocol.PKCS10RequestMessage.java
License:Open Source License
/** * @see org.ejbca.core.protocol.IRequestMessage *//*from w ww. jav a 2s . co m*/ public X509Extensions getRequestExtensions() { try { if (pkcs10 == null) { init(); } } catch (IllegalArgumentException e) { log.error("PKCS10 not inited!"); return null; } X509Extensions ret = null; // Get attributes // The X509 extension is in a a pkcs_9_at_extensionRequest AttributeTable attributes = null; CertificationRequestInfo info = pkcs10.getCertificationRequestInfo(); if (info != null) { ASN1Set attrs = info.getAttributes(); if (attrs != null) { attributes = new AttributeTable(attrs); } } if (attributes != null) { // See if we have it embedded in an extension request instead Attribute attr = attributes.get(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); if (attr != null) { if (log.isDebugEnabled()) { log.debug("got request extension"); } ASN1Set values = attr.getAttrValues(); if (values.size() > 0) { try { ret = X509Extensions.getInstance(values.getObjectAt(0)); } catch (IllegalArgumentException e) { if (log.isDebugEnabled()) { log.debug( "pkcs_9_extensionRequest does not contain Extensions that it should, ignoring invalid encoded extension request."); } } } } } return ret; }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
License:Open Source License
private PKCS10CertificationRequest getP10Request() throws Exception { final KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); // Make a PKCS10 request with extensions ASN1EncodableVector attributes = new ASN1EncodableVector(); // Add a custom extension (dummy) ASN1EncodableVector attr = new ASN1EncodableVector(); attr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); ExtensionsGenerator extgen = new ExtensionsGenerator(); extgen.addExtension(new ASN1ObjectIdentifier("1.2.3.4"), false, new DEROctetString("foo123".getBytes())); Extensions exts = extgen.generate(); attr.add(new DERSet(exts)); attributes.add(new DERSequence(attr)); PKCS10CertificationRequest pkcs10 = CertTools.genPKCS10CertificationRequest("SHA1WithRSA", CertTools.stringToBcX500Name("CN=NOUSED"), keys.getPublic(), new DERSet(attributes), keys.getPrivate(), null);//from w ww . jav a2 s . co m return pkcs10; }
From source file:org.ejbca.extra.ra.ScepRequestGenerator.java
License:Open Source License
/** Generates a SCEP CertReq. Keys must have been set in the generator for this to succeed * //from ww w. j a va 2 s . co m */ public byte[] generateCertReq(String dn, String password, X509Certificate ca) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, IOException, CMSException, InvalidAlgorithmParameterException, CertStoreException, CertificateEncodingException, IllegalStateException { this.cacert = ca; this.reqdn = dn; // Create challenge password attribute for PKCS10 // Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }} // // Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE { // type ATTRIBUTE.&id({IOSet}), // values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type}) // } ASN1EncodableVector challpwdattr = new ASN1EncodableVector(); // Challenge password attribute challpwdattr.add(PKCSObjectIdentifiers.pkcs_9_at_challengePassword); ASN1EncodableVector pwdvalues = new ASN1EncodableVector(); pwdvalues.add(new DERUTF8String(password)); challpwdattr.add(new DERSet(pwdvalues)); // Requested extensions attribute ASN1EncodableVector extensionattr = new ASN1EncodableVector(); extensionattr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); // AltNames GeneralNames san = CertTools.getGeneralNamesFromAltName("dNSName=foo.bar.com,iPAddress=10.0.0.1"); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); try { dOut.writeObject(san); } catch (IOException e) { throw new IllegalArgumentException("error encoding value: " + e); } Vector oidvec = new Vector(); oidvec.add(X509Extensions.SubjectAlternativeName); Vector valuevec = new Vector(); valuevec.add(new X509Extension(false, new DEROctetString(bOut.toByteArray()))); X509Extensions exts = new X509Extensions(oidvec, valuevec); extensionattr.add(new DERSet(exts)); // Complete the Attribute section of the request, the set (Attributes) contains two sequences (Attribute) ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new DERSequence(challpwdattr)); v.add(new DERSequence(extensionattr)); DERSet attributes = new DERSet(v); // Create PKCS#10 certificate request p10request = new PKCS10CertificationRequest("SHA1WithRSA", CertTools.stringToBcX509Name(reqdn), keys.getPublic(), attributes, keys.getPrivate()); // Create self signed cert, validity 1 day cert = CertTools.genSelfCert(reqdn, 24 * 60 * 60 * 1000, null, keys.getPrivate(), keys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, false); // wrap message in pkcs#7 byte[] msg = wrap(p10request.getEncoded(), "19"); return msg; }
From source file:org.ejbca.util.CertToolsTest.java
License:Open Source License
@SuppressWarnings("unchecked") public void test19getAltNameStringFromExtension() throws Exception { PKCS10CertificationRequest p10 = new PKCS10CertificationRequest(p10ReqWithAltNames); CertificationRequestInfo info = p10.getCertificationRequestInfo(); ASN1Set set = info.getAttributes(); // The set of attributes contains a sequence of with type oid // PKCSObjectIdentifiers.pkcs_9_at_extensionRequest Enumeration<Object> en = set.getObjects(); boolean found = false; while (en.hasMoreElements()) { ASN1Sequence seq = ASN1Sequence.getInstance(en.nextElement()); DERObjectIdentifier oid = (DERObjectIdentifier) seq.getObjectAt(0); if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { // The object at position 1 is a SET of x509extensions DERSet s = (DERSet) seq.getObjectAt(1); X509Extensions exts = X509Extensions.getInstance(s.getObjectAt(0)); X509Extension ext = exts.getExtension(X509Extensions.SubjectAlternativeName); if (ext != null) { found = true;/*from ww w . jav a 2s .c o m*/ String altNames = CertTools.getAltNameStringFromExtension(ext); assertEquals("dNSName=ort3-kru.net.polisen.se, iPAddress=10.252.255.237", altNames); } } } assertTrue(found); p10 = new PKCS10CertificationRequest(p10ReqWithAltNames2); info = p10.getCertificationRequestInfo(); set = info.getAttributes(); // The set of attributes contains a sequence of with type oid // PKCSObjectIdentifiers.pkcs_9_at_extensionRequest en = set.getObjects(); found = false; while (en.hasMoreElements()) { ASN1Sequence seq = ASN1Sequence.getInstance(en.nextElement()); DERObjectIdentifier oid = (DERObjectIdentifier) seq.getObjectAt(0); if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { // The object at position 1 is a SET of x509extensions DERSet s = (DERSet) seq.getObjectAt(1); X509Extensions exts = X509Extensions.getInstance(s.getObjectAt(0)); X509Extension ext = exts.getExtension(X509Extensions.SubjectAlternativeName); if (ext != null) { found = true; String altNames = CertTools.getAltNameStringFromExtension(ext); assertEquals("dNSName=foo.bar.com, iPAddress=10.0.0.1", altNames); } } } assertTrue(found); }
From source file:org.elasticsearch.xpack.core.ssl.CertGenUtils.java
License:Open Source License
/** * Generates a certificate signing request * * @param keyPair the key pair that will be associated by the certificate generated from the certificate signing request * @param principal the principal of the certificate; commonly referred to as the distinguished name (DN) * @param sanList the subject alternative names that should be added to the certificate as an X509v3 extension. May be * {@code null}/*from w ww .j a v a 2 s . c om*/ * @return a certificate signing request */ static PKCS10CertificationRequest generateCSR(KeyPair keyPair, X500Principal principal, GeneralNames sanList) throws IOException, OperatorCreationException { Objects.requireNonNull(keyPair, "Key-Pair must not be null"); Objects.requireNonNull(keyPair.getPublic(), "Public-Key must not be null"); Objects.requireNonNull(principal, "Principal must not be null"); JcaPKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(principal, keyPair.getPublic()); if (sanList != null) { ExtensionsGenerator extGen = new ExtensionsGenerator(); extGen.addExtension(Extension.subjectAlternativeName, false, sanList); builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate()); } return builder.build(new JcaContentSignerBuilder("SHA256withRSA").setProvider(CertGenUtils.BC_PROV) .build(keyPair.getPrivate())); }
From source file:org.elasticsearch.xpack.core.ssl.CertificateGenerateToolTests.java
License:Open Source License
public void testGeneratingCsr() throws Exception { Path tempDir = initTempDir(); Path outputFile = tempDir.resolve("out.zip"); Path instanceFile = writeInstancesTo(tempDir.resolve("instances.yml")); Collection<CertificateInformation> certInfos = CertificateGenerateTool.parseFile(instanceFile); assertEquals(4, certInfos.size());// w ww.java2s .c o m assertFalse(Files.exists(outputFile)); CertificateGenerateTool.generateAndWriteCsrs(outputFile, certInfos, randomFrom(1024, 2048)); assertTrue(Files.exists(outputFile)); Set<PosixFilePermission> perms = Files.getPosixFilePermissions(outputFile); assertTrue(perms.toString(), perms.contains(PosixFilePermission.OWNER_READ)); assertTrue(perms.toString(), perms.contains(PosixFilePermission.OWNER_WRITE)); assertEquals(perms.toString(), 2, perms.size()); FileSystem fileSystem = FileSystems.newFileSystem(new URI("jar:" + outputFile.toUri()), Collections.emptyMap()); Path zipRoot = fileSystem.getPath("/"); assertFalse(Files.exists(zipRoot.resolve("ca"))); for (CertificateInformation certInfo : certInfos) { String filename = certInfo.name.filename; assertTrue(Files.exists(zipRoot.resolve(filename))); final Path csr = zipRoot.resolve(filename + "/" + filename + ".csr"); assertTrue(Files.exists(csr)); assertTrue(Files.exists(zipRoot.resolve(filename + "/" + filename + ".key"))); PKCS10CertificationRequest request = readCertificateRequest(csr); assertEquals(certInfo.name.x500Principal.getName(), request.getSubject().toString()); Attribute[] extensionsReq = request.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); if (certInfo.ipAddresses.size() > 0 || certInfo.dnsNames.size() > 0) { assertEquals(1, extensionsReq.length); Extensions extensions = Extensions.getInstance(extensionsReq[0].getAttributeValues()[0]); GeneralNames subjAltNames = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName); assertSubjAltNames(subjAltNames, certInfo); } else { assertEquals(0, extensionsReq.length); } } }