List of usage examples for org.bouncycastle.jce.provider X509CertificateObject X509CertificateObject
public X509CertificateObject(org.bouncycastle.asn1.x509.Certificate c) throws CertificateParsingException
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 .j a v a2s.c om*/ 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 a v 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:de.rub.nds.tlsattacker.tls.protocol.handshake.CertificateHandler.java
License:Apache License
@Override public byte[] prepareMessageAction() { try {/*from ww w . j a v a 2 s . c om*/ // todo try to find a better solution for converting sun -> bc // certificates String alias = tlsContext.getAlias(); java.security.cert.Certificate sunCert = tlsContext.getKeyStore().getCertificate(alias); if (alias == null || sunCert == null) { throw new ConfigurationException("The certificate cannot be fetched. Have you provided correct " + "certificate alias and key? (Current alias: " + alias + ")"); } byte[] certBytes = sunCert.getEncoded(); ASN1Primitive asn1Cert = TlsUtils.readDERObject(certBytes); org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate .getInstance(asn1Cert); org.bouncycastle.asn1.x509.Certificate[] certs = new org.bouncycastle.asn1.x509.Certificate[1]; certs[0] = cert; Certificate tlsCerts = new Certificate(certs); X509CertificateObject x509CertObject = new X509CertificateObject(tlsCerts.getCertificateAt(0)); protocolMessage.setX509CertificateObject(x509CertObject); if (protocolMessage.getMessageIssuer() == ConnectionEnd.SERVER) { tlsContext.setServerCertificate(tlsCerts.getCertificateAt(0)); tlsContext.setX509ServerCertificateObject(x509CertObject); } else { tlsContext.setClientCertificate(tlsCerts.getCertificateAt(0)); tlsContext.setX509ClientCertificateObject(x509CertObject); } ByteArrayOutputStream tlsCertBos = new ByteArrayOutputStream(); tlsCerts.encode(tlsCertBos); protocolMessage.setX509CertificateBytes(tlsCertBos.toByteArray()); // byte[] x509CertBytes = x509CertObject.getEncoded(); protocolMessage.setCertificatesLength(protocolMessage.getX509CertificateBytes().getValue().length - HandshakeByteLength.CERTIFICATES_LENGTH); // protocolMessage.setLength(protocolMessage.getCertificatesLength().getValue() // + HandshakeByteLength.CERTIFICATES_LENGTH); // BC implicitly includes the certificates length of all the // certificates, so we only need to set the protocol message length protocolMessage.setLength(protocolMessage.getX509CertificateBytes().getValue().length); byte[] result = protocolMessage.getX509CertificateBytes().getValue(); long header = (protocolMessage.getHandshakeMessageType().getValue() << 24) + protocolMessage.getLength().getValue(); protocolMessage.setCompleteResultingMessage( ArrayConverter.concatenate(ArrayConverter.longToUint32Bytes(header), result)); return protocolMessage.getCompleteResultingMessage().getValue(); } catch (KeyStoreException | CertificateEncodingException | IOException | CertificateParsingException ex) { throw new ConfigurationException("Certificate with the selected alias could not be found", ex); } }
From source file:de.rub.nds.tlsattacker.tls.protocol.handshake.CertificateHandler.java
License:Apache License
@Override public int parseMessageAction(byte[] message, int pointer) { if (message[pointer] != HandshakeMessageType.CERTIFICATE.getValue()) { throw new InvalidMessageTypeException("This is not a certificate message"); }/*from w w w .j a v a2 s . co m*/ protocolMessage.setType(message[pointer]); int currentPointer = pointer + HandshakeByteLength.MESSAGE_TYPE; int nextPointer = currentPointer + HandshakeByteLength.MESSAGE_TYPE_LENGTH; int length = ArrayConverter.bytesToInt(Arrays.copyOfRange(message, currentPointer, nextPointer)); protocolMessage.setLength(length); currentPointer = nextPointer; nextPointer = currentPointer + HandshakeByteLength.CERTIFICATES_LENGTH; int certificatesLength = ArrayConverter .bytesToInt(Arrays.copyOfRange(message, currentPointer, nextPointer)); protocolMessage.setCertificatesLength(certificatesLength); try { Certificate tlsCerts = Certificate.parse(new ByteArrayInputStream(message, currentPointer, protocolMessage.getCertificatesLength().getValue() + HandshakeByteLength.CERTIFICATES_LENGTH)); X509CertificateObject x509CertObject = new X509CertificateObject(tlsCerts.getCertificateAt(0)); protocolMessage.setX509CertificateObject(x509CertObject); if (protocolMessage.getMessageIssuer() == ConnectionEnd.SERVER) { tlsContext.setServerCertificate(tlsCerts.getCertificateAt(0)); tlsContext.setX509ServerCertificateObject(x509CertObject); } else { tlsContext.setClientCertificate(tlsCerts.getCertificateAt(0)); tlsContext.setX509ClientCertificateObject(x509CertObject); } } catch (IOException | CertificateParsingException ex) { throw new WorkflowExecutionException(ex.getLocalizedMessage(), ex); } nextPointer = nextPointer + protocolMessage.getCertificatesLength().getValue(); protocolMessage.setCompleteResultingMessage(Arrays.copyOfRange(message, pointer, nextPointer)); return nextPointer; }
From source file:de.rub.nds.tlsattacker.tls.protocol.handshake.RSAClientKeyExchangeHandlerTest.java
License:Apache License
public RSAClientKeyExchangeHandlerTest() { // ECC does not work properly in the NSS provider Security.removeProvider("SunPKCS11-NSS"); Security.addProvider(new BouncyCastleProvider()); tlsContext = new TlsContext(); tlsContext.setSelectedCipherSuite(CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA); tlsContext.setClientRandom(clientRandom); tlsContext.setServerRandom(serverRandom); try {/*from w w w . j a v a2s . c o m*/ KeyStore ks = KeystoreHandler.loadKeyStore("../resources/rsa1024.jks", "password"); tlsContext.setKeyStore(ks); tlsContext.setAlias("alias"); tlsContext.setPassword("password"); } catch (CertificateException | KeyStoreException | IOException | NoSuchAlgorithmException ex) { throw new ConfigurationException( "Something went wrong loading key from Keystore or decrypting Premastersecret", ex); } try { String alias = tlsContext.getAlias(); java.security.cert.Certificate sunCert = tlsContext.getKeyStore().getCertificate(alias); if (alias == null || sunCert == null) { throw new ConfigurationException("The certificate cannot be fetched. Have you provided correct " + "certificate alias and key? (Current alias: " + alias + ")"); } byte[] certBytes = sunCert.getEncoded(); ASN1Primitive asn1Cert = TlsUtils.readDERObject(certBytes); org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate .getInstance(asn1Cert); org.bouncycastle.asn1.x509.Certificate[] certs = new org.bouncycastle.asn1.x509.Certificate[1]; certs[0] = cert; Certificate tlsCerts = new Certificate(certs); X509CertificateObject x509CertObject = new X509CertificateObject(tlsCerts.getCertificateAt(0)); tlsContext.setServerCertificate(tlsCerts.getCertificateAt(0)); tlsContext.setX509ServerCertificateObject(x509CertObject); } catch (KeyStoreException | CertificateEncodingException | IOException | CertificateParsingException ex) { throw new ConfigurationException("Certificate with the selected alias could not be found", ex); } handler = new RSAClientKeyExchangeHandler(tlsContext); }
From source file:eu.europa.ec.markt.dss.DSSASN1Utils.java
License:Open Source License
/** * This method return {@code X509Certificate} representing {@code X509CertificateHolder}. The {@code CertificateParsingException} is transformed in {@code * DSSException}./* ww w . j av a 2 s . c o m*/ * * @param certificateHolder {@code X509CertificateHolder} * @return {@code X509Certificate}. * @throws DSSException */ public static X509Certificate getCertificate(final X509CertificateHolder certificateHolder) throws DSSException { try { final X509Certificate certificate = new X509CertificateObject(certificateHolder.toASN1Structure()); return certificate; } catch (CertificateParsingException e) { throw new DSSException(e); } }
From source file:eu.europa.ec.markt.dss.DSSUtils.java
License:Open Source License
public static X509Certificate getCertificate(final X509CertificateHolder x509CertificateHolder) { try {/*from w w w .j a v a2 s . c o m*/ final Certificate certificate = x509CertificateHolder.toASN1Structure(); final X509CertificateObject x509CertificateObject = new X509CertificateObject(certificate); return x509CertificateObject; } catch (CertificateParsingException e) { throw new DSSException(e); } }
From source file:eu.europa.ec.markt.dss.validation.cades.CAdESCertificateSource.java
License:Open Source License
@Override @SuppressWarnings("unchecked") public List<X509Certificate> getCertificates() { List<X509Certificate> list = new ArrayList<X509Certificate>(); try {//from www . j av a2s. c o m if (!onlyExtended) { LOG.fine(cmsSignedData.getCertificates().getMatches(null).size() + " certificate in collection"); for (X509CertificateHolder ch : (Collection<X509CertificateHolder>) cmsSignedData.getCertificates() .getMatches(null)) { X509Certificate c = new X509CertificateObject(ch.toASN1Structure()); LOG.fine("Certificate for subject " + c.getSubjectX500Principal()); if (!list.contains(c)) { list.add(c); } } } // Add certificates in CAdES-XL certificate-values inside SignerInfo attribute if present SignerInformation si = cmsSignedData.getSignerInfos().get(signerId); if (si != null && si.getUnsignedAttributes() != null && si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_certValues) != null) { DERSequence seq = (DERSequence) si.getUnsignedAttributes() .get(PKCSObjectIdentifiers.id_aa_ets_certValues).getAttrValues().getObjectAt(0); for (int i = 0; i < seq.size(); i++) { X509CertificateStructure cs = X509CertificateStructure.getInstance(seq.getObjectAt(i)); X509Certificate c = new X509CertificateObject(cs); if (!list.contains(c)) { list.add(c); } } } } catch (CertificateParsingException e) { throw new RuntimeException(e); } catch (StoreException e) { throw new RuntimeException(e); } return list; }
From source file:eu.europa.ec.markt.dss.validation102853.CAdESCertificateSource.java
License:Open Source License
/** * @throws eu.europa.ec.markt.dss.exception.DSSException * *///from ww w .jav a 2 s .co m private ArrayList<CertificateToken> extractEncapsulatedCertificates() throws DSSException { final ArrayList<CertificateToken> encapsulatedCerts = new ArrayList<CertificateToken>(); try { // Gets certificates from CAdES-XL certificate-values inside SignerInfo attribute if present if (signerInformation != null && signerInformation.getUnsignedAttributes() != null) { final Attribute attr = signerInformation.getUnsignedAttributes() .get(PKCSObjectIdentifiers.id_aa_ets_certValues); if (attr != null) { final ASN1Sequence seq = (ASN1Sequence) attr.getAttrValues().getObjectAt(0); for (int ii = 0; ii < seq.size(); ii++) { final Certificate cs = Certificate.getInstance(seq.getObjectAt(ii)); final X509Certificate cert = new X509CertificateObject(cs); final CertificateToken certToken = addCertificate(cert); if (!encapsulatedCerts.contains(certToken)) { encapsulatedCerts.add(certToken); } } } } //TODO (cades): Read UnsignedAttribute: S/MIME Authenticated Attributes {iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) aa(2) id-aa-ets-CertificateRefs(21)} //TODO (cades): Read certificates from inner timestamps (signature timestamps and archive timestamps) ? } catch (CertificateParsingException e) { throw new DSSException(e); } return encapsulatedCerts; }
From source file:eu.europa.esig.dss.DSSASN1Utils.java
License:Open Source License
public static CertificateToken getCertificate(final X509CertificateHolder x509CertificateHolder) { try {/*w w w . j a va 2 s . c o m*/ final Certificate certificate = x509CertificateHolder.toASN1Structure(); final X509CertificateObject x509CertificateObject = new X509CertificateObject(certificate); return new CertificateToken(x509CertificateObject); } catch (CertificateParsingException e) { throw new DSSException(e); } }