List of usage examples for org.bouncycastle.asn1.x509 GeneralName getInstance
public static GeneralName getInstance(Object obj)
From source file:org.cesecore.util.CertTools.java
License:Open Source License
/** * From an altName string as defined in getSubjectAlternativeName * //from ww w . ja v a 2 s . co m * @param altName * @return ASN.1 GeneralNames * @see #getSubjectAlternativeName */ public static GeneralNames getGeneralNamesFromAltName(final String altName) { if (log.isTraceEnabled()) { log.trace(">getGeneralNamesFromAltName: " + altName); } final ASN1EncodableVector vec = new ASN1EncodableVector(); for (final String email : CertTools.getEmailFromDN(altName)) { vec.add(new GeneralName(1, /*new DERIA5String(iter.next())*/email)); } for (final String dns : CertTools.getPartsFromDN(altName, CertTools.DNS)) { vec.add(new GeneralName(2, new DERIA5String(dns))); } final String directoryName = getDirectoryStringFromAltName(altName); if (directoryName != null) { //final X500Name x500DirectoryName = new X500Name(directoryName); final X500Name x500DirectoryName = new X500Name(LDAPDN.unescapeRDN(directoryName)); final GeneralName gn = new GeneralName(4, x500DirectoryName); vec.add(gn); } for (final String uri : CertTools.getPartsFromDN(altName, CertTools.URI)) { vec.add(new GeneralName(6, new DERIA5String(uri))); } for (final String uri : CertTools.getPartsFromDN(altName, CertTools.URI1)) { vec.add(new GeneralName(6, new DERIA5String(uri))); } for (final String uri : CertTools.getPartsFromDN(altName, CertTools.URI2)) { vec.add(new GeneralName(6, new DERIA5String(uri))); } for (final String addr : CertTools.getPartsFromDN(altName, CertTools.IPADDR)) { final byte[] ipoctets = StringTools.ipStringToOctets(addr); if (ipoctets.length > 0) { final GeneralName gn = new GeneralName(7, new DEROctetString(ipoctets)); vec.add(gn); } else { log.error("Cannot parse/encode ip address, ignoring: " + addr); } } // UPN is an OtherName see method getUpn... for asn.1 definition for (final String upn : CertTools.getPartsFromDN(altName, CertTools.UPN)) { final ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(CertTools.UPN_OBJECTID)); v.add(new DERTaggedObject(true, 0, new DERUTF8String(upn))); vec.add(GeneralName.getInstance(new DERTaggedObject(false, 0, new DERSequence(v)))); } // PermanentIdentifier is an OtherName see method getPermananentIdentifier... for asn.1 definition for (final String permanentIdentifier : CertTools.getPartsFromDN(altName, CertTools.PERMANENTIDENTIFIER)) { final String[] values = getPermanentIdentifierValues(permanentIdentifier); final ASN1EncodableVector v = new ASN1EncodableVector(); // this is the OtherName v.add(new ASN1ObjectIdentifier(CertTools.PERMANENTIDENTIFIER_OBJECTID)); // First the PermanentIdentifier sequence final ASN1EncodableVector piSeq = new ASN1EncodableVector(); if (values[0] != null) { piSeq.add(new DERUTF8String(values[0])); } if (values[1] != null) { piSeq.add(new ASN1ObjectIdentifier(values[1])); } v.add(new DERTaggedObject(true, 0, new DERSequence(piSeq))); // GeneralName gn = new GeneralName(new DERSequence(v), 0); final ASN1Primitive gn = new DERTaggedObject(false, 0, new DERSequence(v)); vec.add(gn); } for (final String guid : CertTools.getPartsFromDN(altName, CertTools.GUID)) { final ASN1EncodableVector v = new ASN1EncodableVector(); byte[] guidbytes = Hex.decode(guid); if (guidbytes != null) { v.add(new ASN1ObjectIdentifier(CertTools.GUID_OBJECTID)); v.add(new DERTaggedObject(true, 0, new DEROctetString(guidbytes))); final ASN1Primitive gn = new DERTaggedObject(false, 0, new DERSequence(v)); vec.add(gn); } else { log.error("Cannot decode hexadecimal guid, ignoring: " + guid); } } // Krb5PrincipalName is an OtherName, see method getKrb5Principal...for ASN.1 definition for (final String principalString : CertTools.getPartsFromDN(altName, CertTools.KRB5PRINCIPAL)) { // Start by parsing the input string to separate it in different parts if (log.isDebugEnabled()) { log.debug("principalString: " + principalString); } // The realm is the last part moving back until an @ final int index = principalString.lastIndexOf('@'); String realm = ""; if (index > 0) { realm = principalString.substring(index + 1); } if (log.isDebugEnabled()) { log.debug("realm: " + realm); } // Now we can have several principals separated by / final ArrayList<String> principalarr = new ArrayList<String>(); int jndex = 0; int bindex = 0; while (jndex < index) { // Loop and add all strings separated by / jndex = principalString.indexOf('/', bindex); if (jndex == -1) { jndex = index; } String s = principalString.substring(bindex, jndex); if (log.isDebugEnabled()) { log.debug("adding principal name: " + s); } principalarr.add(s); bindex = jndex + 1; } // Now we must construct the rather complex asn.1... final ASN1EncodableVector v = new ASN1EncodableVector(); // this is the OtherName v.add(new ASN1ObjectIdentifier(CertTools.KRB5PRINCIPAL_OBJECTID)); // First the Krb5PrincipalName sequence final ASN1EncodableVector krb5p = new ASN1EncodableVector(); // The realm is the first tagged GeneralString krb5p.add(new DERTaggedObject(true, 0, new DERGeneralString(realm))); // Second is the sequence of principal names, which is at tagged position 1 in the krb5p final ASN1EncodableVector principals = new ASN1EncodableVector(); // According to rfc4210 the type NT-UNKNOWN is 0, and according to some other rfc this type should be used... principals.add(new DERTaggedObject(true, 0, new ASN1Integer(0))); // The names themselves are yet another sequence final Iterator<String> i = principalarr.iterator(); final ASN1EncodableVector names = new ASN1EncodableVector(); while (i.hasNext()) { String principalName = (String) i.next(); names.add(new DERGeneralString(principalName)); } principals.add(new DERTaggedObject(true, 1, new DERSequence(names))); krb5p.add(new DERTaggedObject(true, 1, new DERSequence(principals))); v.add(new DERTaggedObject(true, 0, new DERSequence(krb5p))); final ASN1Primitive gn = new DERTaggedObject(false, 0, new DERSequence(v)); vec.add(gn); } // To support custom OIDs in altNames, they must be added as an OtherName of plain type UTF8String for (final String oid : CertTools.getCustomOids(altName)) { for (final String oidValue : CertTools.getPartsFromDN(altName, oid)) { final ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(oid)); v.add(new DERTaggedObject(true, 0, new DERUTF8String(oidValue))); final ASN1Primitive gn = new DERTaggedObject(false, 0, new DERSequence(v)); vec.add(gn); } } if (vec.size() > 0) { return GeneralNames.getInstance(new DERSequence(vec)); } return null; }
From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java
License:Open Source License
/** * Check the private key archive control in the certification request * * @throws OperatorCreationException/*from w w w. j a v a 2s .co m*/ * @throws PKICMPMessageException * @throws CertificateEncodingException * @throws IOException * @throws CRMFException * @throws CMPException * @throws CMSException */ @Test public void testCertificationWithPrivateKeyControl() throws OperatorCreationException, PKICMPMessageException, CertificateException, IOException, CRMFException, CMPException, CMSException, InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchFieldException, IllegalAccessException, CRLException { String distinguishedName = pki.getTestUser1Cert().getSubjectX500Principal().getName(); KeyPair keyPair = new KeyPair(pki.getTestUser1Cert().getPublicKey(), pki.getTestUser1CertPrivateKey()); PKICMPMessages pkiMessages = new PKICMPMessages(); pkiMessages.setPkiKeyStore(pkiKeyStoreRA); byte[] result = pkiMessages.createCertificateMessageWithLocalKey(distinguishedName, keyPair); ASN1InputStream asn1InputStream = new ASN1InputStream(result); ASN1Primitive asn1Primitive = asn1InputStream.readObject(); PKIMessage pkiMessage = PKIMessage.getInstance(asn1Primitive); CertReqMsg[] certReqMsgs = CertReqMessages.getInstance(pkiMessage.getBody().getContent()) .toCertReqMsgArray(); AttributeTypeAndValue[] attributeTypeAndValues = certReqMsgs[0].getCertReq().getControls() .toAttributeTypeAndValueArray(); GeneratePKI genPKI = new GeneratePKI(); genPKI.createPKI(); boolean bFound = false; for (AttributeTypeAndValue attributeTypeAndValue : attributeTypeAndValues) { if (attributeTypeAndValue.getType().equals(CRMFObjectIdentifiers.id_regCtrl_pkiArchiveOptions)) { PKIArchiveControl pkiArchiveControl = new PKIArchiveControl( PKIArchiveOptions.getInstance(attributeTypeAndValue.getValue())); // Decrypt data CMSEnvelopedDataParser cmsEnvelopedDataParser = new CMSEnvelopedDataParser( pkiArchiveControl.getEnvelopedData().getEncoded()); RecipientInformationStore recipients = cmsEnvelopedDataParser.getRecipientInfos(); Collection c = recipients.getRecipients(); Iterator it = c.iterator(); if (it.hasNext()) { RecipientInformation recipient = (RecipientInformation) it.next(); byte[] recdata = recipient .getContent(new JceKeyTransEnvelopedRecipient(genPKI.getSubCACertPrivateKey()) .setProvider(pkiKeyStoreRA.getProvider())); ASN1InputStream tstAsn1InputStream = new ASN1InputStream(recdata); ASN1Primitive tstAsn1Primitive = tstAsn1InputStream.readObject(); EncKeyWithID encKeyWithID = EncKeyWithID.getInstance(tstAsn1Primitive); Assert.assertArrayEquals(keyPair.getPrivate().getEncoded(), encKeyWithID.getPrivateKey().getEncoded()); Assert.assertTrue(encKeyWithID.hasIdentifier()); GeneralName identifier = GeneralName.getInstance(encKeyWithID.getIdentifier()); Assert.assertEquals(genPKI.getTestUser1Cert().getSubjectDN().getName(), identifier.getName().toString()); bFound = true; } } } Assert.assertTrue(bFound); }
From source file:org.ejbca.core.protocol.cmp.BaseCmpMessage.java
License:Open Source License
public GeneralName getRecipient() { if (recipient == null && recipientBytes != null) { ASN1InputStream ais = new ASN1InputStream(new ByteArrayInputStream(recipientBytes)); try {/*from ww w . j a v a2s. c o m*/ recipient = GeneralName.getInstance(ais.readObject()); ais.close(); } catch (IOException e) { throw new RuntimeException(e); } } return recipient; }
From source file:org.ejbca.core.protocol.cmp.BaseCmpMessage.java
License:Open Source License
public GeneralName getSender() { if (sender == null && senderBytes != null) { ASN1InputStream ais = new ASN1InputStream(new ByteArrayInputStream(senderBytes)); try {/* www . j ava2 s . c o m*/ sender = GeneralName.getInstance(ais.readObject()); ais.close(); } catch (IOException e) { throw new RuntimeException(e); } } return sender; }
From source file:org.ejbca.core.protocol.cmp.CrmfRARequestTest.java
License:Open Source License
/** * Send a CMP request with SubjectAltName containing OIDs that are not defined by Ejbca. * Expected to pass and a certificate containing the unsupported OIDs is returned. * /*from w ww . j a va2 s .com*/ * @throws Exception */ @Test public void test04UsingOtherNameInSubjectAltName() throws Exception { ASN1EncodableVector vec = new ASN1EncodableVector(); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(CertTools.UPN_OBJECTID)); v.add(new DERTaggedObject(true, 0, new DERUTF8String("boo@bar"))); GeneralName gn = GeneralName.getInstance(new DERTaggedObject(false, 0, new DERSequence(v))); vec.add(gn); v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier("2.5.5.6")); v.add(new DERTaggedObject(true, 0, new DERIA5String("2.16.528.1.1007.99.8-1-993000027-N-99300011-00.000-00000000"))); gn = GeneralName.getInstance(new DERTaggedObject(false, 0, new DERSequence(v))); vec.add(gn); GeneralNames san = GeneralNames.getInstance(new DERSequence(vec)); ExtensionsGenerator gen = new ExtensionsGenerator(); gen.addExtension(Extension.subjectAlternativeName, false, san); Extensions exts = gen.generate(); final X500Name userDN = new X500Name("CN=TestAltNameUser"); final KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); final byte[] nonce = CmpMessageHelper.createSenderNonce(); final byte[] transid = CmpMessageHelper.createSenderNonce(); final int reqId; String fingerprint = null; try { final PKIMessage one = genCertReq(ISSUER_DN, userDN, keys, this.cacert, nonce, transid, true, exts, null, null, null, null, null); final PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, "CMPKEYIDTESTPROFILE", 567); CertReqMessages ir = (CertReqMessages) req.getBody().getContent(); reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); Assert.assertNotNull(req); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, cmpAlias); // do not check signing if we expect a failure (sFailMessage==null) checkCmpResponseGeneral(resp, ISSUER_DN, userDN, this.cacert, nonce, transid, false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); X509Certificate cert = checkCmpCertRepMessage(userDN, this.cacert, resp, reqId); fingerprint = CertTools.getFingerprintAsString(cert); } finally { try { this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, "TestAltNameUser", RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE); } catch (NotFoundException e) { /*Do nothing*/} try { this.internalCertStoreSession.removeCertificate(fingerprint); } catch (Exception e) { /*Do nothing*/} } }
From source file:org.glite.voms.ac.AttributeCertificate.java
License:eu-egee.org license
public X509Principal getIssuerX509() { if (acInfo == null) { return null; }//from w ww. jav a2s. co m if (acInfo.getIssuer() == null) { return null; } ASN1Sequence seq = (ASN1Sequence) acInfo.getIssuer().getIssuerName().toASN1Primitive(); for (Enumeration e = seq.getObjects(); e.hasMoreElements();) { GeneralName gn = GeneralName.getInstance(e.nextElement()); if (gn.getTagNo() == 4) { return Util.generalNameToX509Name(gn); } } return null; }
From source file:org.glite.voms.ac.AttributeCertificate.java
License:eu-egee.org license
public X500Principal getIssuer() { if (acInfo == null) { return null; }/* w ww . ja v a 2 s .co m*/ if (acInfo.getIssuer() == null) { return null; } ASN1Sequence seq = (ASN1Sequence) acInfo.getIssuer().getIssuerName().toASN1Primitive(); for (Enumeration e = seq.getObjects(); e.hasMoreElements();) { GeneralName gn = GeneralName.getInstance(e.nextElement()); if (gn.getTagNo() == 4) { return Util.generalNameToX500Name(gn); } } return null; }
From source file:org.glite.voms.ac.AttributeCertificate.java
License:eu-egee.org license
public String getHolderX509() { if (acInfo == null) { return null; }//from w w w . j a va2 s . c o m if (acInfo.getHolder() == null) { return null; } GeneralNames gns = acInfo.getHolder().getIssuer(); for (Enumeration e = ((ASN1Sequence) gns.toASN1Primitive()).getObjects(); e.hasMoreElements();) { GeneralName gn = GeneralName.getInstance(e.nextElement()); if (gn.getTagNo() == 4) { X509Principal principal = Util.generalNameToX509Name(gn); return PKIUtils.getOpenSSLFormatPrincipal(principal); } } return null; }
From source file:org.glite.voms.ac.AttributeCertificateInfo.java
License:eu-egee.org license
public AttributeCertificateInfo(ASN1Sequence seq) throws IOException { DERObjectIdentifier AC_TARGET_OID_DER = new DERObjectIdentifier(AC_TARGET_OID); DERObjectIdentifier AC_CERTS_OID_DER = new DERObjectIdentifier(AC_CERTS_OID); DERObjectIdentifier AC_FULL_ATTRIBUTES_OID_DER = new DERObjectIdentifier(AC_FULL_ATTRIBUTES_OID); version = (DERInteger) seq.getObjectAt(0); holder = new Holder((ASN1Sequence) seq.getObjectAt(1)); issuer = new AttCertIssuer(seq.getObjectAt(2)); signature = new AlgorithmIdentifier((ASN1Sequence) seq.getObjectAt(3)); serialNumber = (DERInteger) seq.getObjectAt(4); // VOMS has encoding problems of attCertValidity (uses PrivateKeyUsagePeriod syntax instead) ASN1Sequence s2 = (ASN1Sequence) seq.getObjectAt(5); ASN1Sequence s3 = s2;//from w w w. j a va 2s .c o m if (s2.getObjectAt(0) instanceof ASN1TaggedObject) { badVomsEncoding = true; DEREncodableVector v = new DEREncodableVector(); for (int i = 0; i < 2; i++) { byte[] bb = ((DEROctetString) ((ASN1TaggedObject) s2.getObjectAt(i)).getObject()).getOctets(); v.add(new DERGeneralizedTime(new String(bb))); } s3 = (ASN1Sequence) new DERSequence(v); } attrCertValidityPeriod = AttCertValidityPeriod.getInstance(s3); attributes = (ASN1Sequence) seq.getObjectAt(6); // getting FQANs // System.out.println("Getting FQANs"); if (attributes != null && attributes.size() != 0) { for (Enumeration e = attributes.getObjects(); e.hasMoreElements();) { // DERObject o = (DERObject)e.nextElement(); // byte[] value = null; // try { // value = o.getEncoded(); // } // catch(Exception ex) {} // System.out.println("Class is: " + o.getClass()); // System.out.print("Value is: "); // for (int i =0; i < value.length; i++) // System.out.print(Integer.toHexString(value[i]) + " "); // System.out.println(); ASN1Sequence attribute = (ASN1Sequence) e.nextElement(); if (VOMS_ATTR_OID.equals(((DERObjectIdentifier) attribute.getObjectAt(0)).getId())) { DLSet set = (DLSet) attribute.getObjectAt(1); for (Enumeration s = set.getObjects(); s.hasMoreElements();) { IetfAttrSyntax attr = new IetfAttrSyntax((ASN1Sequence) s.nextElement()); String url = ((DERIA5String) GeneralName .getInstance( ((ASN1Sequence) attr.getPolicyAuthority().toASN1Primitive()).getObjectAt(0)) .getName()).getString(); int idx = url.indexOf("://"); if ((idx < 0) || (idx == (url.length() - 1))) { throw new IllegalArgumentException( "Bad encoding of VOMS policyAuthority : [" + url + "]"); } myVo = url.substring(0, idx); myHostPort = url.substring(idx + 3); idx = myHostPort.lastIndexOf(":"); if ((idx < 0) || (idx == (myHostPort.length() - 1))) { throw new IllegalArgumentException( "Bad encoding of VOMS policyAuthority : [" + url + "]"); } myHost = myHostPort.substring(0, idx); myPort = Integer.valueOf(myHostPort.substring(idx + 1)).intValue(); if (attr.getValueType() != IetfAttrSyntax.VALUE_OCTETS) { throw new IllegalArgumentException( "VOMS attribute values are not encoded as octet strings, policyAuthority = " + url); } for (Iterator j = attr.getValues().iterator(); j.hasNext();) { String fqan = new String(((ASN1OctetString) j.next()).getOctets()); FQAN f = new FQAN(fqan); // maybe requiring that the attributes start with vo is too much? if (!myStringList.contains(fqan) && (fqan.startsWith("/" + myVo + "/") || fqan.equals("/" + myVo))) { myStringList.add(fqan); myFQANs.add(f); } } } } } } // check if the following two can be detected better!!! // for example, is it possible to have only the extensions? how to detect this? if (seq.size() > 8) { issuerUniqueID = new DERBitString(seq.getObjectAt(7)); extensions = new X509Extensions((ASN1Sequence) seq.getObjectAt(8)); } else if (seq.size() > 7) { extensions = new X509Extensions((ASN1Sequence) seq.getObjectAt(7)); } // start parsing of known extensions // System.out.println("Getting AC_TARGET"); if (extensions.getExtension(AC_TARGET_OID_DER) != null) { byte[] data = (extensions.getExtension(AC_TARGET_OID_DER).getValue().getOctets()); ASN1Primitive dobj = null; try { dobj = new ASN1InputStream(new ByteArrayInputStream(data)).readObject(); // System.out.println("DOBJ Class: " + dobj.getClass()); acTargets = new ACTargets(ASN1Sequence.getInstance(dobj)); } catch (Exception e) { throw new IllegalArgumentException("DERO: " + e.getMessage(), e); } } // System.out.println("Getting AC_CERTS"); if (extensions.getExtension(AC_CERTS_OID_DER) != null) { byte[] data = (extensions.getExtension(AC_CERTS_OID_DER).getValue().getOctets()); ASN1Primitive dobj = null; try { dobj = new ASN1InputStream(new ByteArrayInputStream(data)).readObject(); // System.out.println("DOBJ Class: " + dobj.getClass()); acCerts = new ACCerts(ASN1Sequence.getInstance(dobj)); } catch (Exception e) { throw new IllegalArgumentException("DERO: " + e.getMessage(), e); } } // System.out.println("Getting FULL_ATTRIBUTES"); if (extensions.getExtension(AC_FULL_ATTRIBUTES_OID_DER) != null) { byte[] data = (extensions.getExtension(AC_FULL_ATTRIBUTES_OID_DER).getValue().getOctets()); ASN1Primitive dobj = null; try { dobj = new ASN1InputStream(new ByteArrayInputStream(data)).readObject(); // System.out.println("DOBJ Class: " + dobj.getClass()); fullAttributes = new FullAttributes(ASN1Sequence.getInstance(dobj)); } catch (Exception e) { throw new IllegalArgumentException("DERO: " + e.getMessage()); } } }
From source file:org.glite.voms.ac.AttributeHolder.java
License:Open Source License
/** * Gets the Grantor of these attributes. * * @return the grantor./*from w w w .j a v a 2s .com*/ */ public String getGrantor() { ASN1Sequence seq = ASN1Sequence.getInstance(grantor.toASN1Primitive()); GeneralName name = GeneralName.getInstance(seq.getObjectAt(0)); return DERIA5String.getInstance(name.getName()).getString(); }