List of usage examples for org.bouncycastle.jce PrincipalUtil getSubjectX509Principal
public static X509Principal getSubjectX509Principal(X509Certificate cert) throws CertificateEncodingException
From source file:be.fedict.trust.service.bean.CertificateAuthorityLookupBean.java
License:Open Source License
private void refreshLookupMap() throws CertificateEncodingException, NoSuchAlgorithmException { LOG.debug("refreshing lookup map"); List<CertificateAuthorityEntity> activeCertificateAuthorities = this.certificateAuthorityDAO .listActiveCertificateAuthorities(); Map<String, String> freshLookupMap = new HashMap<String, String>(); for (CertificateAuthorityEntity certificateAuthority : activeCertificateAuthorities) { X509Certificate caCert = certificateAuthority.getCertificate(); X509Principal issuerName = PrincipalUtil.getSubjectX509Principal(caCert); byte[] issuerNameHash = getHash(issuerName.getEncoded()); String caNameHashKey = Hex.encodeHexString(issuerNameHash); String caName = caCert.getSubjectX500Principal().toString(); freshLookupMap.put(caNameHashKey, caName); LOG.debug("lookup entry: " + caNameHashKey + " = " + caName); }//w w w . j a v a2s . co m this.lookupMap = freshLookupMap; // concurrency is no problem here }
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 www .ja v a2 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. j av a 2 s . c o m*/ * @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:com.github.drrb.surefiresplitter.go.ssl.Entity.java
License:Open Source License
private Entity(KeyPair keyPair, X509Certificate certificate, List<Certificate> chain) throws Exception { this.keyPair = keyPair; this.certificate = certificate; this.chain = chain; this.principal = PrincipalUtil.getSubjectX509Principal(certificate); }
From source file:com.viettel.voffice.ca.uds.X509ExtensionUtil.java
License:Open Source License
/** * Get subject of certificate//from w w w. java 2 s . co m * * @param certificate X509Certificate * @return <CODE>String</CODE> name of subject or empty <CODE>String</CODE> */ public static String getSubject(X509Certificate certificate) { try { X509Principal principal = PrincipalUtil.getSubjectX509Principal(certificate); Vector vector = principal.getValues(X509Principal.CN); if (vector.size() != 1) { return ""; } return vector.firstElement().toString(); } catch (CertificateEncodingException ex) { LogUtil.addLog(ex);//binhnt sonar a160901 return ""; } }
From source file:com.viettel.voffice.ca.uds.X509ExtensionUtil.java
License:Open Source License
/** * Get organization of certificate// w w w . ja va 2s . c o m * * @param certificate X509Certificate * @return <CODE>String</CODE> name of subject or empty <CODE>String</CODE> */ public static String getOrganization(X509Certificate certificate) { try { X509Principal principal = PrincipalUtil.getSubjectX509Principal(certificate); Vector vector = principal.getValues(X509Principal.O); if (vector.size() != 1) { return ""; } return vector.firstElement().toString(); } catch (CertificateEncodingException ex) { LogUtil.addLog(ex);//binhnt sonar a160901 return ""; } }
From source file:com.viettel.voffice.ca.uds.X509ExtensionUtil.java
License:Open Source License
/** * Get unit of certificate/*ww w . ja va 2 s. com*/ * * @param certificate X509Certificate * @return <CODE>String</CODE> name of subject or empty <CODE>String</CODE> */ public static String getOrganizationUnit(X509Certificate certificate) { try { X509Principal principal = PrincipalUtil.getSubjectX509Principal(certificate); Vector vector = principal.getValues(X509Principal.OU); if (vector.size() != 1) { return ""; } return vector.firstElement().toString(); } catch (CertificateEncodingException ex) { LogUtil.addLog(ex);//binhnt sonar a160901 return ""; } }
From source file:com.viettel.voffice.ca.uds.X509ExtensionUtil.java
License:Open Source License
/** * Get location of certificate/*from ww w. j a v a 2 s . c om*/ * * @param certificate X509Certificate * @return <CODE>String</CODE> name of subject or empty <CODE>String</CODE> */ public static String getLocation(X509Certificate certificate) { try { X509Principal principal = PrincipalUtil.getSubjectX509Principal(certificate); Vector vector = principal.getValues(X509Principal.L); if (vector.size() != 1) { return ""; } return vector.firstElement().toString(); } catch (CertificateEncodingException ex) { LogUtil.addLog(ex);//binhnt sonar a160901 return ""; } }
From source file:ee.sk.digidoc.factory.BouncyCastleNotaryFactory.java
License:Open Source License
/** * Method for creating CertificateID for OCSP request * @param signersCert/*from w w w.j a v a 2 s .c o m*/ * @param caCert * @param provider * @return * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws CertificateEncodingException */ private CertificateID creatCertReq(X509Certificate signersCert, X509Certificate caCert) throws NoSuchAlgorithmException, NoSuchProviderException, CertificateEncodingException, DigiDocException { // TODO: checks this OID !!! MessageDigest digest = MessageDigest.getInstance("1.3.14.3.2.26", "BC"); if (m_logger.isDebugEnabled()) m_logger.debug("CA cert: " + ((caCert != null) ? caCert.toString() : "NULL")); X509Principal issuerName = PrincipalUtil.getSubjectX509Principal(caCert); if (m_logger.isDebugEnabled()) m_logger.debug("CA issuer: " + ((issuerName != null) ? issuerName.getName() : "NULL")); //Issuer name hash digest.update(issuerName.getEncoded()); ASN1OctetString issuerNameHash = new BERConstructedOctetString(digest.digest()); //Issuer key hash will be readed out from X509extendions // 4 first bytes are not useful for me, oid 2.5.29.15 contains keyid byte[] arr = caCert.getExtensionValue("2.5.29.14"); if (m_logger.isDebugEnabled()) m_logger.debug("Issuer key hash: " + ((arr != null) ? arr.length : 0)); if (arr == null || arr.length == 0) throw new DigiDocException(DigiDocException.ERR_CA_CERT_READ, "CA certificate has no SubjectKeyIdentifier extension!", null); byte[] arr2 = new byte[arr.length - 4]; System.arraycopy(arr, 4, arr2, 0, arr2.length); ASN1OctetString issuerKeyHash = new BERConstructedOctetString(arr2); CertID cerid = new CertID(new AlgorithmIdentifier("1.3.14.3.2.26"), issuerNameHash, issuerKeyHash, new DERInteger(signersCert.getSerialNumber())); return new CertificateID(cerid); }
From source file:ee.sk.digidoc.factory.BouncyCastleNotaryFactory.java
License:Open Source License
/** * Creates a new OCSP request//w w w .ja v a 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; }