List of usage examples for java.security.cert Certificate getPublicKey
public abstract PublicKey getPublicKey();
From source file:com.fine47.http.SecureSocketFactory.java
private SecureSocketFactory(String factoryId, KeyStore store, String alias) throws CertificateException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(store); // Loading the CA certificate from store. Certificate rootca = store.getCertificate(alias); // Turn it to X509 format. InputStream is = new ByteArrayInputStream(rootca.getEncoded()); X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is); ActivityHttpClient.silentCloseInputStream(is); if (null == x509ca) { throw new CertificateException("Found expired SSL certificate in this store: " + factoryId); }/*from www . j ava 2 s . co m*/ // Check the CA's validity. x509ca.checkValidity(); // Accepted CA is only the one installed in the store. acceptedIssuers = new X509Certificate[] { x509ca }; // Get the public key. publicKey = rootca.getPublicKey(); sslCtx = SSLContext.getInstance("TLS"); sslCtx.init(null, new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { Exception error = null; if (null == chain || 0 == chain.length) { error = new CertificateException("Certificate chain is invalid"); } else if (null == authType || 0 == authType.length()) { error = new CertificateException("Authentication type is invalid"); } else try { for (X509Certificate cert : chain) { if (ActivityHttpClient.isDebugging()) { Log.d(ActivityHttpClient.LOG_TAG, "Server Certificate Details:"); Log.d(ActivityHttpClient.LOG_TAG, "---------------------------"); Log.d(ActivityHttpClient.LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString()); Log.d(ActivityHttpClient.LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString()); Log.d(ActivityHttpClient.LOG_TAG, "Serial Number: " + cert.getSerialNumber()); Log.d(ActivityHttpClient.LOG_TAG, "Version: " + cert.getVersion()); Log.d(ActivityHttpClient.LOG_TAG, "Not before: " + cert.getNotBefore().toString()); Log.d(ActivityHttpClient.LOG_TAG, "Not after: " + cert.getNotAfter().toString()); Log.d(ActivityHttpClient.LOG_TAG, "---------------------------"); } // Make sure that it hasn't expired. cert.checkValidity(); // Verify the certificate's chain. cert.verify(publicKey); } } catch (InvalidKeyException ex) { error = ex; } catch (NoSuchAlgorithmException ex) { error = ex; } catch (NoSuchProviderException ex) { error = ex; } catch (SignatureException ex) { error = ex; } if (null != error && ActivityHttpClient.isDebugging()) { Log.e(ActivityHttpClient.LOG_TAG, "Error while setting up a secure socket factory.", error); throw new CertificateException(error); } } @Override public X509Certificate[] getAcceptedIssuers() { return acceptedIssuers; } } }, null); setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); }
From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.enrollment.EnrollmentManager.java
/** * Gets the Public Key of the SCEP-Server and initializes it for later use. This method contacts the SCEP Server * and fetches its CA Cert and extracts the Public Key of the server from the received reply. * * @return the public key of the SCEP Server which is to be used to encrypt pyloads. * @throws AgentCoreOperationException if the SCEPUrl is invalid or if the flow of sending the CSR and getting * the signed certificate fails or if the signed certificate cannot be * retrieved from the reply from the server. *//*from w ww . j ava 2s . co m*/ private PublicKey initPublicKeyOfServer() throws AgentCoreOperationException { URL url; CertStore certStore; PublicKey serverCertPublicKey = null; try { // The URL where we are going to request our cert from url = new URL(this.SCEPUrl); /* // This is called when we get the certificate for our CSR signed by CA // Implement this handler to check the CA cert in prod. We can do cert pinning here CallbackHandler cb = new CallbackHandler() { @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } };*/ // I did not implement any verification of the CA cert. DO NOT DO THAT. // For testing this is OK, in Prod make sure to VERIFY the CA CertificateVerifier ocv = new OptimisticCertificateVerifier(); // Instantiate our SCEP client Client scepClient = new Client(url, ocv); // Get the CA capabilities. For some reason the IOS router does not return // correct information here. Do not trust it. Should return SHA1withRSA for // strongest hash and sig. Returns MD5. if (log.isDebugEnabled()) { Capabilities cap = scepClient.getCaCapabilities(); log.debug(String.format( "\nStrongestCipher: %s,\nStrongestMessageDigest: %s,\nStrongestSignatureAlgorithm: %s," + "\nIsRenewalSupported: %s,\nIsRolloverSupported: %s", cap.getStrongestCipher(), cap.getStrongestMessageDigest(), cap.getStrongestSignatureAlgorithm(), cap.isRenewalSupported(), cap.isRolloverSupported())); } certStore = scepClient.getCaCertificate(); for (Certificate cert : certStore.getCertificates(null)) { if (cert instanceof X509Certificate) { if (log.isDebugEnabled()) { log.debug(((X509Certificate) cert).getIssuerDN().getName()); } //TODO: Need to identify the correct certificate. // I have chosen the CA cert based on its BasicConstraint criticality being set to "true" if (((X509CertImpl) cert).getBasicConstraintsExtension().isCritical()) { serverCertPublicKey = cert.getPublicKey(); } } } } catch (MalformedURLException ex) { String errorMsg = "Could not create valid URL from given SCEP URI: " + SCEPUrl; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, ex); } catch (ClientException e) { String errorMsg = "Could not retrieve [Server-Certificate] from the SCEP-Server."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } catch (CertStoreException e) { String errorMsg = "Could not retrieve [Server-Certificates] from the response message from SCEP-Server."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } return serverCertPublicKey; }
From source file:org.apache.cloudstack.network.lb.CertServiceImpl.java
private void validate(String certInput, String keyInput, String password, String chainInput) { Certificate cert; PrivateKey key;// w w w .ja v a 2s. com List<Certificate> chain = null; try { cert = parseCertificate(certInput); key = parsePrivateKey(keyInput, password); if (chainInput != null) { chain = parseChain(chainInput); } } catch (IOException e) { throw new IllegalArgumentException("Parsing certificate/key failed: " + e.getMessage(), e); } validateCert(cert, chainInput != null ? true : false); validateKeys(cert.getPublicKey(), key); if (chainInput != null) validateChain(chain, cert); }
From source file:com.adito.boot.KeyStoreManager.java
/** * Get a key pair from this key store//from w ww. j a v a2 s . c om * * @param alias alias under which the pair is stored * @param password password protecting the keys if any * @return key pair */ public KeyPair getKeyPair(String alias, char[] password) { try { checkKeyStore(); if (isKeyStoreExists() && !isKeyStoreEmpty()) { Key key = keyStore.getKey(alias, password); if (key instanceof PrivateKey) { Certificate cert = keyStore.getCertificate(alias); PublicKey publicKey = cert.getPublicKey(); return new KeyPair(publicKey, (PrivateKey) key); } } } catch (Exception e) { log.error("Could not get key pair with alias " + alias + ".", e); } return null; }
From source file:ddf.security.samlp.SimpleSign.java
public boolean validateSignature(String sigAlg, String queryParamsToValidate, String encodedSignature, @Nullable String encodedPublicKey) throws SignatureException { if (encodedPublicKey == null) { LOGGER.warn(/*w ww. j av a 2 s. c o m*/ "Could not verify the signature of request because there was no signing certificate. Ensure that the IdP Metadata includes a signing certificate."); return false; } try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X509"); Certificate certificate = certificateFactory.generateCertificate( new ByteArrayInputStream(Base64.getMimeDecoder().decode(encodedPublicKey))); java.security.Signature sig; String jceSigAlg = JCEMapper.translateURItoJCEID(sigAlg); if (jceSigAlg == null) { throw new SignatureException(new NoSuchAlgorithmException( String.format("The Signature Algorithm %s is not supported.", sigAlg))); } try { sig = java.security.Signature.getInstance(jceSigAlg); } catch (NoSuchAlgorithmException e) { throw new SignatureException(e); } sig.initVerify(certificate.getPublicKey()); sig.update(queryParamsToValidate.getBytes(StandardCharsets.UTF_8)); return sig.verify(Base64.getMimeDecoder().decode(encodedSignature)); } catch (InvalidKeyException | CertificateException | java.security.SignatureException | IllegalArgumentException e) { throw new SignatureException(e); } }
From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.enrollment.EnrollmentManager.java
/** * Gets the Public Key of the SCEP-Server and initializes it for later use. This method contacts the SCEP Server * and fetches its CA Cert and extracts the Public Key of the server from the received reply. * * @return the public key of the SCEP Server which is to be used to encrypt pyloads. * @throws AgentCoreOperationException if the SCEPUrl is invalid or if the flow of sending the CSR and getting * the signed certificate fails or if the signed certificate cannot be * retrieved from the reply from the server. *//* w ww .jav a 2 s.co m*/ private PublicKey initPublicKeyOfServer() throws AgentCoreOperationException { URL url; CertStore certStore; PublicKey serverCertPublicKey = null; try { // The URL where we are going to request our cert from url = new URL(this.SCEPUrl); /* // This is called when we get the certificate for our CSR signed by CA // Implement this handler to check the CA cert in prod. We can do cert pinning here CallbackHandler cb = new CallbackHandler() { @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } };*/ // Implement verification of the CA cert. VERIFY the CA CertificateVerifier ocv = new OptimisticCertificateVerifier(); // Instantiate our SCEP client Client scepClient = new Client(url, ocv); // Get the CA capabilities. Should return SHA1withRSA for strongest hash and sig. Returns MD5. if (log.isDebugEnabled()) { Capabilities cap = scepClient.getCaCapabilities(); log.debug(String.format( "\nStrongestCipher: %s,\nStrongestMessageDigest: %s,\nStrongestSignatureAlgorithm: %s," + "\nIsRenewalSupported: %s,\nIsRolloverSupported: %s", cap.getStrongestCipher(), cap.getStrongestMessageDigest(), cap.getStrongestSignatureAlgorithm(), cap.isRenewalSupported(), cap.isRolloverSupported())); } certStore = scepClient.getCaCertificate(); for (Certificate cert : certStore.getCertificates(null)) { if (cert instanceof X509Certificate) { if (log.isDebugEnabled()) { log.debug(((X509Certificate) cert).getIssuerDN().getName()); } // I have chosen the CA cert based on its BasicConstraintExtension "is_ca" being set to "true" // This is because the returned keystore may contain many certificates including RAs. if (((Boolean) ((X509CertImpl) cert).getBasicConstraintsExtension() .get(CERT_IS_CA_EXTENSION))) { serverCertPublicKey = cert.getPublicKey(); } } } } catch (MalformedURLException ex) { String errorMsg = "Could not create valid URL from given SCEP URI: " + SCEPUrl; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, ex); } catch (ClientException e) { String errorMsg = "Could not retrieve [Server-Certificate] from the SCEP-Server."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } catch (CertStoreException e) { String errorMsg = "Could not retrieve [Server-Certificates] from the response message from SCEP-Server."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } catch (IOException e) { String errorMsg = "Error occurred whilst trying to get property ['is_ca'] from the retreived Certificates"; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } return serverCertPublicKey; }
From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java
/** * Verifies the signature on an enveloped digital signature on a UDDI * entity, such as a business, service, tmodel or binding template. * <br><Br>/*from w ww .j ava2 s . c om*/ * It is expected that either the public key of the signing certificate * is included within the signature keyinfo section OR that sufficient * information is provided in the signature to reference a public key * located within the Trust Store provided<br><Br> Optionally, this * function also validate the signing certificate using the options * provided to the configuration map. * * @param obj an enveloped signed JAXB object * @param OutErrorMessage a human readable error message explaining the * reason for failure * @return true if the validation passes the signature validation test, * and optionally any certificate validation or trust chain validation * @throws IllegalArgumentException for null input */ public boolean verifySignedUddiEntity(Object obj, AtomicReference<String> OutErrorMessage) throws IllegalArgumentException { if (OutErrorMessage == null) { OutErrorMessage = new AtomicReference<String>(); OutErrorMessage.set(""); } if (obj == null) { throw new IllegalArgumentException("obj"); } try { DOMResult domResult = new DOMResult(); JAXB.marshal(obj, domResult); Document doc = ((Document) domResult.getNode()); Element docElement = doc.getDocumentElement(); //this is our signed node X509Certificate signingcert = getSigningCertificatePublicKey(docElement); if (signingcert != null) { logger.info( "verifying signature based on X509 public key " + signingcert.getSubjectDN().toString()); if (map.containsKey(CHECK_TIMESTAMPS) && Boolean.parseBoolean(map.getProperty(CHECK_TIMESTAMPS))) { signingcert.checkValidity(); } if (map.containsKey(CHECK_REVOCATION_STATUS_OCSP) && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_OCSP))) { logger.info("verifying revocation status via OSCP for X509 public key " + signingcert.getSubjectDN().toString()); X500Principal issuerX500Principal = signingcert.getIssuerX500Principal(); logger.info("certificate " + signingcert.getSubjectDN().toString() + " was issued by " + issuerX500Principal.getName() + ", attempting to retrieve certificate"); Security.setProperty("ocsp.enable", "false"); X509Certificate issuer = FindCertByDN(issuerX500Principal); if (issuer == null) { OutErrorMessage.set( "Unable to verify certificate status from OCSP because the issuer of the certificate is not in the trust store. " + OutErrorMessage.get()); //throw new CertificateException("unable to locate the issuers certificate in the trust store"); } else { RevocationStatus check = OCSP.check(signingcert, issuer); logger.info("certificate " + signingcert.getSubjectDN().toString() + " revocation status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString()); if (check.getCertStatus() != RevocationStatus.CertStatus.GOOD) { OutErrorMessage .set("Certificate status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString() + "." + OutErrorMessage.get()); //throw new CertificateException("Certificate status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString()); } } } if (map.containsKey(CHECK_REVOCATION_STATUS_CRL) && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_CRL))) { logger.info("verifying revokation status via CRL for X509 public key " + signingcert.getSubjectDN().toString()); Security.setProperty("ocsp.enable", "false"); System.setProperty("com.sun.security.enableCRLDP", "true"); X509CertSelector targetConstraints = new X509CertSelector(); targetConstraints.setCertificate(signingcert); PKIXParameters params = new PKIXParameters(GetTrustStore()); params.setRevocationEnabled(true); CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert)); CertPathValidator certPathValidator = CertPathValidator .getInstance(CertPathValidator.getDefaultType()); CertPathValidatorResult result = certPathValidator.validate(certPath, params); try { PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result; logger.info("revokation status via CRL PASSED for X509 public key " + signingcert.getSubjectDN().toString()); } catch (Exception ex) { OutErrorMessage.set("Certificate status is via CRL Failed: " + ex.getMessage() + "." + OutErrorMessage.get()); } } if (map.containsKey(CHECK_TRUST_CHAIN) && Boolean.parseBoolean(map.getProperty(CHECK_TRUST_CHAIN))) { logger.info("verifying trust chain X509 public key " + signingcert.getSubjectDN().toString()); try { PKIXParameters params = new PKIXParameters(GetTrustStore()); params.setRevocationEnabled(false); CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert)); CertPathValidator certPathValidator = CertPathValidator .getInstance(CertPathValidator.getDefaultType()); CertPathValidatorResult result = certPathValidator.validate(certPath, params); PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result; TrustAnchor ta = pkixResult.getTrustAnchor(); X509Certificate cert = ta.getTrustedCert(); logger.info( "trust chain validated X509 public key " + signingcert.getSubjectDN().toString()); } catch (Exception ex) { OutErrorMessage.set("Certificate status Trust validation failed: " + ex.getMessage() + "." + OutErrorMessage.get()); } } boolean b = verifySignature(docElement, signingcert.getPublicKey(), OutErrorMessage); if ((OutErrorMessage.get() == null || OutErrorMessage.get().length() == 0) && b) { //no error message and its cryptographically valid return true; } return false; } //last chance validation logger.info( "signature did not have an embedded X509 public key. reverting to user specified certificate"); //cert wasn't included in the signature, revert to some other means KeyStore ks = KeyStore.getInstance(map.getProperty(SIGNATURE_KEYSTORE_FILETYPE)); URL url = Thread.currentThread().getContextClassLoader() .getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE)); if (url == null) { try { url = new File(map.getProperty(SIGNATURE_KEYSTORE_FILE)).toURI().toURL(); } catch (Exception x) { } } if (url == null) { try { url = this.getClass().getClassLoader().getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE)); } catch (Exception x) { } } if (url == null) { logger.error(""); OutErrorMessage.set("The signed entity is signed but does not have a certificate attached and" + "you didn't specify a keystore for me to look it up in. " + OutErrorMessage.get()); return false; } KeyStore.PrivateKeyEntry keyEntry = null; ks.load(url.openStream(), map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray()); if (map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD) == null) { keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS), new KeyStore.PasswordProtection( map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray())); } else { keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS), new KeyStore.PasswordProtection( map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD).toCharArray())); } Certificate origCert = keyEntry.getCertificate(); if (map.containsKey(CHECK_TIMESTAMPS)) { if (origCert.getPublicKey() instanceof X509Certificate) { X509Certificate x = (X509Certificate) origCert.getPublicKey(); x.checkValidity(); } } PublicKey validatingKey = origCert.getPublicKey(); return verifySignature(docElement, validatingKey, OutErrorMessage); } catch (Exception e) { //throw new RuntimeException(e); logger.error("Error caught validating signature", e); OutErrorMessage.set(e.getMessage()); return false; } }
From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.enrollment.EnrollmentManager.java
/** * Gets the Public Key of the SCEP-Server and initializes it for later use. This method contacts the SCEP Server * and fetches its CA Cert and extracts the Public Key of the server from the received reply. * * @return the public key of the SCEP Server which is to be used to encrypt pyloads. * @throws AgentCoreOperationException if the SCEPUrl is invalid or if the flow of sending the CSR and getting * the signed certificate fails or if the signed certificate cannot be * retrieved from the reply from the server. *//*w ww. j av a 2s . c om*/ private PublicKey initPublicKeyOfServer() throws AgentCoreOperationException { URL url; CertStore certStore; PublicKey serverCertPublicKey = null; try { // The URL where we are going to request our cert from url = new URL(this.SCEPUrl); /* // This is called when we get the certificate for our CSR signed by CA // Implement this handler to check the CA cert in prod. We can do cert pinning here CallbackHandler cb = new CallbackHandler() { @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } };*/ // Implement verification of the CA cert. VERIFY the CA CertificateVerifier ocv = new OptimisticCertificateVerifier(); // Instantiate our SCEP client Client scepClient = new Client(url, ocv); // Get the CA capabilities. Should return SHA1withRSA for strongest hash and sig. Returns MD5. if (log.isDebugEnabled()) { Capabilities cap = scepClient.getCaCapabilities(); log.debug(String.format( "\nStrongestCipher: %s,\nStrongestMessageDigest: %s,\nStrongestSignatureAlgorithm: %s," + "\nIsRenewalSupported: %s,\nIsRolloverSupported: %s", cap.getStrongestCipher(), cap.getStrongestMessageDigest(), cap.getStrongestSignatureAlgorithm(), cap.isRenewalSupported(), cap.isRolloverSupported())); } certStore = scepClient.getCaCertificate(); for (Certificate cert : certStore.getCertificates(null)) { if (cert instanceof X509Certificate) { if (log.isDebugEnabled()) { log.debug(((X509Certificate) cert).getIssuerDN().getName()); } // I have chosen the CA cert based on its BasicConstraintExtension "is_ca" being set to "true" // This is because the returned keystore may contain many certificates including RAs. if (((Boolean) ((X509CertImpl) cert).getBasicConstraintsExtension() .get(CERT_IS_CA_EXTENSION))) { serverCertPublicKey = cert.getPublicKey(); storeCertificateToStore(AgentConstants.SERVER_CA_CERT_ALIAS, cert); } } } } catch (MalformedURLException ex) { String errorMsg = "Could not create valid URL from given SCEP URI: " + SCEPUrl; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, ex); } catch (ClientException e) { String errorMsg = "Could not retrieve [Server-Certificate] from the SCEP-Server."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } catch (CertStoreException e) { String errorMsg = "Could not retrieve [Server-Certificates] from the response message from SCEP-Server."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } catch (IOException e) { String errorMsg = "Error occurred whilst trying to get property ['is_ca'] from the retreived Certificates"; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } return serverCertPublicKey; }
From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java
public boolean verifyCertificate(X509Certificate certToVerify) { Certificate rootCert = getMCCertificate(INTERMEDIATE_CERT_ALIAS); JcaX509CertificateHolder certHolder; try {/*from w w w . j av a 2s . co m*/ certHolder = new JcaX509CertificateHolder(certToVerify); } catch (CertificateEncodingException e) { log.error("Could not create JcaX509CertificateHolder", e); return false; } PublicKey pubKey = rootCert.getPublicKey(); if (pubKey == null) { log.error("Could not get public key of root certificate"); return false; } ContentVerifierProvider contentVerifierProvider; try { contentVerifierProvider = new JcaContentVerifierProviderBuilder().setProvider(BC_PROVIDER_NAME) .build(pubKey); } catch (OperatorCreationException e) { log.error("Could not create ContentVerifierProvider from public key", e); return false; } if (contentVerifierProvider == null) { log.error("Created ContentVerifierProvider from root public key is null"); return false; } try { if (certHolder.isSignatureValid(contentVerifierProvider)) { return true; } } catch (CertException e) { log.error("Error when trying to validate signature", e); return false; } log.debug("Certificate does not seem to be valid!"); return false; }
From source file:eu.europa.ejusticeportal.dss.applet.DssApplet.java
/** * This methods checks if the data coming from the server can be trusted. * The hash provided by the server is checked using the public key. * @param data the data coming from the server. * @param serverHash the hash of the data coming from the server. * @param algo the algorithm used for the server hash. * @return <code>true</code> if the serverHash can be verified with the public key. */// w w w .jav a 2s . c o m private boolean canTrustServerHash(final String data, final String serverHash, final String algo) { Certificate certificate; InputStream pemInputStream; try { pemInputStream = getClass().getClassLoader().getResourceAsStream("certificate.pem"); if (pemInputStream == null) { LOG.log(Level.SEVERE, "Missing certificate.pem file. Impossible to check if the data coming from the server can be trusted."); return false; } } catch (Exception e) { LOG.log(Level.SEVERE, "Missing certificate.pem file. Impossible to check if the data coming from the server can be trusted."); return false; } try { certificate = CertificateFactory.getInstance("X.509").generateCertificate(pemInputStream); PublicKey publicKey = certificate.getPublicKey(); Signature sigVerify = Signature.getInstance(new String(Base64.decodeBase64(algo)), "BC"); sigVerify.initVerify(publicKey); sigVerify.update(data.getBytes("UTF-8")); boolean signatureMatch = sigVerify.verify(Base64.decodeBase64(serverHash)); if (signatureMatch) { LOG.log(Level.INFO, "The data coming from the server can be trusted."); return true; } else { LOG.log(Level.SEVERE, "!!! Tampered data received !!!"); LOG.log(Level.INFO, serverHash); LOG.log(Level.INFO, data); return false; } } catch (CertificateException e) { LOG.error(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { LOG.error(e.getMessage(), e); } catch (NoSuchProviderException e) { LOG.error(e.getMessage(), e); } catch (InvalidKeyException e) { LOG.error(e.getMessage(), e); } catch (SignatureException e) { LOG.error(e.getMessage(), e); } catch (UnsupportedEncodingException e) { LOG.error(e.getMessage(), e); } LOG.log(Level.SEVERE, "Impossible to check if the data coming from the server can be trusted."); return false; }