List of usage examples for org.bouncycastle.asn1.x509 X509Extensions getExtension
public X509Extension getExtension(ASN1ObjectIdentifier oid)
From source file:chapter6.PKCS10CertCreateExample.java
public static X509Certificate[] buildChain() throws Exception { // Create the certification request KeyPair pair = Utils.generateRSAKeyPair(); PKCS10CertificationRequest request = PKCS10ExtensionExample.generateRequest(pair); // Create a root certificate KeyPair rootPair = Utils.generateRSAKeyPair(); X509Certificate rootCert = X509V1CreateExample.generateV1Certificate(rootPair); // Validate the certification request if (request.verify("BC") == false) { System.out.println("Request failed to verify!!"); System.exit(1);//from w w w. j a v a 2 s . co m } // Create the certificate using the information in the request X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(rootCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X500Principal(request.getCertificationRequestInfo().getSubject().getEncoded())); certGen.setPublicKey(request.getPublicKey("BC")); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(rootCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(request.getPublicKey("BC"))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); // Extract the extension request attribute ASN1Set attributes = request.getCertificationRequestInfo().getAttributes(); for (int i = 0; i < attributes.size(); i++) { Attribute attr = Attribute.getInstance(attributes.getObjectAt(i)); // Process extension request if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0)); Enumeration e = extensions.oids(); while (e.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement(); X509Extension ext = extensions.getExtension(oid); certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets()); } } } X509Certificate issuedCert = certGen.generateX509Certificate(rootPair.getPrivate()); return new X509Certificate[] { issuedCert, rootCert }; }
From source file:chapter7.OCSPResponderExample.java
/** * * @param request//from www . ja v a 2s . c o m * @param responderKey * @param pubKey * @param revokedID * @return * @throws NoSuchProviderException * @throws OCSPException */ public static OCSPResp generateOCSPResponse(final OCSPReq request, final PrivateKey responderKey, final PublicKey pubKey, final CertificateID revokedID) throws NoSuchProviderException, OCSPException { BasicOCSPRespGenerator basicRespGen = new BasicOCSPRespGenerator(pubKey); X509Extensions reqExtensions = request.getRequestExtensions(); if (reqExtensions != null) { X509Extension ext = reqExtensions.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); if (ext != null) { Vector oids = new Vector(); Vector values = new Vector(); oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); values.add(ext); basicRespGen.setResponseExtensions(new X509Extensions(oids, values)); } } Req[] requests = request.getRequestList(); for (Req x : requests) { CertificateID certID = x.getCertID(); // This would normally be a lot more general!! if (certID.equals(revokedID)) { basicRespGen.addResponse(certID, new RevokedStatus(new Date(), CRLReason.privilegeWithdrawn)); } else { basicRespGen.addResponse(certID, CertificateStatus.GOOD); } } BasicOCSPResp basicResp = basicRespGen.generate(CryptoDefs.Algorithm.SHA256withRSA.getName(), responderKey, null, new Date(), CryptoDefs.Provider.BC.getName()); OCSPRespGenerator respGen = new OCSPRespGenerator(); return respGen.generate(OCSPRespGenerator.SUCCESSFUL, basicResp); }
From source file:com.otterca.common.crypto.SimplePolicyGeneratorTest.java
License:Apache License
/** * Test behavior when CPS is set./*from ww w. ja v a2 s . c o m*/ * * @throws IOException */ @Test @edu.umd.cs.findbugs.annotations.SuppressWarnings("NP_NONNULL_PARAM_VIOLATION") public void testCpsPolicy() throws IOException { SimplePolicyGeneratorImpl generator = new SimplePolicyGeneratorImpl(CPS_URI, null, null, null); // get policy extensions byte[] policyBytes = generator.getExtension(SUBJECT, ISSUER); assertNotNull(policyBytes); X509Extensions exts = X509Extensions.getInstance(DLSequence.fromByteArray(policyBytes)); ASN1Encodable asn1 = exts.getExtension(X509Extensions.CertificatePolicies).getParsedValue(); CertificatePolicies policies = CertificatePolicies.getInstance(asn1); assertNotNull(policies, "unable to find CertificatePolicies extension"); for (PolicyInformation info : policies.getPolicyInformation()) { if (id_qt_cps.equals(info.getPolicyIdentifier())) { DLSequence dls = (DLSequence) info.getPolicyQualifiers(); for (int i = 0; i < dls.size(); i++) { DLSequence dls1 = (DLSequence) dls.getObjectAt(i); PolicyQualifierInfo pqInfo = new PolicyQualifierInfo((ASN1ObjectIdentifier) dls1.getObjectAt(0), dls1.getObjectAt(1)); // DLSequence dls1 = (DLSequence) dls.getObjectAt(i); if (id_qt_cps.equals(pqInfo.getPolicyQualifierId())) { assertEquals(pqInfo.getQualifier().toString(), CPS_URI); } else { fail("unknown policy qualifier id: " + pqInfo.getPolicyQualifierId()); } } } else { fail("unknown policy identifier: " + info.getPolicyIdentifier()); } } }
From source file:com.otterca.common.crypto.SimplePolicyGeneratorTest.java
License:Apache License
/** * Test behavior when user notice is set. * /*from ww w . j av a 2 s .c o m*/ * @throws IOException */ @Test @edu.umd.cs.findbugs.annotations.SuppressWarnings("NP_NONNULL_PARAM_VIOLATION") public void testUserNoticePolicy() throws IOException { SimplePolicyGeneratorImpl generator = new SimplePolicyGeneratorImpl(null, ORGANIZATION, USER_NOTICE, Integer.valueOf(1)); // get policy extensions byte[] policyBytes = generator.getExtension(SUBJECT, ISSUER); assertNotNull(policyBytes); X509Extensions exts = X509Extensions.getInstance(DLSequence.fromByteArray(policyBytes)); ASN1Encodable asn1 = exts.getExtension(X509Extensions.CertificatePolicies).getParsedValue(); CertificatePolicies policies = CertificatePolicies.getInstance(asn1); assertNotNull(policies, "unable to find CertificatePolicies extension"); for (PolicyInformation info : policies.getPolicyInformation()) { if (id_qt_unotice.equals(info.getPolicyIdentifier())) { DLSequence dls = (DLSequence) info.getPolicyQualifiers(); for (int i = 0; i < dls.size(); i++) { UserNotice userNotice = UserNotice.getInstance((DLSequence) dls.getObjectAt(i)); assertEquals(userNotice.getNoticeRef().getOrganization().getString(), ORGANIZATION); assertEquals(userNotice.getNoticeRef().getNoticeNumbers()[0].getValue(), BigInteger.ONE); assertEquals(userNotice.getExplicitText().getString(), USER_NOTICE); } } else { fail("unknown policy identifier: " + info.getPolicyIdentifier()); } } }
From source file:com.otterca.common.crypto.X509CertificateBuilderImpl.java
License:Apache License
/** * @see com.otterca.repository.util.X509CertificateBuilder#build(java.security * .PrivateKey)/*from w w w .java 2 s. c o m*/ */ @Override public X509Certificate build(PrivateKey pkey) throws InvalidKeyException, NoSuchAlgorithmException, SignatureException, CertificateEncodingException, CertificateParsingException, KeyStoreException { // validate everything going into the certificate. Standard validations // are quick, issuer validations may require significant resources. validator.validate(); generator = new X509V3CertificateGenerator(); // set the mandatory properties generator.setSerialNumber(serialNumber); generator.setIssuerDN((issuer == null) ? issuerDN : new X509Principal(issuer.getIssuerDN().getName())); generator.setSubjectDN(subjectDN); generator.setNotBefore(notBefore); generator.setNotAfter(notAfter); generator.setPublicKey(pubkey); generator.setSignatureAlgorithm(SIGNATURE_ALGORITHM); // can this certificate be used to sign more certificates? // make sure pathLengthConstraint is always lower than issuer's. setBasicConstraint(); setSKID(); setAKID(); setSubjectAlternativeName(); setIssuerAlternativeName(); setExtendedKeyUsage(); setInhibitAnyPolicy(); setPrivateKeyUsagePeriod(); setNameConstraints(); setAuthorityInfoAccess(); setSubjectInfoAccess(); // set/clear key usage flag. if (keyUsage != null) { if (basicConstraint) { keyUsage = new KeyUsage(keyUsage.intValue() | KeyUsage.keyCertSign); } else { keyUsage = new KeyUsage(keyUsage.intValue() & (Integer.MAX_VALUE ^ KeyUsage.keyCertSign)); } } else if (basicConstraint) { keyUsage = new KeyUsage(KeyUsage.keyCertSign); } // add mandatory key usage constraints. if (keyUsage != null) { generator.addExtension(X509Extensions.KeyUsage, true, keyUsage); } // establish any extensions. for (X509ExtensionGenerator extGenerator : extensionGenerators) { try { byte[] extensionBytes = extGenerator.getExtension(new X500Principal(subjectDN.getEncoded()), issuer); if (extensionBytes != null) { X509Extensions exts = X509Extensions.getInstance(DLSequence.fromByteArray(extensionBytes)); ASN1Encodable asn1 = exts.getExtension(X509Extensions.CertificatePolicies).getParsedValue(); DERObjectIdentifier objectIdentifier = new DERObjectIdentifier( extGenerator.getObjectIdentifier()); generator.addExtension(objectIdentifier, extGenerator.isCritical(), asn1); } } catch (IOException e) { log.info("X509Extension extraction threw IOException! " + e.getMessage()); // throw an exception if this is an error in a critical // extension. Otherwise // will continue to build the certificate and count on the // caller's verification // process. if (extGenerator.isCritical()) { X509CertificateBuilderException ex = new X509CertificateBuilderException(); ex.addError(ErrorType.OTHER_ERROR, e.getMessage()); throw ex; } } } X509Certificate cert = generator.generate(pkey); return cert; }
From source file:com.yacme.ext.oxsit.cust_it.comp.security.cert.CertificateComplianceCA_IT.java
License:Open Source License
/** * check if qcStatements are present as per ETSI * @param _TbsC //from w w w. j av a2s . c o m * @return */ private boolean hasQcStatements(TBSCertificateStructure _TbsC) { //first check for CNIPA requirement //then check for ETSI 102 280 requirements //then check for ETSI 101 862 //qcstatements are defined in ETSI 101 862 X509Extensions xExt = _TbsC.getExtensions(); X509Extension qcStats = xExt.getExtension(X509Extensions.QCStatements); if (qcStats == null) { //no qcStatement setCertificateStateHelper(CertificateState.MISSING_EXTENSION); m_aLogger.log("missing qcStatements"); return false; } int numberOfChecksOk = 4; //if this drops to zero, //it's not marked critical if (!qcStats.isCritical()) numberOfChecksOk--; ASN1Sequence dns = (ASN1Sequence) X509Extension.convertValueToObject(qcStats); for (int i = 0; i < dns.size(); i++) { QCStatement qcs = QCStatement.getInstance(dns.getObjectAt(i)); if (QCStatement.id_etsi_qcs_QcCompliance.equals(qcs.getStatementId())) numberOfChecksOk--; if (QCStatement.id_etsi_qcs_QcSSCD.equals(qcs.getStatementId())) numberOfChecksOk--; if (QCStatement.id_etsi_qcs_RetentionPeriod.equals(qcs.getStatementId())) numberOfChecksOk--; } if (numberOfChecksOk != 0) { m_xQc.setCertificateElementErrorState(X509Extensions.QCStatements.getId(), CertificateElementState.INVALID_value); setCertificateStateHelper(CertificateState.ERROR_IN_EXTENSION); return false; } return true; }
From source file:com.yacme.ext.oxsit.cust_it.comp.security.cert.CertificateCompliance_IT.java
License:Open Source License
/** * check if qcStatements are present as per ETSI * @param _TbsC /*from w w w .j a va2 s. c o m*/ * @return */ private boolean hasQcStatements(TBSCertificateStructure _TbsC) { //first check for CNIPA requirement //then check for ETSI 102 280 requirements //then check for ETSI 101 862 //qcstatements are defined in ETSI 101 862 X509Extensions xExt = _TbsC.getExtensions(); X509Extension qcStats = xExt.getExtension(X509Extensions.QCStatements); if (qcStats == null) { //no qcStatement setCertificateStateHelper(CertificateState.MISSING_EXTENSION); m_aLogger.log("missing qcStatements"); String s = m_xQc.getCertificateDisplayObj() .getCertificateElementCommentString(CertificateElementID.NOT_CRITICAL_EXTENSION); s = s + "\r"; m_xQc.getCertificateDisplayObj().setCertificateElementCommentString( CertificateElementID.NOT_CRITICAL_EXTENSION, s + "qcStatement missing"); return false; } int numberOfChecksOk = 4; //if this drops to zero, //it's not marked critical if (!qcStats.isCritical()) numberOfChecksOk--; ASN1Sequence dns = (ASN1Sequence) X509Extension.convertValueToObject(qcStats); for (int i = 0; i < dns.size(); i++) { QCStatement qcs = QCStatement.getInstance(dns.getObjectAt(i)); if (QCStatement.id_etsi_qcs_QcCompliance.equals(qcs.getStatementId())) numberOfChecksOk--; if (QCStatement.id_etsi_qcs_QcSSCD.equals(qcs.getStatementId())) numberOfChecksOk--; if (QCStatement.id_etsi_qcs_RetentionPeriod.equals(qcs.getStatementId())) numberOfChecksOk--; } if (numberOfChecksOk != 0) { m_xQc.setCertificateElementErrorState(X509Extensions.QCStatements.getId(), CertificateElementState.INVALID_value); setCertificateStateHelper(CertificateState.ERROR_IN_EXTENSION); m_xQc.getCertificateDisplayObj().setCertificateExtensionCommentString( X509Extensions.QCStatements.getId(), "some statement is wrong."); return false; } return true; }
From source file:com.yacme.ext.oxsit.cust_it.comp.security.cert.X509CertDisplayBase_IT.java
License:Open Source License
@Override public void prepareDisplayStrings(XFrame _xFrame, XComponent _xComp) throws IllegalArgumentException, Exception { m_xQc = (XOX_X509Certificate) UnoRuntime.queryInterface(XOX_X509Certificate.class, _xComp); if (m_xQc == null) throw (new IllegalArgumentException( "com.yacme.ext.oxsit.security.cert.XOX_X509CertificateDisplay#prepareDisplayStrings wrong argument")); ////from w w w . ja v a 2s . c o m m_aX509 = null; //remove old certificate //remove old data from HashMaps m_aExtensions.clear(); m_aExtensionLocalizedNames.clear(); m_aExtensionDisplayValues.clear(); m_aCriticalExtensions.clear(); m_aNotCriticalExtensions.clear(); ByteArrayInputStream as = new ByteArrayInputStream(m_xQc.getCertificateAttributes().getDEREncoded()); ASN1InputStream aderin = new ASN1InputStream(as); DERObject ado; try { ado = aderin.readObject(); m_aX509 = new X509CertificateStructure((ASN1Sequence) ado); //initializes the certificate display information initSubjectName(); m_sVersion = String.format("V%d", m_aX509.getVersion()); m_sSerialNumber = new String("" + m_aX509.getSerialNumber().getValue()); initIssuerName(); m_sNotValidBefore = initCertDate(m_aX509.getStartDate().getDate()); m_sNotValidAfter = initCertDate(m_aX509.getEndDate().getDate()); m_sSubjectPublicKeyAlgorithm = initPublicKeyAlgorithm(); m_sSubjectPublicKeyValue = initPublicKeyData(); m_sSignatureAlgorithm = initSignatureAlgorithm(); initThumbPrints(); //now initializes the Extension listing X509Extensions aX509Exts = m_aX509.getTBSCertificate().getExtensions(); //fill the internal extension HashMaps //at the same time we'll get the extension localized name from resources and //fill the display data MessageConfigurationAccess m_aRegAcc = null; m_aRegAcc = new MessageConfigurationAccess(m_xContext, m_xMCF); //FIXME: may be we need to adapt this to the context: the following is valid ONLY if this //object is instantiated from within a dialog, is not true if instantiated from a not UI method (e.g. from basic for example). IDynamicLogger aDlgH = null; CertificateExtensionDisplayHelper aHelper = new CertificateExtensionDisplayHelper(m_xContext, m_lTheLocale, m_sTimeLocaleString, m_sLocaleDateOfBirth, m_bDisplayOID, m_aLogger); for (Enumeration<DERObjectIdentifier> enume = aX509Exts.oids(); enume.hasMoreElements();) { DERObjectIdentifier aDERId = enume.nextElement(); String aTheOID = aDERId.getId(); X509Extension aext = aX509Exts.getExtension(aDERId); m_aExtensions.put(aTheOID, aext); //now grab the localized description try { m_aExtensionLocalizedNames.put(aTheOID, m_aRegAcc.getStringFromRegistry(aTheOID) + ((m_bDisplayOID) ? (" (OID: " + aTheOID.toString() + ")") : "")); } catch (com.sun.star.uno.Exception e) { m_aLogger.severe("setDEREncoded", e); m_aExtensionLocalizedNames.put(aTheOID, aTheOID); } //and decode this extension m_aExtensionDisplayValues.put(aTheOID, aHelper.examineExtension(aext, aDERId, this)); if (aext.isCritical()) m_aCriticalExtensions.put(aTheOID, aext); else m_aNotCriticalExtensions.put(aTheOID, aext); } m_aRegAcc.dispose(); } catch (IOException e) { m_aLogger.severe("setDEREncoded", e); } }
From source file:ec.rubrica.util.BouncyCastleUtils.java
License:Open Source License
public static boolean certificateHasPolicy(X509Certificate cert, String sOid) { try {/*from ww w. ja v a2 s.c om*/ logger.fine("Read cert policies: " + cert.getSerialNumber().toString()); ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); ASN1InputStream aIn = new ASN1InputStream(bIn); ASN1Sequence seq = (ASN1Sequence) aIn.readObject(); X509CertificateStructure obj = new X509CertificateStructure(seq); TBSCertificateStructure tbsCert = obj.getTBSCertificate(); if (tbsCert.getVersion() == 3) { X509Extensions ext = tbsCert.getExtensions(); if (ext != null) { Enumeration en = ext.oids(); while (en.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement(); X509Extension extVal = ext.getExtension(oid); ASN1OctetString oct = extVal.getValue(); ASN1InputStream extIn = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())); if (oid.equals(X509Extension.certificatePolicies)) { ASN1Sequence cp = (ASN1Sequence) extIn.readObject(); for (int i = 0; i != cp.size(); i++) { PolicyInformation pol = PolicyInformation.getInstance(cp.getObjectAt(i)); DERObjectIdentifier dOid = pol.getPolicyIdentifier(); String soid2 = dOid.getId(); logger.fine("Policy: " + soid2); if (soid2.startsWith(sOid)) return true; } } } } } } catch (Exception ex) { logger.severe("Error reading cert policies: " + ex); } return false; }
From source file:edu.washington.iam.tools.IamCertificateHelper.java
License:Apache License
public static int parseCsr(IamCertificate cert) throws IamCertificateException { try {//from www . j a va 2 s. c om PEMReader pRd = new PEMReader(new StringReader(cert.pemRequest)); PKCS10CertificationRequest request = (PKCS10CertificationRequest) pRd.readObject(); if (request == null) throw new IamCertificateException("invalid CSR (request)"); CertificationRequestInfo info = request.getCertificationRequestInfo(); if (info == null) throw new IamCertificateException("invalid CSR (info)"); X509Name dn = info.getSubject(); if (dn == null) throw new IamCertificateException("invalid CSR (dn)"); log.debug("dn=" + dn.toString()); cert.dn = dn.toString(); try { List cns = dn.getValues(X509Name.CN); cert.cn = (String) (cns.get(0)); log.debug("cn=" + cert.cn); cert.names.add(cert.cn); // first entry for names is always cn cns = dn.getValues(X509Name.C); cert.dnC = (String) (cns.get(0)); cns = dn.getValues(X509Name.ST); cert.dnST = (String) (cns.get(0)); } catch (Exception e) { log.debug("get cn error: " + e); throw new IamCertificateException("invalid CSR"); } // see if we've got alt names (in extensions) ASN1Set attrs = info.getAttributes(); if (attrs != null) { for (int a = 0; a < attrs.size(); a++) { Attribute attr = Attribute.getInstance(attrs.getObjectAt(a)); if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { // is the extension X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0)); // get the subAltName extension DERObjectIdentifier sanoid = new DERObjectIdentifier( X509Extensions.SubjectAlternativeName.getId()); X509Extension xext = extensions.getExtension(sanoid); if (xext != null) { log.debug("processing altname extensions"); ASN1Object asn1 = X509Extension.convertValueToObject(xext); Enumeration dit = DERSequence.getInstance(asn1).getObjects(); while (dit.hasMoreElements()) { GeneralName gn = GeneralName.getInstance(dit.nextElement()); log.debug("altname tag=" + gn.getTagNo()); log.debug("altname name=" + gn.getName().toString()); if (gn.getTagNo() == GeneralName.dNSName) cert.names.add(gn.getName().toString()); } } } } } // check key size PublicKey pk = request.getPublicKey(); log.debug("key alg = " + pk.getAlgorithm()); log.debug("key fmt = " + pk.getFormat()); if (pk.getAlgorithm().equals("RSA")) { RSAPublicKey rpk = (RSAPublicKey) pk; cert.keySize = rpk.getModulus().bitLength(); log.debug("key size = " + cert.keySize); } } catch (IOException e) { log.debug("ioerror: " + e); throw new IamCertificateException("invalid CSR " + e.getMessage()); } catch (Exception e) { log.debug("excp: " + e); throw new IamCertificateException("invalid CSR"); } return 1; }