List of usage examples for java.security.cert CertificateFactory generateCertificate
public final Certificate generateCertificate(InputStream inStream) throws CertificateException
From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java
private Boolean isValidSignature(String tokenString, byte[] signature) { Boolean isValid = false;//from w w w . j a va 2 s . co m File lterCert = ConfigurationListener.getLterCertificate(); try { FileInputStream certFis = new FileInputStream(lterCert); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(certFis); PublicKey pubKey = cert.getPublicKey(); Signature sig = Signature.getInstance("MD5withRSA"); sig.initVerify(pubKey); sig.update(tokenString.getBytes()); isValid = sig.verify(signature); } catch (FileNotFoundException e) { logger.error("Gatekeeper.validateSignature :" + e.getMessage()); e.printStackTrace(); } catch (CertificateException e) { logger.error("Gatekeeper.validateSignature :" + e.getMessage()); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { logger.error("Gatekeeper.validateSignature :" + e.getMessage()); e.printStackTrace(); } catch (InvalidKeyException e) { logger.error("Gatekeeper.validateSignature :" + e.getMessage()); e.printStackTrace(); } catch (SignatureException e) { logger.error("Gatekeeper.validateSignature :" + e.getMessage()); e.printStackTrace(); } return isValid; }
From source file:org.wso2.carbon.identity.certificateauthority.endpoint.scep.ScepEndpoint.java
private Response pkiOperation(int tenantId, HttpServletRequest request) { try {//from www . j a v a 2 s . c om byte[] body = getMessageBytes(request); CMSSignedData sd = new CMSSignedData(body); Store reqStore = sd.getCertificates(); Collection<X509CertificateHolder> reqCerts = reqStore.getMatches(null); CertificateFactory factory = CertificateFactory.getInstance("X.509"); X509CertificateHolder holder = reqCerts.iterator().next(); ByteArrayInputStream bais = new ByteArrayInputStream(holder.getEncoded()); X509Certificate reqCert = (X509Certificate) factory.generateCertificate(bais); PkcsPkiEnvelopeDecoder envDecoder = new PkcsPkiEnvelopeDecoder(getRecipient(tenantId), getRecipientKey(tenantId)); PkiMessageDecoder decoder = new PkiMessageDecoder(reqCert, envDecoder); PkiMessage<?> msg = decoder.decode(sd); MessageType msgType = msg.getMessageType(); Object msgData = msg.getMessageData(); Nonce senderNonce = Nonce.nextNonce(); TransactionId transId = msg.getTransactionId(); Nonce recipientNonce = msg.getSenderNonce(); CertRep certRep; if (msgType == MessageType.GET_CERT) { final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData; final X509Name principal = iasn.getName(); final BigInteger serial = iasn.getSerialNumber().getValue(); List<X509Certificate> issued = doGetCert(principal, serial); if (issued.size() == 0) { certRep = new CertRep(transId, senderNonce, recipientNonce, FailInfo.badCertId); } else { CMSSignedData messageData = getMessageData(issued); certRep = new CertRep(transId, senderNonce, recipientNonce, messageData); } } else if (msgType == MessageType.GET_CERT_INITIAL) { final IssuerAndSubject ias = (IssuerAndSubject) msgData; final X500Name issuer = X500Name.getInstance(ias.getIssuer()); final X500Name subject = X500Name.getInstance(ias.getSubject()); try { List<X509Certificate> issued = doGetCertInitial(tenantId, issuer, subject, transId); if (issued.size() == 0) { certRep = new CertRep(transId, senderNonce, recipientNonce); } else { CMSSignedData messageData = getMessageData(issued); certRep = new CertRep(transId, senderNonce, recipientNonce, messageData); } } catch (Exception e) { throw new ServletException(e); } } else if (msgType == MessageType.GET_CRL) { final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData; final X509Name issuer = iasn.getName(); final BigInteger serialNumber = iasn.getSerialNumber().getValue(); try { CMSSignedData messageData = getMessageData(doGetCrl(tenantId, issuer, serialNumber)); certRep = new CertRep(transId, senderNonce, recipientNonce, messageData); } catch (Exception e) { throw new ServletException(e); } } else if (msgType == MessageType.PKCS_REQ) { final PKCS10CertificationRequest certReq = (PKCS10CertificationRequest) msgData; try { List<X509Certificate> issued = doEnrol(certReq, transId, tenantId); if (issued.size() == 0) { certRep = new CertRep(transId, senderNonce, recipientNonce); } else { CMSSignedData messageData = getMessageData(issued); certRep = new CertRep(transId, senderNonce, recipientNonce, messageData); } } catch (Exception e) { throw new ServletException(e); } } else { log.error("Unknown message for operation"); return ResponseUtils.badRequest("Unknown message for operation"); } PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder(reqCert, "DESede"); PkiMessageEncoder encoder = new PkiMessageEncoder(getSignerKey(tenantId), getSigner(tenantId), envEncoder); CMSSignedData signedData = encoder.encode(certRep); return Response.ok().type("application/x-pki-message").entity(signedData.getEncoded()).build(); } catch (Exception e) { log.error(e); return ResponseUtils.serverError(); } }
From source file:uk.ac.cam.ucs.webauth.RavenFilter.java
/** * Gets a KeyStore and initialises if necessary. * /* ww w . j a v a2 s. c om*/ * The caller should ensure the KeyStore is persisted to a safe place. * * @return An initialised KeyStore */ protected KeyStore getKeyStore() { // init a new keystore with the Raven certificate, KeyStore keyStore; try { keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, new char[] {}); // Null InputStream, no password CertificateFactory factory = CertificateFactory.getInstance("X.509"); Certificate cert = factory.generateCertificate(new FileInputStream(sCertRealPath)); keyStore.setCertificateEntry(DEFAULT_KEYNAME, cert); } catch (KeyStoreException e) { log.error("Unable to setup KeyStore", e); throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { log.error("Unable to find crypto algorithm.", e); throw new RuntimeException(e); } catch (CertificateException e) { log.error("Unable to load certificate.", e); throw new RuntimeException(e); } catch (FileNotFoundException e) { log.error("Unable to load certificate file: " + sCertRealPath, e); throw new RuntimeException(e); } catch (IOException e) { log.error("General IO problem. Unable to initialised filter.", e); throw new RuntimeException(e); } return keyStore; }
From source file:XmldapCertsAndKeys.java
public static X509Certificate getXmldapCert1() throws CertificateException { byte[] certBytes = Base64.decode(cert1B64); CertificateFactory cf = CertificateFactory.getInstance("X509"); ByteArrayInputStream inStream = new ByteArrayInputStream(certBytes); return (X509Certificate) cf.generateCertificate(inStream); }
From source file:de.sub.goobi.helper.ldap.Ldap.java
private void loadCertificates(String path, String passwd) { /* wenn die Zertifikate noch nicht im Keystore sind, jetzt einlesen */ File myPfad = new File(path); if (!myPfad.exists()) { try (FileOutputStream ksos = (FileOutputStream) serviceManager.getFileService().write(myPfad.toURI()); // TODO: Rename parameters to something more meaningful, // this is quite specific for the GDZ FileInputStream cacertFile = new FileInputStream(ConfigCore.getParameter("ldap_cert_root")); FileInputStream certFile2 = new FileInputStream(ConfigCore.getParameter("ldap_cert_pdc"))) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cacert = (X509Certificate) cf.generateCertificate(cacertFile); X509Certificate servercert = (X509Certificate) cf.generateCertificate(certFile2); KeyStore ks = KeyStore.getInstance("jks"); char[] password = passwd.toCharArray(); // TODO: Let this method really load a keystore if configured // initialize the keystore, if file is available, load the // keystore ks.load(null);//from w w w . j ava 2 s . c om ks.setCertificateEntry("ROOTCERT", cacert); ks.setCertificateEntry("PDC", servercert); ks.store(ksos, password); } catch (Exception e) { logger.error(e); } } }
From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java
/** * To validate the current certificate and alias. * * @param alias Alias of the certificate. * @param certificate Bas64 endcoded certificated. * @return response code based on the validation *//*from w w w. j a v a2s. co m*/ public ResponseCode validateCertificate(String alias, int tenantId, String certificate) { File trustStoreFile = new File(TRUST_STORE); ResponseCode responseCode = ResponseCode.SUCCESS; ByteArrayInputStream serverCert = null; try { localTrustStoreStream = new FileInputStream(trustStoreFile); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD); if (StringUtils.isNotEmpty(alias) && trustStore.containsAlias(alias + "_" + tenantId)) { responseCode = ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE; } if (responseCode != ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE) { byte[] cert = (Base64.decodeBase64(certificate.getBytes(StandardCharsets.UTF_8))); serverCert = new ByteArrayInputStream(cert); if (serverCert.available() == 0) { responseCode = ResponseCode.CERTIFICATE_NOT_FOUND; } else { CertificateFactory cf = CertificateFactory.getInstance(CERTIFICATE_TYPE); while (serverCert.available() > 0) { Certificate generatedCertificate = cf.generateCertificate(serverCert); X509Certificate x509Certificate = (X509Certificate) generatedCertificate; if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) { responseCode = ResponseCode.CERTIFICATE_EXPIRED; } } } } } catch (IOException e) { log.error("I/O Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (CertificateException e) { log.error("Certificate Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (NoSuchAlgorithmException e) { log.error("No Such Algorithm Exception while trying to load trust store while trying to check whether " + "alias " + alias + " exists", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (KeyStoreException e) { log.error("KeyStore Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } finally { closeStreams(serverCert); } return responseCode; }
From source file:org.kitodo.services.data.LdapServerService.java
private void loadCertificates(String path, String passwd, LdapServer ldapServer) { /* wenn die Zertifikate noch nicht im Keystore sind, jetzt einlesen */ File myPfad = new File(path); if (!myPfad.exists()) { try (FileOutputStream ksos = (FileOutputStream) serviceManager.getFileService().write(myPfad.toURI()); // TODO: Rename parameters to something more meaningful, // this is quite specific for the GDZ FileInputStream cacertFile = new FileInputStream(ldapServer.getRootCertificate()); FileInputStream certFile2 = new FileInputStream(ldapServer.getPdcCertificate())) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cacert = (X509Certificate) cf.generateCertificate(cacertFile); X509Certificate servercert = (X509Certificate) cf.generateCertificate(certFile2); KeyStore ks = KeyStore.getInstance("jks"); char[] password = passwd.toCharArray(); // TODO: Let this method really load a keystore if configured // initialize the keystore, if file is available, load the // keystore ks.load(null);// w ww .j av a 2s . c o m ks.setCertificateEntry("ROOTCERT", cacert); ks.setCertificateEntry("PDC", servercert); ks.store(ksos, password); } catch (IOException | CertificateException | KeyStoreException | NoSuchAlgorithmException | RuntimeException e) { logger.error(e.getMessage(), e); } } }
From source file:eu.europa.ec.markt.dss.validation.xades.XAdESCertificateSource.java
@Override public List<X509Certificate> getCertificates() { List<X509Certificate> list = new ArrayList<X509Certificate>(); try {//from w ww . j ava2 s . c om CertificateFactory factory = CertificateFactory.getInstance("X509"); NodeList nodeList2 = (NodeList) XMLUtils.getNodeList(signatureElement, "ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties/xades:CertificateValues/xades:EncapsulatedX509Certificate"); for (int i = 0; i < nodeList2.getLength(); i++) { Element certEl = (Element) nodeList2.item(i); byte[] derEncoded = Base64.decodeBase64(certEl.getTextContent()); X509Certificate cert = (X509Certificate) factory .generateCertificate(new ByteArrayInputStream(derEncoded)); if (!list.contains(cert)) { list.add(cert); } } if (!onlyExtended) { NodeList nodeList = (NodeList) XMLUtils.getNodeList(signatureElement, "ds:KeyInfo/ds:X509Data/ds:X509Certificate"); for (int i = 0; i < nodeList.getLength(); i++) { Element certEl = (Element) nodeList.item(i); byte[] derEncoded = Base64.decodeBase64(certEl.getTextContent()); X509Certificate cert = (X509Certificate) factory .generateCertificate(new ByteArrayInputStream(derEncoded)); if (!list.contains(cert)) { list.add(cert); } } } } catch (CertificateException e) { throw new RuntimeException(e); } return list; }
From source file:com.hpe.elderberry.TaxiiConnection.java
private List<Certificate> addPemsToStore(KeyStore store, List<String> pems) throws CertificateException { List<Certificate> result = new ArrayList<>(pems.size()); CertificateFactory factory = CertificateFactory.getInstance("X.509"); pems.forEach(pem -> {// w ww . j av a 2s.c o m try { X509Certificate cert = (X509Certificate) factory.generateCertificate(toInputStream(pem)); store.setCertificateEntry(randomUUID().toString(), cert); result.add(cert); } catch (Exception e) { throw new RuntimeException("unable to load PEM: " + pem + ", " + e.getMessage(), e); } }); return result; }
From source file:org.kitodo.production.services.data.LdapServerService.java
private void loadCertificates(String path, String passwd, LdapServer ldapServer) { /* wenn die Zertifikate noch nicht im Keystore sind, jetzt einlesen */ File myPfad = new File(path); if (!myPfad.exists()) { try (FileOutputStream ksos = (FileOutputStream) ServiceManager.getFileService().write(myPfad.toURI()); // TODO: Rename parameters to something more meaningful, // this is quite specific for the GDZ FileInputStream cacertFile = new FileInputStream(ldapServer.getRootCertificate()); FileInputStream certFile2 = new FileInputStream(ldapServer.getPdcCertificate())) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cacert = (X509Certificate) cf.generateCertificate(cacertFile); X509Certificate servercert = (X509Certificate) cf.generateCertificate(certFile2); KeyStore ks = KeyStore.getInstance("jks"); char[] password = passwd.toCharArray(); // TODO: Let this method really load a keystore if configured // initialize the keystore, if file is available, load the // keystore ks.load(null);//from ww w . ja va2 s . co m ks.setCertificateEntry("ROOTCERT", cacert); ks.setCertificateEntry("PDC", servercert); ks.store(ksos, password); } catch (IOException | CertificateException | KeyStoreException | NoSuchAlgorithmException | RuntimeException e) { logger.error(e.getMessage(), e); } } }