List of usage examples for org.bouncycastle.asn1 DERSequence DERSequence
public DERSequence(ASN1Encodable[] elements)
From source file:org.deviceconnect.android.ssl.EndPointKeyStoreManager.java
License:MIT License
@Override public void requestKeyStore(final String ipAddress, final KeyStoreCallback callback) { mExecutor.execute(new Runnable() { @Override// ww w .ja va 2 s . co m public void run() { if (BuildConfig.DEBUG) { mLogger.info("Requested keystore: alias = " + getAlias() + ", IP Address = " + ipAddress); } try { String alias = getAlias(); if (hasIPAddress(ipAddress)) { if (BuildConfig.DEBUG) { mLogger.info("Certificate is cached for alias: " + alias); } Certificate[] chain = mKeyStore.getCertificateChain(getAlias()); callback.onSuccess(mKeyStore, chain[0], chain[1]); } else { if (BuildConfig.DEBUG) { mLogger.info("Generating key pair..."); } final KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA"); final KeyPair keyPair = keyGenerator.generateKeyPair(); if (BuildConfig.DEBUG) { mLogger.info("Generated key pair."); mLogger.info("Executing certificate request..."); } final CertificateAuthorityClient localCA = new CertificateAuthorityClient(mContext, mRootCA); final List<ASN1Encodable> names = new ArrayList<>(); names.add(new GeneralName(GeneralName.iPAddress, ipAddress)); for (SAN cache : mSANs) { if (!cache.mName.equals(ipAddress)) { names.add(new GeneralName(cache.mTagNo, cache.mName)); } } names.add(new GeneralName(GeneralName.iPAddress, "0.0.0.0")); names.add(new GeneralName(GeneralName.iPAddress, "127.0.0.1")); names.add(new GeneralName(GeneralName.dNSName, "localhost")); GeneralNames generalNames = new GeneralNames( new DERSequence(names.toArray(new ASN1Encodable[names.size()]))); localCA.executeCertificateRequest(createCSR(keyPair, "localhost", generalNames), new CertificateRequestCallback() { @Override public void onCreate(final Certificate cert, final Certificate rootCert) { if (BuildConfig.DEBUG) { mLogger.info("Generated server certificate"); } try { Certificate[] chain = { cert, rootCert }; setCertificate(chain, keyPair.getPrivate()); saveKeyStore(); if (BuildConfig.DEBUG) { mLogger.info("Saved server certificate"); } mSANs.add(new SAN(GeneralName.iPAddress, ipAddress)); callback.onSuccess(mKeyStore, cert, rootCert); } catch (Exception e) { mLogger.log(Level.SEVERE, "Failed to save server certificate", e); callback.onError(KeyStoreError.FAILED_BACKUP_KEYSTORE); } finally { localCA.dispose(); } } @Override public void onError() { mLogger.severe("Failed to generate server certificate"); localCA.dispose(); callback.onError(KeyStoreError.FAILED_BACKUP_KEYSTORE); } }); } } catch (KeyStoreException e) { callback.onError(KeyStoreError.BROKEN_KEYSTORE); } catch (GeneralSecurityException e) { callback.onError(KeyStoreError.UNSUPPORTED_CERTIFICATE_FORMAT); } } }); }
From source file:org.deviceconnect.android.ssl.EndPointKeyStoreManager.java
License:MIT License
/** * ??????./*from w w w . j ava 2 s. c o m*/ * * @param keyPair * @param commonName ? * @param generalNames SANs * @return ???? * @throws GeneralSecurityException ????? */ private static PKCS10CertificationRequest createCSR(final KeyPair keyPair, final String commonName, final GeneralNames generalNames) throws GeneralSecurityException { final String signatureAlgorithm = "SHA256WithRSAEncryption"; final X500Principal principal = new X500Principal( "CN=" + commonName + ", O=Device Connect Project, L=N/A, ST=N/A, C=JP"); DERSequence sanExtension = new DERSequence( new ASN1Encodable[] { X509Extensions.SubjectAlternativeName, new DEROctetString(generalNames) }); DERSet extensions = new DERSet(new DERSequence(sanExtension)); DERSequence extensionRequest = new DERSequence( new ASN1Encodable[] { PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensions }); DERSet attributes = new DERSet(extensionRequest); return new PKCS10CertificationRequest(signatureAlgorithm, principal, keyPair.getPublic(), attributes, keyPair.getPrivate()); }
From source file:org.ejbca.core.ejb.authentication.web.WebAuthenticationProviderSessionBeanTest.java
License:Open Source License
private static X509Certificate generateUnbornCert(String dn, String policyId, PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, IllegalStateException, NoSuchProviderException, OperatorCreationException, CertificateException, IOException { int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign; // Create self signed certificate Date firstDate = new Date(); // Set starting date to tomorrow firstDate.setTime(firstDate.getTime() + (24 * 3600 * 1000)); Date lastDate = new Date(); // Set Expiry in two days lastDate.setTime(lastDate.getTime() + ((2 * 24 * 60 * 60 * 1000))); // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be // a CVC public key that is passed as parameter PublicKey publicKey = null;/*from ww w . j a v a 2 s . c o m*/ if (pubKey instanceof RSAPublicKey) { RSAPublicKey rsapk = (RSAPublicKey) pubKey; RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent()); try { publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec); } catch (InvalidKeySpecException e) { publicKey = pubKey; } } else if (pubKey instanceof ECPublicKey) { ECPublicKey ecpk = (ECPublicKey) pubKey; try { ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA" publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec); } catch (InvalidKeySpecException e) { publicKey = pubKey; } catch (NullPointerException e) { publicKey = pubKey; } } else { publicKey = pubKey; } // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this // bean is created. byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(new Date().getTime()); random.nextBytes(serno); final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded())); X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(CertTools.stringToBcX500Name(dn), new java.math.BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(dn), pkinfo); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certbuilder.addExtension(Extension.basicConstraints, true, bc); // Put critical KeyUsage in CA-certificates if (isCA) { X509KeyUsage ku = new X509KeyUsage(keyusage); certbuilder.addExtension(Extension.keyUsage, true, ku); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox. try { if (isCA) { ASN1InputStream spkiAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); ASN1InputStream apkiAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); try { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) spkiAsn1InputStream.readObject()); X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils(); SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) apkiAsn1InputStream.readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski); certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki); } finally { spkiAsn1InputStream.close(); apkiAsn1InputStream.close(); } } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certbuilder.addExtension(Extension.certificatePolicies, false, seq); } final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA") .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(privKey), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded()); return selfcert; }
From source file:org.ejbca.core.ejb.ca.sign.SignSessionTest.java
License:Open Source License
public void test29TestExtensionOverride() 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 certificateProfileSession.removeCertificateProfile(admin, "TESTEXTENSIONOVERRIDE"); EndUserCertificateProfile certprof = new EndUserCertificateProfile(); // Default profile does not allow Extension override certprof.setValidity(298);/*from w w w .j av a2 s . c o m*/ certificateProfileSession.addCertificateProfile(admin, "TESTEXTENSIONOVERRIDE", certprof); int cprofile = certificateProfileSession.getCertificateProfileId(admin, "TESTEXTENSIONOVERRIDE"); // Create a good end entity profile (good enough), allowing multiple UPN // names endEntityProfileSession.removeEndEntityProfile(admin, "TESTEXTENSIONOVERRIDE"); 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(admin, "TESTEXTENSIONOVERRIDE", profile); int eeprofile = endEntityProfileSession.getEndEntityProfileId(admin, "TESTEXTENSIONOVERRIDE"); UserDataVO user = new UserDataVO("foo", "C=SE,CN=extoverride", rsacaid, null, "foo@anatom.nu", SecConst.USER_ENDUSER, eeprofile, cprofile, SecConst.TOKEN_SOFT_PEM, 0, null); user.setPassword("foo123"); user.setStatus(UserDataConstants.STATUS_NEW); // Change a user that we know... userAdminSession.changeUser(admin, 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); // AltNames // String[] namearray = altnames.split(","); GeneralNames san = CertTools.getGeneralNamesFromAltName(altnames); ByteArrayOutputStream extOut = new ByteArrayOutputStream(); DEROutputStream derOut = new DEROutputStream(extOut); try { derOut.writeObject(san); } catch (IOException e) { throw new IllegalArgumentException("error encoding value: " + e); } // Extension request attribute is a set of X509Extensions // ASN1EncodableVector x509extensions = new ASN1EncodableVector(); // An X509Extensions is a sequence of Extension which is a sequence of // {oid, X509Extension} // ASN1EncodableVector extvalue = new ASN1EncodableVector(); Vector<DERObjectIdentifier> oidvec = new Vector<DERObjectIdentifier>(); oidvec.add(X509Extensions.SubjectAlternativeName); Vector<X509Extension> valuevec = new Vector<X509Extension>(); valuevec.add(new X509Extension(false, new DEROctetString(extOut.toByteArray()))); X509Extensions exts = new X509Extensions(oidvec, valuevec); 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 = new PKCS10CertificationRequest("SHA1WithRSA", new X509Name("C=SE,CN=extoverride"), rsakeys.getPublic(), attributes, rsakeys.getPrivate()); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(req); dOut.close(); byte[] p10bytes = bOut.toByteArray(); // FileOutputStream fos = new FileOutputStream("/tmp/foo.der"); // fos.write(p10bytes); // fos.close(); PKCS10RequestMessage p10 = new PKCS10RequestMessage(p10bytes); p10.setUsername("foo"); p10.setPassword("foo123"); // See if the request message works... X509Extensions p10exts = p10.getRequestExtensions(); assertNotNull(p10exts); IResponseMessage resp = signSession.createCertificate(admin, p10, org.ejbca.core.protocol.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 c = cert.getSubjectAlternativeNames(); assertNull(c); // Change so that we allow override of validity time CertificateProfile prof = certificateProfileSession.getCertificateProfile(admin, cprofile); prof.setAllowExtensionOverride(true); certificateProfileSession.changeCertificateProfile(admin, "TESTEXTENSIONOVERRIDE", prof); userAdminSession.changeUser(admin, user, false); resp = signSession.createCertificate(admin, p10, org.ejbca.core.protocol.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)); }
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 ww w. j a v a 2s . c o 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.model.ca.caadmin.X509CA.java
License:Open Source License
/** Generate a list of Distribution points. * @param distPoints distribution points as String in semi column (';') separated format. * @return list of distribution points./* www . j av a2 s. c o m*/ */ private List<DistributionPoint> generateDistributionPoints(String distPoints) { if (distPoints == null) { distPoints = ""; } // Multiple CDPs are separated with the ';' sign Iterator<String> it = StringTools.splitURIs(distPoints).iterator(); ArrayList<DistributionPoint> result = new ArrayList<DistributionPoint>(); while (it.hasNext()) { String uri = (String) it.next(); GeneralName gn = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(uri)); if (log.isDebugEnabled()) { log.debug("Added CRL distpoint: " + uri); } ASN1EncodableVector vec = new ASN1EncodableVector(); vec.add(gn); GeneralNames gns = new GeneralNames(new DERSequence(vec)); DistributionPointName dpn = new DistributionPointName(0, gns); result.add(new DistributionPoint(dpn, null, null)); } return result; }
From source file:org.ejbca.core.model.ca.certextensions.BasicCertificateExtension.java
License:Open Source License
/** * This certificate extension implementations overrides this method as it * want to be able to return a byte[] with the extension value. Otherwise * the implementation could have been put in the getValue method as the * super class CertificateExtension has a default implementation for * getValueEncoded which calls getValue. * @see CertificateExtension#getValueEncoded(UserDataVO, CA, CertificateProfile, PublicKey, PublicKey) *///from w ww.j a v a 2s . co m @Override public byte[] getValueEncoded(UserDataVO userData, CA ca, CertificateProfile certProfile, PublicKey userPublicKey, PublicKey caPublicKey) throws CertificateExtensionException, CertificateExtentionConfigurationException { final byte[] result; String encoding = StringUtils.trim(getProperties().getProperty(PROPERTY_ENCODING)); String[] values = getValues(userData); if (log.isDebugEnabled()) { log.debug("Got extension values: " + Arrays.toString(values)); } if (values == null || values.length == 0) { throw new CertificateExtentionConfigurationException( intres.getLocalizedMessage("certext.basic.incorrectvalue", Integer.valueOf(getId()), getOID())); } if (encoding.equalsIgnoreCase(ENCODING_RAW)) { if (values.length > 1) { // nvalues can not be used together with encoding=RAW throw new CertificateExtentionConfigurationException( intres.getLocalizedMessage("certext.certextmissconfigured", Integer.valueOf(getId()))); } else { result = parseRaw(values[0]); } } else { if (values.length > 1) { ASN1EncodableVector ev = new ASN1EncodableVector(); for (String value : values) { DEREncodable derval = parseValue(encoding, value); ev.add(derval); } result = new DERSequence(ev).getDEREncoded(); } else { result = parseValue(encoding, values[0]).getDERObject().getDEREncoded(); } } return result; }
From source file:org.ejbca.core.model.ca.certextensions.BasicCertificateExtension.java
License:Open Source License
/** * Tries to read the hex-string as an DERObject. If it contains more than one DEREncodable object, return a DERSequence of the objects. *///ww w . ja va 2s . c om private DEREncodable parseHexEncodedDERObject(String value) throws CertificateExtentionConfigurationException { DEREncodable retval = null; if (value.matches("^\\p{XDigit}*")) { byte[] bytes = Hex.decode(value); try { ASN1InputStream ais = new ASN1InputStream(bytes); DEREncodable firstObject = ais.readObject(); if (ais.available() > 0) { ASN1EncodableVector ev = new ASN1EncodableVector(); ev.add(firstObject); while (ais.available() > 0) { ev.add(ais.readObject()); } retval = new DERSequence(ev); } else { retval = firstObject; } } catch (Exception e) { throw new CertificateExtentionConfigurationException(intres.getLocalizedMessage( "certext.basic.illegalvalue", value, Integer.valueOf(getId()), getOID())); } } else { throw new CertificateExtentionConfigurationException(intres .getLocalizedMessage("certext.basic.illegalvalue", value, Integer.valueOf(getId()), getOID())); } return retval; }
From source file:org.ejbca.core.model.ca.certextensions.standard.AuthorityInformationAccess.java
License:Open Source License
@Override public DEREncodable getValue(final UserDataVO subject, final CA ca, final CertificateProfile certProfile, final PublicKey userPublicKey, final PublicKey caPublicKey) throws CertificateExtentionConfigurationException, CertificateExtensionException { final ASN1EncodableVector accessList = new ASN1EncodableVector(); GeneralName accessLocation;//w w w . j av a2 s. c o m String url; // caIssuers final List<String> caIssuers = certProfile.getCaIssuers(); if (caIssuers != null) { for (final Iterator<String> it = caIssuers.iterator(); it.hasNext();) { url = it.next(); if (StringUtils.isNotEmpty(url)) { accessLocation = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(url)); accessList.add(new AccessDescription(AccessDescription.id_ad_caIssuers, accessLocation)); } } } // ocsp url final X509CA x509ca = (X509CA) ca; url = certProfile.getOCSPServiceLocatorURI(); if (certProfile.getUseDefaultOCSPServiceLocator()) { url = x509ca.getDefaultOCSPServiceLocator(); } if (StringUtils.isNotEmpty(url)) { accessLocation = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(url)); accessList.add(new AccessDescription(AccessDescription.id_ad_ocsp, accessLocation)); } org.bouncycastle.asn1.x509.AuthorityInformationAccess ret = null; if (accessList.size() > 0) { ret = new org.bouncycastle.asn1.x509.AuthorityInformationAccess(new DERSequence(accessList)); } if (ret == null) { log.error("AuthorityInformationAccess is used, but nor caIssuers not Ocsp url are defined!"); } return ret; }
From source file:org.ejbca.core.model.ca.certextensions.standard.AuthorityKeyIdentifier.java
License:Open Source License
@Override public DEREncodable getValue(final UserDataVO subject, final CA ca, final CertificateProfile certProfile, final PublicKey userPublicKey, final PublicKey caPublicKey) throws CertificateExtentionConfigurationException, CertificateExtensionException { org.bouncycastle.asn1.x509.AuthorityKeyIdentifier ret = null; // Default value is that we calculate it from scratch! // (If this is a root CA we must calculate the AuthorityKeyIdentifier from scratch) // (If the CA signing this cert does not have a SubjectKeyIdentifier we must calculate the AuthorityKeyIdentifier from scratch) try {// w ww . j av a2s .co m final byte[] keybytes = caPublicKey.getEncoded(); final SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(keybytes)).readObject()); ret = new org.bouncycastle.asn1.x509.AuthorityKeyIdentifier(apki); // If we have a CA-certificate (i.e. this is not a Root CA), we must take the authority key identifier from // the CA-certificates SubjectKeyIdentifier if it exists. If we don't do that we will get the wrong identifier if the // CA does not follow RFC3280 (guess if MS-CA follows RFC3280?) final X509Certificate cacert = (X509Certificate) ca.getCACertificate(); final boolean isRootCA = (certProfile.getType() == CertificateProfile.TYPE_ROOTCA); if ((cacert != null) && (!isRootCA)) { byte[] akibytes; akibytes = CertTools.getSubjectKeyId(cacert); if (akibytes != null) { // TODO: The code below is snipped from AuthorityKeyIdentifier.java in BC 1.36, because there is no method there // to set only a pre-computed key identifier // This should be replaced when such a method is added to BC final ASN1OctetString keyidentifier = new DEROctetString(akibytes); final ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new DERTaggedObject(false, 0, keyidentifier)); final ASN1Sequence seq = new DERSequence(v); ret = new org.bouncycastle.asn1.x509.AuthorityKeyIdentifier(seq); log.debug("Using AuthorityKeyIdentifier from CA-certificates SubjectKeyIdentifier."); } } } catch (IOException e) { throw new CertificateExtensionException("IOException parsing CA public key: " + e.getMessage(), e); } if (ret == null) { log.error("AuthorityKeyIdentifier is used, but no key identifier can be created!"); } return ret; }