use of java.security.NoSuchProviderException in project jersey by jersey.
the class SslConfigurator method createSSLContext.
/**
* Create new SSL context instance using the current SSL context configuration.
*
* @return newly configured SSL context instance.
*/
public SSLContext createSSLContext() {
TrustManagerFactory trustManagerFactory = null;
KeyManagerFactory keyManagerFactory = null;
KeyStore _keyStore = keyStore;
if (_keyStore == null && (keyStoreBytes != null || keyStoreFile != null)) {
try {
if (keyStoreProvider != null) {
_keyStore = KeyStore.getInstance(keyStoreType != null ? keyStoreType : KeyStore.getDefaultType(), keyStoreProvider);
} else {
_keyStore = KeyStore.getInstance(keyStoreType != null ? keyStoreType : KeyStore.getDefaultType());
}
InputStream keyStoreInputStream = null;
try {
if (keyStoreBytes != null) {
keyStoreInputStream = new ByteArrayInputStream(keyStoreBytes);
} else if (!keyStoreFile.equals("NONE")) {
keyStoreInputStream = new FileInputStream(keyStoreFile);
}
_keyStore.load(keyStoreInputStream, keyStorePass);
} finally {
try {
if (keyStoreInputStream != null) {
keyStoreInputStream.close();
}
} catch (IOException ignored) {
}
}
} catch (KeyStoreException e) {
throw new IllegalStateException(LocalizationMessages.SSL_KS_IMPL_NOT_FOUND(), e);
} catch (CertificateException e) {
throw new IllegalStateException(LocalizationMessages.SSL_KS_CERT_LOAD_ERROR(), e);
} catch (FileNotFoundException e) {
throw new IllegalStateException(LocalizationMessages.SSL_KS_FILE_NOT_FOUND(keyStoreFile), e);
} catch (IOException e) {
throw new IllegalStateException(LocalizationMessages.SSL_KS_LOAD_ERROR(keyStoreFile), e);
} catch (NoSuchProviderException e) {
throw new IllegalStateException(LocalizationMessages.SSL_KS_PROVIDERS_NOT_REGISTERED(), e);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(LocalizationMessages.SSL_KS_INTEGRITY_ALGORITHM_NOT_FOUND(), e);
}
}
if (_keyStore != null) {
String kmfAlgorithm = keyManagerFactoryAlgorithm;
if (kmfAlgorithm == null) {
kmfAlgorithm = AccessController.doPrivileged(PropertiesHelper.getSystemProperty(KEY_MANAGER_FACTORY_ALGORITHM, KeyManagerFactory.getDefaultAlgorithm()));
}
try {
if (keyManagerFactoryProvider != null) {
keyManagerFactory = KeyManagerFactory.getInstance(kmfAlgorithm, keyManagerFactoryProvider);
} else {
keyManagerFactory = KeyManagerFactory.getInstance(kmfAlgorithm);
}
final char[] password = keyPass != null ? keyPass : keyStorePass;
if (password != null) {
keyManagerFactory.init(_keyStore, password);
} else {
String ksName = keyStoreProvider != null ? LocalizationMessages.SSL_KMF_NO_PASSWORD_FOR_PROVIDER_BASED_KS() : keyStoreBytes != null ? LocalizationMessages.SSL_KMF_NO_PASSWORD_FOR_BYTE_BASED_KS() : keyStoreFile;
LOGGER.config(LocalizationMessages.SSL_KMF_NO_PASSWORD_SET(ksName));
keyManagerFactory = null;
}
} catch (KeyStoreException e) {
throw new IllegalStateException(LocalizationMessages.SSL_KMF_INIT_FAILED(), e);
} catch (UnrecoverableKeyException e) {
throw new IllegalStateException(LocalizationMessages.SSL_KMF_UNRECOVERABLE_KEY(), e);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(LocalizationMessages.SSL_KMF_ALGORITHM_NOT_SUPPORTED(), e);
} catch (NoSuchProviderException e) {
throw new IllegalStateException(LocalizationMessages.SSL_KMF_PROVIDER_NOT_REGISTERED(), e);
}
}
KeyStore _trustStore = trustStore;
if (_trustStore == null && (trustStoreBytes != null || trustStoreFile != null)) {
try {
if (trustStoreProvider != null) {
_trustStore = KeyStore.getInstance(trustStoreType != null ? trustStoreType : KeyStore.getDefaultType(), trustStoreProvider);
} else {
_trustStore = KeyStore.getInstance(trustStoreType != null ? trustStoreType : KeyStore.getDefaultType());
}
InputStream trustStoreInputStream = null;
try {
if (trustStoreBytes != null) {
trustStoreInputStream = new ByteArrayInputStream(trustStoreBytes);
} else if (!trustStoreFile.equals("NONE")) {
trustStoreInputStream = new FileInputStream(trustStoreFile);
}
_trustStore.load(trustStoreInputStream, trustStorePass);
} finally {
try {
if (trustStoreInputStream != null) {
trustStoreInputStream.close();
}
} catch (IOException ignored) {
}
}
} catch (KeyStoreException e) {
throw new IllegalStateException(LocalizationMessages.SSL_TS_IMPL_NOT_FOUND(), e);
} catch (CertificateException e) {
throw new IllegalStateException(LocalizationMessages.SSL_TS_CERT_LOAD_ERROR(), e);
} catch (FileNotFoundException e) {
throw new IllegalStateException(LocalizationMessages.SSL_TS_FILE_NOT_FOUND(trustStoreFile), e);
} catch (IOException e) {
throw new IllegalStateException(LocalizationMessages.SSL_TS_LOAD_ERROR(trustStoreFile), e);
} catch (NoSuchProviderException e) {
throw new IllegalStateException(LocalizationMessages.SSL_TS_PROVIDERS_NOT_REGISTERED(), e);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(LocalizationMessages.SSL_TS_INTEGRITY_ALGORITHM_NOT_FOUND(), e);
}
}
if (_trustStore != null) {
String tmfAlgorithm = trustManagerFactoryAlgorithm;
if (tmfAlgorithm == null) {
tmfAlgorithm = AccessController.doPrivileged(PropertiesHelper.getSystemProperty(TRUST_MANAGER_FACTORY_ALGORITHM, TrustManagerFactory.getDefaultAlgorithm()));
}
try {
if (trustManagerFactoryProvider != null) {
trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm, trustManagerFactoryProvider);
} else {
trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm);
}
trustManagerFactory.init(_trustStore);
} catch (KeyStoreException e) {
throw new IllegalStateException(LocalizationMessages.SSL_TMF_INIT_FAILED(), e);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(LocalizationMessages.SSL_TMF_ALGORITHM_NOT_SUPPORTED(), e);
} catch (NoSuchProviderException e) {
throw new IllegalStateException(LocalizationMessages.SSL_TMF_PROVIDER_NOT_REGISTERED(), e);
}
}
try {
String secProtocol = "TLS";
if (securityProtocol != null) {
secProtocol = securityProtocol;
}
final SSLContext sslContext = SSLContext.getInstance(secProtocol);
sslContext.init(keyManagerFactory != null ? keyManagerFactory.getKeyManagers() : null, trustManagerFactory != null ? trustManagerFactory.getTrustManagers() : null, null);
return sslContext;
} catch (KeyManagementException e) {
throw new IllegalStateException(LocalizationMessages.SSL_CTX_INIT_FAILED(), e);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(LocalizationMessages.SSL_CTX_ALGORITHM_NOT_SUPPORTED(), e);
}
}
use of java.security.NoSuchProviderException in project tomcat by apache.
the class SessionIdGeneratorBase method createSecureRandom.
/**
* Create a new random number generator instance we should use for
* generating session identifiers.
*/
private SecureRandom createSecureRandom() {
SecureRandom result = null;
long t1 = System.currentTimeMillis();
if (secureRandomClass != null) {
try {
// Construct and seed a new random number generator
Class<?> clazz = Class.forName(secureRandomClass);
result = (SecureRandom) clazz.newInstance();
} catch (Exception e) {
log.error(sm.getString("sessionIdGeneratorBase.random", secureRandomClass), e);
}
}
if (result == null) {
// No secureRandomClass or creation failed. Use SecureRandom.
try {
if (secureRandomProvider != null && secureRandomProvider.length() > 0) {
result = SecureRandom.getInstance(secureRandomAlgorithm, secureRandomProvider);
} else if (secureRandomAlgorithm != null && secureRandomAlgorithm.length() > 0) {
result = SecureRandom.getInstance(secureRandomAlgorithm);
}
} catch (NoSuchAlgorithmException e) {
log.error(sm.getString("sessionIdGeneratorBase.randomAlgorithm", secureRandomAlgorithm), e);
} catch (NoSuchProviderException e) {
log.error(sm.getString("sessionIdGeneratorBase.randomProvider", secureRandomProvider), e);
}
}
if (result == null) {
// Invalid provider / algorithm
try {
result = SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException e) {
log.error(sm.getString("sessionIdGeneratorBase.randomAlgorithm", secureRandomAlgorithm), e);
}
}
if (result == null) {
// Nothing works - use platform default
result = new SecureRandom();
}
// Force seeding to take place
result.nextInt();
long t2 = System.currentTimeMillis();
if ((t2 - t1) > 100)
log.info(sm.getString("sessionIdGeneratorBase.createRandom", result.getAlgorithm(), Long.valueOf(t2 - t1)));
return result;
}
use of java.security.NoSuchProviderException in project tomcat by apache.
the class SSLValve method invoke.
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
/* mod_header converts the '\n' into ' ' so we have to rebuild the client certificate */
String strcert0 = mygetHeader(request, sslClientCertHeader);
if (strcert0 != null && strcert0.length() > 28) {
String strcert1 = strcert0.replace(' ', '\n');
String strcert2 = strcert1.substring(28, strcert1.length() - 26);
String strcert3 = "-----BEGIN CERTIFICATE-----\n";
String strcert4 = strcert3.concat(strcert2);
String strcerts = strcert4.concat("\n-----END CERTIFICATE-----\n");
// ByteArrayInputStream bais = new ByteArrayInputStream(strcerts.getBytes("UTF-8"));
ByteArrayInputStream bais = new ByteArrayInputStream(strcerts.getBytes(StandardCharsets.ISO_8859_1));
X509Certificate[] jsseCerts = null;
String providerName = (String) request.getConnector().getProperty("clientCertProvider");
try {
CertificateFactory cf;
if (providerName == null) {
cf = CertificateFactory.getInstance("X.509");
} else {
cf = CertificateFactory.getInstance("X.509", providerName);
}
X509Certificate cert = (X509Certificate) cf.generateCertificate(bais);
jsseCerts = new X509Certificate[1];
jsseCerts[0] = cert;
} catch (java.security.cert.CertificateException e) {
log.warn(sm.getString("sslValve.certError", strcerts), e);
} catch (NoSuchProviderException e) {
log.error(sm.getString("sslValve.invalidProvider", providerName), e);
}
request.setAttribute(Globals.CERTIFICATES_ATTR, jsseCerts);
}
strcert0 = mygetHeader(request, sslCipherHeader);
if (strcert0 != null) {
request.setAttribute(Globals.CIPHER_SUITE_ATTR, strcert0);
}
strcert0 = mygetHeader(request, sslSessionIdHeader);
if (strcert0 != null) {
request.setAttribute(Globals.SSL_SESSION_ID_ATTR, strcert0);
}
strcert0 = mygetHeader(request, sslCipherUserKeySizeHeader);
if (strcert0 != null) {
request.setAttribute(Globals.KEY_SIZE_ATTR, Integer.valueOf(strcert0));
}
getNext().invoke(request, response);
}
use of java.security.NoSuchProviderException in project camel by apache.
the class XmlVerifierProcessor method verify.
@SuppressWarnings("unchecked")
protected void verify(InputStream input, final Message out) throws Exception {
//NOPMD
LOG.debug("Verification of XML signature document started");
final Document doc = parseInput(input, out);
XMLSignatureFactory fac;
// not work
try {
fac = XMLSignatureFactory.getInstance("DOM", "ApacheXMLDSig");
} catch (NoSuchProviderException ex) {
fac = XMLSignatureFactory.getInstance("DOM");
}
KeySelector selector = getConfiguration().getKeySelector();
if (selector == null) {
throw new IllegalStateException("Wrong configuration. Key selector is missing.");
}
DOMValidateContext valContext = new DOMValidateContext(selector, doc);
valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
valContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE);
if (getConfiguration().getSecureValidation() == Boolean.TRUE) {
valContext.setProperty("org.apache.jcp.xml.dsig.secureValidation", Boolean.TRUE);
valContext.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.TRUE);
}
setUriDereferencerAndBaseUri(valContext);
setCryptoContextProperties(valContext);
NodeList signatureNodes = getSignatureNodes(doc);
List<XMLObject> collectedObjects = new ArrayList<XMLObject>(3);
List<Reference> collectedReferences = new ArrayList<Reference>(3);
int totalCount = signatureNodes.getLength();
for (int i = 0; i < totalCount; i++) {
Element signatureNode = (Element) signatureNodes.item(i);
valContext.setNode(signatureNode);
final XMLSignature signature = fac.unmarshalXMLSignature(valContext);
if (getConfiguration().getXmlSignatureChecker() != null) {
XmlSignatureChecker.Input checkerInput = new CheckerInputBuilder().message(out).messageBodyDocument(doc).keyInfo(signature.getKeyInfo()).currentCountOfSignatures(i + 1).currentSignatureElement(signatureNode).objects(signature.getObjects()).signatureValue(signature.getSignatureValue()).signedInfo(signature.getSignedInfo()).totalCountOfSignatures(totalCount).xmlSchemaValidationExecuted(getSchemaResourceUri(out) != null).build();
getConfiguration().getXmlSignatureChecker().checkBeforeCoreValidation(checkerInput);
}
boolean coreValidity;
try {
coreValidity = signature.validate(valContext);
} catch (XMLSignatureException se) {
throw getConfiguration().getValidationFailedHandler().onXMLSignatureException(se);
}
// Check core validation status
boolean goon = coreValidity;
if (!coreValidity) {
goon = handleSignatureValidationFailed(valContext, signature);
}
if (goon) {
LOG.debug("XML signature {} verified", i + 1);
} else {
throw new XmlSignatureInvalidException("XML signature validation failed");
}
collectedObjects.addAll(signature.getObjects());
collectedReferences.addAll(signature.getSignedInfo().getReferences());
}
map2Message(collectedReferences, collectedObjects, out, doc);
}
use of java.security.NoSuchProviderException in project Smack by igniterealtime.
the class XMPPTCPConnection method proceedTLSReceived.
/**
* The server has indicated that TLS negotiation can start. We now need to secure the
* existing plain connection and perform a handshake. This method won't return until the
* connection has finished the handshake or an error occurred while securing the connection.
* @throws IOException
* @throws CertificateException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws KeyStoreException
* @throws UnrecoverableKeyException
* @throws KeyManagementException
* @throws SmackException
* @throws Exception if an exception occurs.
*/
@SuppressWarnings("LiteralClassName")
private void proceedTLSReceived() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException, KeyManagementException, SmackException {
SSLContext context = this.config.getCustomSSLContext();
KeyStore ks = null;
KeyManager[] kms = null;
PasswordCallback pcb = null;
SmackDaneVerifier daneVerifier = null;
if (config.getDnssecMode() == DnssecMode.needsDnssecAndDane) {
SmackDaneProvider daneProvider = DNSUtil.getDaneProvider();
if (daneProvider == null) {
throw new UnsupportedOperationException("DANE enabled but no SmackDaneProvider configured");
}
daneVerifier = daneProvider.newInstance();
if (daneVerifier == null) {
throw new IllegalStateException("DANE requested but DANE provider did not return a DANE verifier");
}
}
if (context == null) {
final String keyStoreType = config.getKeystoreType();
final CallbackHandler callbackHandler = config.getCallbackHandler();
final String keystorePath = config.getKeystorePath();
if ("PKCS11".equals(keyStoreType)) {
try {
Constructor<?> c = Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(InputStream.class);
String pkcs11Config = "name = SmartCard\nlibrary = " + config.getPKCS11Library();
ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes(StringUtils.UTF8));
Provider p = (Provider) c.newInstance(config);
Security.addProvider(p);
ks = KeyStore.getInstance("PKCS11", p);
pcb = new PasswordCallback("PKCS11 Password: ", false);
callbackHandler.handle(new Callback[] { pcb });
ks.load(null, pcb.getPassword());
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception", e);
ks = null;
}
} else if ("Apple".equals(keyStoreType)) {
ks = KeyStore.getInstance("KeychainStore", "Apple");
ks.load(null, null);
//pcb = new PasswordCallback("Apple Keychain",false);
//pcb.setPassword(null);
} else if (keyStoreType != null) {
ks = KeyStore.getInstance(keyStoreType);
if (callbackHandler != null && StringUtils.isNotEmpty(keystorePath)) {
try {
pcb = new PasswordCallback("Keystore Password: ", false);
callbackHandler.handle(new Callback[] { pcb });
ks.load(new FileInputStream(keystorePath), pcb.getPassword());
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception", e);
ks = null;
}
} else {
ks.load(null, null);
}
}
if (ks != null) {
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
try {
if (pcb == null) {
kmf.init(ks, null);
} else {
kmf.init(ks, pcb.getPassword());
pcb.clearPassword();
}
kms = kmf.getKeyManagers();
} catch (NullPointerException npe) {
LOGGER.log(Level.WARNING, "NullPointerException", npe);
}
}
// If the user didn't specify a SSLContext, use the default one
context = SSLContext.getInstance("TLS");
final SecureRandom secureRandom = new java.security.SecureRandom();
X509TrustManager customTrustManager = config.getCustomX509TrustManager();
if (daneVerifier != null) {
// User requested DANE verification.
daneVerifier.init(context, kms, customTrustManager, secureRandom);
} else {
TrustManager[] customTrustManagers = null;
if (customTrustManager != null) {
customTrustManagers = new TrustManager[] { customTrustManager };
}
context.init(kms, customTrustManagers, secureRandom);
}
}
Socket plain = socket;
// Secure the plain connection
socket = context.getSocketFactory().createSocket(plain, host, plain.getPort(), true);
final SSLSocket sslSocket = (SSLSocket) socket;
// Immediately set the enabled SSL protocols and ciphers. See SMACK-712 why this is
// important (at least on certain platforms) and it seems to be a good idea anyways to
// prevent an accidental implicit handshake.
TLSUtils.setEnabledProtocolsAndCiphers(sslSocket, config.getEnabledSSLProtocols(), config.getEnabledSSLCiphers());
// Initialize the reader and writer with the new secured version
initReaderAndWriter();
// Proceed to do the handshake
sslSocket.startHandshake();
if (daneVerifier != null) {
daneVerifier.finish(sslSocket);
}
final HostnameVerifier verifier = getConfiguration().getHostnameVerifier();
if (verifier == null) {
throw new IllegalStateException("No HostnameVerifier set. Use connectionConfiguration.setHostnameVerifier() to configure.");
} else if (!verifier.verify(getXMPPServiceDomain().toString(), sslSocket.getSession())) {
throw new CertificateException("Hostname verification of certificate failed. Certificate does not authenticate " + getXMPPServiceDomain());
}
// Set that TLS was successful
secureSocket = sslSocket;
}
Aggregations