List of usage examples for org.bouncycastle.asn1.x509 X509Extension X509Extension
public X509Extension(boolean critical, ASN1OctetString value)
From source file:bluecrystal.bcdeps.helper.DerEncoder.java
License:Open Source License
public static OCSPReq GenOcspReq(X509Certificate nextCert, X509Certificate nextIssuer) throws OCSPException { OCSPReqGenerator ocspRequestGenerator = new OCSPReqGenerator(); CertificateID certId = new CertificateID(CertificateID.HASH_SHA1, nextIssuer, nextCert.getSerialNumber()); ocspRequestGenerator.addRequest(certId); BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis()); Vector<DERObjectIdentifier> oids = new Vector<DERObjectIdentifier>(); Vector<X509Extension> values = new Vector<X509Extension>(); oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); values.add(new X509Extension(false, new DEROctetString(nonce.toByteArray()))); ocspRequestGenerator.setRequestExtensions(new X509Extensions(oids, values)); return ocspRequestGenerator.generate(); }
From source file:ch.bfh.unicert.certimport.CertificateIssuer.java
License:GNU General Public License
public Certificate createClientCertificate(IdentityData id, String keyStorePath, PublicKey pk, int validity, String applicationIdentifier, String[] roles, String uniBoardWsdlURL, String uniBoardServiceURL, String section) throws CertificateCreationException { X509Certificate caCert;/*from ww w . ja va 2 s . c o m*/ RSAPrivateCrtKey privKey; try { caCert = this.readIssuerCertificate(this.issuerId); privKey = this.readPrivateKey(this.issuerId, this.privKeyPass); } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) { logger.log(Level.SEVERE, null, ex); throw new CertificateCreationException("230 Could not create client certificate. Key error"); } RSAPrivateCrtKeyParameters cipherParams = this.createIssuerCipherParams(privKey); X509Certificate clientCert; Hashtable extension = new Hashtable(); extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier))); String completeRole = ""; for (String role : roles) { completeRole += role + ", "; } completeRole = completeRole.substring(0, completeRole.length() - 2); extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole))); extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider()))); Map<String, String> extensionMap = new HashMap(); if (id.getOtherValues() != null) { for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) { extension.put(new DERObjectIdentifier(entry.getKey().getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue()))); extensionMap.put(entry.getKey().getName(), entry.getValue()); } } try { String x509NameString = ""; x509NameString += "CN=" + id.getCommonName(); if (id.getSurname() != null && !id.getSurname().equals("")) { x509NameString += ", SURNAME=" + id.getSurname(); } if (id.getGivenName() != null && !id.getGivenName().equals("")) { x509NameString += ", GIVENNAME=" + id.getGivenName(); } if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) { x509NameString += ", UID=" + id.getUniqueIdentifier(); } if (id.getOrganisation() != null && !id.getOrganisation().equals("")) { x509NameString += ", O=" + id.getOrganisation(); } if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) { x509NameString += ", OU=" + id.getOrganisationUnit(); } if (id.getCountryName() != null && !id.getCountryName().equals("")) { x509NameString += ", C=" + id.getCountryName(); } if (id.getState() != null && !id.getState().equals("")) { x509NameString += ", ST=" + id.getState(); } if (id.getLocality() != null && !id.getLocality().equals("")) { x509NameString += ", L=" + id.getLocality(); } X509Name x509Name = new X509Name(x509NameString); V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator(); certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis()))); certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert)); certGen.setSubject(x509Name); certGen.setExtensions(new X509Extensions(extension)); DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5"); AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull()); certGen.setSignature(sigAlgId); certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject())); certGen.setStartDate(new Time(new Date(System.currentTimeMillis()))); certGen.setEndDate(new Time(getExpiryDate(validity).getTime())); TBSCertificateStructure tbsCert = certGen.generateTBSCertificate(); //Sign certificate SHA1Digest digester = new SHA1Digest(); AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine()); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(tbsCert); byte[] signature; byte[] certBlock = bOut.toByteArray(); // first create digest digester.update(certBlock, 0, certBlock.length); byte[] hash = new byte[digester.getDigestSize()]; digester.doFinal(hash, 0); // then sign it rsa.init(true, cipherParams); DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash); byte[] digest = dInfo.getEncoded(ASN1Encodable.DER); signature = rsa.processBlock(digest, 0, digest.length); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCert); v.add(sigAlgId); v.add(new DERBitString(signature)); // Create CRT data structure clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v))); clientCert.verify(caCert.getPublicKey()); } catch (IOException | InvalidCipherTextException | CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | SignatureException e) { logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() }); throw new CertificateCreationException("230 Could not create client certificate"); } Certificate cert = new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(), id.getOrganisation(), id.getOrganisationUnit(), id.getCountryName(), id.getState(), id.getLocality(), id.getSurname(), id.getGivenName(), applicationIdentifier, roles, id.getIdentityProvider(), extensionMap); //post message on UniBoard if corresponding JNDI parameter is defined postOnUniBoard(cert, uniBoardWsdlURL, uniBoardServiceURL, section, (RSAPublicKey) caCert.getPublicKey(), privKey); return cert; }
From source file:ch.bfh.unicert.issuer.CertificateIssuerBean.java
License:GNU General Public License
/** * Actually creates the requestor certificate. * * @param id requestor identity data//from w w w. ja v a 2 s . c om * @param caCert certificate of the certification authority * @param cipherParams issuer private key parameters used for signing * @param pk public key of the requestor to certify * @param expiry the expiry date * @param applicationIdentifier the application identifier for which te certificate is issued * @param role role for which the certificate is issued * @return the certificate object containing the X509 certificate * @throws CertificateCreationException if an error occurs */ private Certificate createClientCertificate(IdentityData id, X509Certificate caCert, CipherParameters cipherParams, PublicKey pk, Calendar expiry, String applicationIdentifier, String[] roles) throws CertificateCreationException { X509Certificate clientCert; Hashtable extension = new Hashtable(); extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier))); String completeRole = ""; for (String role : roles) { completeRole += role + ", "; } completeRole = completeRole.substring(0, completeRole.length() - 2); extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole))); extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider()))); Map<String, String> extensionMap = new HashMap(); if (id.getOtherValues() != null) { for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) { extension.put(new DERObjectIdentifier(entry.getKey().getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue()))); extensionMap.put(entry.getKey().getName(), entry.getValue()); } } try { String x509NameString = ""; x509NameString += "CN=" + id.getCommonName(); if (id.getSurname() != null && !id.getSurname().equals("")) { x509NameString += ", SURNAME=" + id.getSurname(); } if (id.getGivenName() != null && !id.getGivenName().equals("")) { x509NameString += ", GIVENNAME=" + id.getGivenName(); } if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) { x509NameString += ", UID=" + id.getUniqueIdentifier(); } if (id.getOrganisation() != null && !id.getOrganisation().equals("")) { x509NameString += ", O=" + id.getOrganisation(); } if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) { x509NameString += ", OU=" + id.getOrganisationUnit(); } if (id.getCountryName() != null && !id.getCountryName().equals("")) { x509NameString += ", C=" + id.getCountryName(); } if (id.getState() != null && !id.getState().equals("")) { x509NameString += ", ST=" + id.getState(); } if (id.getLocality() != null && !id.getLocality().equals("")) { x509NameString += ", L=" + id.getLocality(); } X509Name x509Name = new X509Name(x509NameString); V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator(); certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis()))); certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert)); certGen.setSubject(x509Name); certGen.setExtensions(new X509Extensions(extension)); DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5"); AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull()); certGen.setSignature(sigAlgId); certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject())); certGen.setStartDate(new Time(new Date(System.currentTimeMillis()))); certGen.setEndDate(new Time(expiry.getTime())); TBSCertificateStructure tbsCert = certGen.generateTBSCertificate(); //Sign certificate SHA1Digest digester = new SHA1Digest(); AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine()); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(tbsCert); byte[] signature; byte[] certBlock = bOut.toByteArray(); // first create digest digester.update(certBlock, 0, certBlock.length); byte[] hash = new byte[digester.getDigestSize()]; digester.doFinal(hash, 0); // then sign it rsa.init(true, cipherParams); DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash); byte[] digest = dInfo.getEncoded(ASN1Encodable.DER); signature = rsa.processBlock(digest, 0, digest.length); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCert); v.add(sigAlgId); v.add(new DERBitString(signature)); // Create CRT data structure clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v))); clientCert.verify(caCert.getPublicKey()); } catch (IOException | CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | InvalidCipherTextException | SignatureException e) { logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() }); throw new CertificateCreationException("230 Could not create client certificate"); } return new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(), id.getOrganisation(), id.getOrganisationUnit(), id.getCountryName(), id.getState(), id.getLocality(), id.getSurname(), id.getGivenName(), applicationIdentifier, roles, id.getIdentityProvider(), extensionMap); }
From source file:chapter6.PKCS10ExtensionExample.java
public static PKCS10CertificationRequest generateRequest(KeyPair pair) throws Exception { // Create a SubjectAlternativeName extension value GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test")); // Create the extensions object and add it as an attribute Vector oids = new Vector(); Vector values = new Vector(); oids.add(X509Extensions.SubjectAlternativeName); values.add(new X509Extension(false, new DEROctetString(subjectAltName))); X509Extensions extensions = new X509Extensions(oids, values); Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new DERSet(extensions)); return new PKCS10CertificationRequest("SHA256withRSA", new X500Principal("CN=Requested Test Certificate"), pair.getPublic(), new DERSet(attribute), pair.getPrivate()); }
From source file:chapter7.OCSPClientExample.java
/** * * @param issuerCert//from w w w.j av a2 s. c o m * @param serialNumber * @return * @throws OCSPException */ public static OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws OCSPException { //1.- Generate the id for the certificate we are looking for CertificateID id = new CertificateID(CertificateID.HASH_SHA1, issuerCert, serialNumber); //2.- Basic request generation with nonce OCSPReqGenerator gen = new OCSPReqGenerator(); gen.addRequest(id); //3.- Create details for nonce extension BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis()); Vector oids = new Vector(); Vector values = new Vector(); oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); values.add(new X509Extension(false, new DEROctetString(nonce.toByteArray()))); gen.setRequestExtensions(new X509Extensions(oids, values)); return gen.generate(); }
From source file:com.itextpdf.text.pdf.OcspClientBouncyCastle.java
License:Open Source License
/** * Generates an OCSP request using BouncyCastle. * @param issuerCert certificate of the issues * @param serialNumber serial number/* w w w . j av a 2 s . c o m*/ * @return an OCSP request * @throws OCSPException * @throws IOException */ private static OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws OCSPException, IOException { //Add provider BC Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); // Generate the id for the certificate we are looking for CertificateID id = new CertificateID(CertificateID.HASH_SHA1, issuerCert, serialNumber); // basic request generation with nonce OCSPReqGenerator gen = new OCSPReqGenerator(); gen.addRequest(id); // create details for nonce extension Vector<DERObjectIdentifier> oids = new Vector<DERObjectIdentifier>(); Vector<X509Extension> values = new Vector<X509Extension>(); oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); values.add(new X509Extension(false, new DEROctetString(new DEROctetString(PdfEncryption.createDocumentId()).getEncoded()))); gen.setRequestExtensions(new X509Extensions(oids, values)); return gen.generate(); }
From source file:com.spilowagie.text.pdf.OcspClientBouncyCastle.java
License:Mozilla Public License
/** * Generates an OCSP request using BouncyCastle. * @param issuerCert certificate of the issues * @param serialNumber serial number/* w ww . j a va2 s.c om*/ * @return an OCSP request * @throws OCSPException * @throws IOException */ private static OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws OCSPException, IOException { //Add provider BC Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); // Generate the id for the certificate we are looking for CertificateID id = new CertificateID(CertificateID.HASH_SHA1, issuerCert, serialNumber); // basic request generation with nonce OCSPReqGenerator gen = new OCSPReqGenerator(); gen.addRequest(id); // create details for nonce extension Vector oids = new Vector(); Vector values = new Vector(); oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); values.add(new X509Extension(false, new DEROctetString(new DEROctetString(PdfEncryption.createDocumentId()).getEncoded()))); gen.setRequestExtensions(new X509Extensions(oids, values)); return gen.generate(); }
From source file:com.viettel.hqmc.DAO.FilesDAO.java
private static OCSPReq generateOCSPRequest2(X509Certificate issuerCert, BigInteger serialNumber) throws Exception { //TODO: Have to check if this is OK with synapse implementation. //Add provider BC Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); CertificateID id = new CertificateID(CertificateID.HASH_SHA1, issuerCert, serialNumber); OCSPReqGenerator generator = new OCSPReqGenerator(); generator.addRequest(id);/*from w w w .j a v a 2 s .c o m*/ BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis()); Vector<ASN1ObjectIdentifier> objectIdentifiers = new Vector<ASN1ObjectIdentifier>(); Vector<X509Extension> values = new Vector<X509Extension>(); objectIdentifiers.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); values.add(new X509Extension(false, new DEROctetString(nonce.toByteArray()))); generator.setRequestExtensions(new X509Extensions(objectIdentifiers, values)); return generator.generate(); }
From source file:ee.sk.digidoc.factory.BouncyCastleNotaryFactory.java
License:Open Source License
/** * Creates a new OCSP request//from w w w . j ava 2 s . c o m * @param nonce 128 byte RSA+SHA1 signatures digest * Use null if you want to verify only the certificate * and this is not related to any signature * @param signersCert signature owners cert * @param caCert CA cert for this signer * @param bSigned flag signed request or not */ private OCSPReq createOCSPRequest(byte[] nonce, X509Certificate signersCert, X509Certificate caCert, boolean bSigned) throws DigiDocException { OCSPReq req = null; OCSPReqGenerator ocspRequest = new OCSPReqGenerator(); try { //Create certificate id, for OCSP request CertificateID certId = creatCertReq(signersCert, caCert); if (m_logger.isDebugEnabled()) m_logger.debug("Request for: " + certId.getHashAlgOID() + " serial: " + certId.getSerialNumber() + " issuer: " + Base64Util.encode(certId.getIssuerKeyHash()) + " subject: " + Base64Util.encode(certId.getIssuerNameHash())); ocspRequest.addRequest(certId); if (nonce != null) { ASN1OctetString ocset = new BERConstructedOctetString(nonce); X509Extension ext = new X509Extension(false, ocset); //nonce Identifier DERObjectIdentifier nonceIdf = new DERObjectIdentifier(nonceOid); Hashtable tbl = new Hashtable(1); tbl.put(nonceIdf, ext); // create extendions, with one extendion(NONCE) X509Extensions extensions = new X509Extensions(tbl); ocspRequest.setRequestExtensions(extensions); } //X509Name n = new X509Name() GeneralName name = null; if (bSigned) { if (m_logger.isDebugEnabled()) m_logger.debug("SignCert: " + ((m_signCert != null) ? m_signCert.toString() : "NULL")); name = new GeneralName(PrincipalUtil.getSubjectX509Principal(m_signCert)); } else { name = new GeneralName(PrincipalUtil.getSubjectX509Principal(signersCert)); // VS: Mihhails patch for accepting Hansa's cert /* Hashtable myLookUp=new Hashtable(X509Name.DefaultLookUp); DERObjectIdentifier SERIALNUMBER = new DERObjectIdentifier("2.5.4.5"); myLookUp.put(SERIALNUMBER, "SERIALNUMBER"); name = new GeneralName(new X509Name(X509Name.DefaultReverse, myLookUp,signersCert.getSubjectDN().toString())); */ } ocspRequest.setRequestorName(name); if (bSigned) { // lets generate signed request X509Certificate[] chain = { m_signCert }; req = ocspRequest.generate("SHA1WITHRSA", m_signKey, chain, "BC"); if (!req.verify(m_signCert.getPublicKey(), "BC")) { m_logger.error("Verify failed"); } } else { // unsigned request req = ocspRequest.generate(); } } catch (Exception ex) { DigiDocException.handleException(ex, DigiDocException.ERR_OCSP_REQ_CREATE); } return req; }
From source file:es.uji.security.crypto.openxades.digidoc.factory.BouncyCastleNotaryFactory.java
License:Open Source License
/** * Creates a new OCSP request//from w w w. j av a2 s. c o m * * @param nonce * 128 byte RSA+SHA1 signatures digest Use null if you want to verify only the * certificate and this is not related to any signature * @param signersCert * signature owners cert * @param caCert * CA cert for this signer * @param bSigned * flag signed request or not */ private OCSPReq createOCSPRequest(byte[] nonce, X509Certificate signersCert, X509Certificate caCert, boolean bSigned) throws DigiDocException { OCSPReq req = null; OCSPReqGenerator ocspRequest = new OCSPReqGenerator(); try { // Create certificate id, for OCSP request CertificateID certId = creatCertReq(signersCert, caCert); if (m_logger.isDebugEnabled()) m_logger.debug("Request for: " + certId.getHashAlgOID() + " serial: " + certId.getSerialNumber() + " issuer: " + Base64.encodeBytes(certId.getIssuerKeyHash()) + " subject: " + Base64.encodeBytes(certId.getIssuerNameHash())); ocspRequest.addRequest(certId); if (nonce != null) { ASN1OctetString ocset = new BERConstructedOctetString(nonce); X509Extension ext = new X509Extension(false, ocset); // nonce Identifier DERObjectIdentifier nonceIdf = new DERObjectIdentifier(nonceOid); Hashtable tbl = new Hashtable(1); tbl.put(nonceIdf, ext); // create extendions, with one extendion(NONCE) X509Extensions extensions = new X509Extensions(tbl); ocspRequest.setRequestExtensions(extensions); } // X509Name n = new X509Name() GeneralName name = null; if (bSigned) { if (m_logger.isDebugEnabled()) m_logger.debug("SignCert: " + ((m_signCert != null) ? m_signCert.toString() : "NULL")); name = new GeneralName(PrincipalUtil.getSubjectX509Principal(m_signCert)); } else { name = new GeneralName(PrincipalUtil.getSubjectX509Principal(signersCert)); // VS: Mihhails patch for accepting Hansa's cert /* * Hashtable myLookUp=new Hashtable(X509Name.DefaultLookUp); DERObjectIdentifier * SERIALNUMBER = new DERObjectIdentifier("2.5.4.5"); myLookUp.put(SERIALNUMBER, * "SERIALNUMBER"); name = new GeneralName(new X509Name(X509Name.DefaultReverse, * myLookUp,signersCert.getSubjectDN().toString())); */ } ocspRequest.setRequestorName(name); if (bSigned) { // lets generate signed request X509Certificate[] chain = { m_signCert }; req = ocspRequest.generate("SHA1WITHRSA", m_signKey, chain, "BC"); if (!req.verify(m_signCert.getPublicKey(), "BC")) { m_logger.error("Verify failed"); } } else { // unsigned request req = ocspRequest.generate(); } } catch (Exception e) { DigiDocException.handleException(e, DigiDocException.ERR_OCSP_REQ_CREATE); } return req; }