Java Code Examples for org.apache.wss4j.common.crypto.Crypto#getPrivateKey()
The following examples show how to use
org.apache.wss4j.common.crypto.Crypto#getPrivateKey() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XmlSecInInterceptor.java From cxf with Apache License 2.0 | 5 votes |
private void configureDecryptionKeys(Message message, XMLSecurityProperties properties) throws IOException, UnsupportedCallbackException, WSSecurityException { String cryptoKey = null; String propKey = null; if (RSSecurityUtils.isSignedAndEncryptedTwoWay(message)) { cryptoKey = SecurityConstants.SIGNATURE_CRYPTO; propKey = SecurityConstants.SIGNATURE_PROPERTIES; } else { cryptoKey = SecurityConstants.ENCRYPT_CRYPTO; propKey = SecurityConstants.ENCRYPT_PROPERTIES; } Crypto crypto = null; try { crypto = new CryptoLoader().getCrypto(message, cryptoKey, propKey); } catch (Exception ex) { throwFault("Crypto can not be loaded", ex); } if (crypto != null) { String alias = decryptionAlias; if (alias == null) { alias = crypto.getDefaultX509Identifier(); } if (alias != null) { CallbackHandler callback = RSSecurityUtils.getCallbackHandler(message, this.getClass()); WSPasswordCallback passwordCallback = new WSPasswordCallback(alias, WSPasswordCallback.DECRYPT); callback.handle(new Callback[] {passwordCallback}); Key privateKey = crypto.getPrivateKey(alias, passwordCallback.getPassword()); properties.setDecryptionKey(privateKey); } } }
Example 2
Source File: IdpTest.java From cxf-fediz with Apache License 2.0 | 5 votes |
private static void signAuthnRequest(SignableSAMLObject signableObject) throws Exception { Crypto crypto = CryptoFactory.getInstance("stsKeystoreA.properties"); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias("realma"); X509Certificate[] issuerCerts = crypto.getX509Certificates(cryptoType); String sigAlgo = SSOConstants.RSA_SHA1; // Get the private key PrivateKey privateKey = crypto.getPrivateKey("realma", "realma"); // Create the signature Signature signature = OpenSAMLUtil.buildSignature(); signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); signature.setSignatureAlgorithm(sigAlgo); BasicX509Credential signingCredential = new BasicX509Credential(issuerCerts[0], privateKey); signature.setSigningCredential(signingCredential); X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory(); kiFactory.setEmitEntityCertificate(true); try { KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential); signature.setKeyInfo(keyInfo); } catch (org.opensaml.security.SecurityException ex) { throw new Exception( "Error generating KeyInfo from signing credential", ex); } signableObject.setSignature(signature); signableObject.releaseDOM(); signableObject.releaseChildrenDOM(true); }
Example 3
Source File: SamlRedirectBindingFilter.java From cxf with Apache License 2.0 | 4 votes |
/** * Sign a request according to the redirect binding spec for Web SSO */ private void signRequest( String authnRequest, String relayState, UriBuilder ub ) throws Exception { Crypto crypto = getSignatureCrypto(); if (crypto == null) { LOG.warning("No crypto instance of properties file configured for signature"); throw ExceptionUtils.toInternalServerErrorException(null, null); } String signatureUser = getSignatureUsername(); if (signatureUser == null) { LOG.warning("No user configured for signature"); throw ExceptionUtils.toInternalServerErrorException(null, null); } CallbackHandler callbackHandler = getCallbackHandler(); if (callbackHandler == null) { LOG.warning("No CallbackHandler configured to supply a password for signature"); throw ExceptionUtils.toInternalServerErrorException(null, null); } CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(signatureUser); X509Certificate[] issuerCerts = crypto.getX509Certificates(cryptoType); if (issuerCerts == null) { throw new Exception( "No issuer certs were found to sign the request using name: " + signatureUser ); } String sigAlgo = getSignatureAlgorithm(); String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm(); LOG.fine("automatic sig algo detection: " + pubKeyAlgo); if ("DSA".equalsIgnoreCase(pubKeyAlgo)) { sigAlgo = SSOConstants.DSA_SHA1; } LOG.fine("Using Signature algorithm " + sigAlgo); ub.queryParam(SSOConstants.SIG_ALG, URLEncoder.encode(sigAlgo, StandardCharsets.UTF_8.name())); // Get the password WSPasswordCallback[] cb = {new WSPasswordCallback(signatureUser, WSPasswordCallback.SIGNATURE)}; callbackHandler.handle(cb); String password = cb[0].getPassword(); // Get the private key PrivateKey privateKey = crypto.getPrivateKey(signatureUser, password); // Sign the request String jceSigAlgo = JCEMapper.translateURItoJCEID(sigAlgo); Signature signature = Signature.getInstance(jceSigAlgo); signature.initSign(privateKey); String requestToSign = SSOConstants.SAML_REQUEST + "=" + authnRequest + "&" + SSOConstants.RELAY_STATE + "=" + relayState + "&" + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(sigAlgo, StandardCharsets.UTF_8.name()); signature.update(requestToSign.getBytes(StandardCharsets.UTF_8)); byte[] signBytes = signature.sign(); String encodedSignature = Base64.getEncoder().encodeToString(signBytes); // Clean the private key from memory when we're done try { privateKey.destroy(); } catch (DestroyFailedException ex) { // ignore } ub.queryParam(SSOConstants.SIGNATURE, URLEncoder.encode(encodedSignature, StandardCharsets.UTF_8.name())); }
Example 4
Source File: SAMLResponseValidatorTest.java From cxf with Apache License 2.0 | 4 votes |
/** * Sign a SAML Response * @throws Exception */ private void signResponse( Response response, String issuerKeyName, String issuerKeyPassword, Crypto issuerCrypto, boolean useKeyInfo ) throws Exception { // // Create the signature // Signature signature = OpenSAMLUtil.buildSignature(); signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); // prepare to sign the SAML token CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(issuerKeyName); X509Certificate[] issuerCerts = issuerCrypto.getX509Certificates(cryptoType); if (issuerCerts == null) { throw new Exception( "No issuer certs were found to sign the SAML Assertion using issuer name: " + issuerKeyName); } String sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1; String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm(); if ("DSA".equalsIgnoreCase(pubKeyAlgo)) { sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_DSA; } PrivateKey privateKey = issuerCrypto.getPrivateKey(issuerKeyName, issuerKeyPassword); signature.setSignatureAlgorithm(sigAlgo); BasicX509Credential signingCredential = new BasicX509Credential(issuerCerts[0], privateKey); signature.setSigningCredential(signingCredential); if (useKeyInfo) { X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory(); kiFactory.setEmitEntityCertificate(true); try { KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential); signature.setKeyInfo(keyInfo); } catch (org.opensaml.security.SecurityException ex) { throw new Exception( "Error generating KeyInfo from signing credential", ex); } } // add the signature to the assertion SignableSAMLObject signableObject = response; signableObject.setSignature(signature); signableObject.releaseDOM(); signableObject.releaseChildrenDOM(true); }
Example 5
Source File: SAMLSSOResponseValidatorTest.java From cxf with Apache License 2.0 | 4 votes |
/** * Sign a SAML Response * @throws Exception */ private void signResponse( Response response, String issuerKeyName, String issuerKeyPassword, Crypto issuerCrypto, boolean useKeyInfo ) throws Exception { // // Create the signature // Signature signature = OpenSAMLUtil.buildSignature(); signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); // prepare to sign the SAML token CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(issuerKeyName); X509Certificate[] issuerCerts = issuerCrypto.getX509Certificates(cryptoType); if (issuerCerts == null) { throw new Exception( "No issuer certs were found to sign the SAML Assertion using issuer name: " + issuerKeyName); } String sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1; String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm(); if ("DSA".equalsIgnoreCase(pubKeyAlgo)) { sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_DSA; } PrivateKey privateKey = issuerCrypto.getPrivateKey(issuerKeyName, issuerKeyPassword); signature.setSignatureAlgorithm(sigAlgo); BasicX509Credential signingCredential = new BasicX509Credential(issuerCerts[0], privateKey); signature.setSigningCredential(signingCredential); if (useKeyInfo) { X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory(); kiFactory.setEmitEntityCertificate(true); try { KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential); signature.setKeyInfo(keyInfo); } catch (org.opensaml.security.SecurityException ex) { throw new Exception( "Error generating KeyInfo from signing credential", ex); } } // add the signature to the assertion SignableSAMLObject signableObject = response; signableObject.setSignature(signature); signableObject.releaseDOM(); signableObject.releaseChildrenDOM(true); }
Example 6
Source File: CombinedValidatorTest.java From cxf with Apache License 2.0 | 4 votes |
private void signResponse( Response response, String issuerKeyName, String issuerKeyPassword, Crypto issuerCrypto, boolean useKeyInfo ) throws Exception { // // Create the signature // Signature signature = OpenSAMLUtil.buildSignature(); signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); // prepare to sign the SAML token CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(issuerKeyName); X509Certificate[] issuerCerts = issuerCrypto.getX509Certificates(cryptoType); if (issuerCerts == null) { throw new Exception( "No issuer certs were found to sign the SAML Assertion using issuer name: " + issuerKeyName); } String sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1; String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm(); if ("DSA".equalsIgnoreCase(pubKeyAlgo)) { sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_DSA; } PrivateKey privateKey = issuerCrypto.getPrivateKey(issuerKeyName, issuerKeyPassword); signature.setSignatureAlgorithm(sigAlgo); BasicX509Credential signingCredential = new BasicX509Credential(issuerCerts[0], privateKey); signature.setSigningCredential(signingCredential); if (useKeyInfo) { X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory(); kiFactory.setEmitEntityCertificate(true); try { KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential); signature.setKeyInfo(keyInfo); } catch (org.opensaml.security.SecurityException ex) { throw new Exception("Error generating KeyInfo from signing credential", ex); } } // add the signature to the assertion SignableSAMLObject signableObject = response; signableObject.setSignature(signature); signableObject.releaseDOM(); signableObject.releaseChildrenDOM(true); }
Example 7
Source File: IdpTest.java From cxf-fediz with Apache License 2.0 | 4 votes |
@org.junit.Test public void testSeparateSignature() throws Exception { OpenSAMLUtil.initSamlEngine(); // Create SAML AuthnRequest String consumerURL = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; AuthnRequest authnRequest = new DefaultAuthnRequestBuilder().createAuthnRequest( null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL ); authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml"); String authnRequestEncoded = encodeAuthnRequest(authnRequest); String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, UTF_8.name()); String relayState = UUID.randomUUID().toString(); // Sign request Crypto crypto = CryptoFactory.getInstance("stsKeystoreA.properties"); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias("realma"); // Get the private key PrivateKey privateKey = crypto.getPrivateKey("realma", "realma"); java.security.Signature signature = java.security.Signature.getInstance("SHA1withRSA"); signature.initSign(privateKey); String requestToSign = SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest + "&" + SSOConstants.RELAY_STATE + "=" + relayState + "&" + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(SSOConstants.RSA_SHA1, UTF_8.name()); signature.update(requestToSign.getBytes(UTF_8)); byte[] signBytes = signature.sign(); String encodedSignature = Base64.getEncoder().encodeToString(signBytes); String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up?" + SSOConstants.RELAY_STATE + "=" + relayState + "&" + SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest + "&" + SSOConstants.SIGNATURE + "=" + URLEncoder.encode(encodedSignature, UTF_8.name()); final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(USER, PWD)); webClient.getOptions().setJavaScriptEnabled(false); final HtmlPage idpPage = webClient.getPage(url); webClient.getOptions().setJavaScriptEnabled(true); Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText()); org.opensaml.saml.saml2.core.Response samlResponse = parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID()); String expected = "urn:oasis:names:tc:SAML:2.0:status:Success"; Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue()); // Check claims String parsedResponse = DOM2Writer.nodeToString(samlResponse.getDOM().getOwnerDocument()); String claim = ClaimTypes.FIRSTNAME.toString(); Assert.assertTrue(parsedResponse.contains(claim)); claim = ClaimTypes.LASTNAME.toString(); Assert.assertTrue(parsedResponse.contains(claim)); claim = ClaimTypes.EMAILADDRESS.toString(); Assert.assertTrue(parsedResponse.contains(claim)); webClient.close(); }
Example 8
Source File: IdpTest.java From cxf-fediz with Apache License 2.0 | 4 votes |
@org.junit.Test public void testSeparateSignatureRSASHA256() throws Exception { OpenSAMLUtil.initSamlEngine(); // Create SAML AuthnRequest String consumerURL = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; AuthnRequest authnRequest = new DefaultAuthnRequestBuilder().createAuthnRequest( null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL ); authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml"); String authnRequestEncoded = encodeAuthnRequest(authnRequest); String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, UTF_8.name()); String relayState = UUID.randomUUID().toString(); // Sign request Crypto crypto = CryptoFactory.getInstance("stsKeystoreA.properties"); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias("realma"); // Get the private key PrivateKey privateKey = crypto.getPrivateKey("realma", "realma"); java.security.Signature signature = java.security.Signature.getInstance("SHA256withRSA"); signature.initSign(privateKey); String encodedSignatureAlgorithm = URLEncoder.encode("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", UTF_8.name()); String requestToSign = SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest + "&" + SSOConstants.RELAY_STATE + "=" + relayState + "&" + SSOConstants.SIG_ALG + "=" + encodedSignatureAlgorithm; signature.update(requestToSign.getBytes(UTF_8)); byte[] signBytes = signature.sign(); String encodedSignature = Base64.getEncoder().encodeToString(signBytes); String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up?" + SSOConstants.RELAY_STATE + "=" + relayState + "&" + SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest + "&" + SSOConstants.SIG_ALG + "=" + encodedSignatureAlgorithm + "&" + SSOConstants.SIGNATURE + "=" + URLEncoder.encode(encodedSignature, UTF_8.name()); final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(USER, PWD)); webClient.getOptions().setJavaScriptEnabled(false); final HtmlPage idpPage = webClient.getPage(url); webClient.getOptions().setJavaScriptEnabled(true); Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText()); org.opensaml.saml.saml2.core.Response samlResponse = parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID()); String expected = "urn:oasis:names:tc:SAML:2.0:status:Success"; Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue()); // Check claims String parsedResponse = DOM2Writer.nodeToString(samlResponse.getDOM().getOwnerDocument()); String claim = ClaimTypes.FIRSTNAME.toString(); Assert.assertTrue(parsedResponse.contains(claim)); claim = ClaimTypes.LASTNAME.toString(); Assert.assertTrue(parsedResponse.contains(claim)); claim = ClaimTypes.EMAILADDRESS.toString(); Assert.assertTrue(parsedResponse.contains(claim)); webClient.close(); }
Example 9
Source File: IdpTest.java From cxf-fediz with Apache License 2.0 | 4 votes |
@org.junit.Test public void testBase64DecodingErrorSeparateSignature() throws Exception { OpenSAMLUtil.initSamlEngine(); // Create SAML AuthnRequest String consumerURL = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; AuthnRequest authnRequest = new DefaultAuthnRequestBuilder().createAuthnRequest( null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL ); authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml"); String authnRequestEncoded = encodeAuthnRequest(authnRequest); String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, UTF_8.name()); String relayState = UUID.randomUUID().toString(); // Sign request Crypto crypto = CryptoFactory.getInstance("stsKeystoreA.properties"); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias("realma"); // Get the private key PrivateKey privateKey = crypto.getPrivateKey("realma", "realma"); java.security.Signature signature = java.security.Signature.getInstance("SHA1withRSA"); signature.initSign(privateKey); String requestToSign = SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest + "&" + SSOConstants.RELAY_STATE + "=" + relayState + "&" + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(SSOConstants.RSA_SHA1, UTF_8.name()); signature.update(requestToSign.getBytes(UTF_8)); byte[] signBytes = signature.sign(); String encodedSignature = Base64.getEncoder().encodeToString(signBytes); String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up?" + SSOConstants.RELAY_STATE + "=" + relayState + "&" + SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest + "&" + SSOConstants.SIGNATURE + "=" + URLEncoder.encode(encodedSignature, UTF_8.name()) + "-xyz"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(USER, PWD)); webClient.getOptions().setJavaScriptEnabled(false); final HtmlPage idpPage = webClient.getPage(url); org.opensaml.saml.saml2.core.Response samlResponse = parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID()); String expected = "urn:oasis:names:tc:SAML:2.0:status:Requester"; Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue()); webClient.close(); }
Example 10
Source File: IdpTest.java From cxf-fediz with Apache License 2.0 | 4 votes |
@org.junit.Test public void testChangedSeparateSignature() throws Exception { OpenSAMLUtil.initSamlEngine(); // Create SAML AuthnRequest String consumerURL = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; AuthnRequest authnRequest = new DefaultAuthnRequestBuilder().createAuthnRequest( null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL ); authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml"); String authnRequestEncoded = encodeAuthnRequest(authnRequest); String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, UTF_8.name()); String relayState = UUID.randomUUID().toString(); // Sign request Crypto crypto = CryptoFactory.getInstance("stsKeystoreA.properties"); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias("realma"); // Get the private key PrivateKey privateKey = crypto.getPrivateKey("realma", "realma"); java.security.Signature signature = java.security.Signature.getInstance("SHA1withRSA"); signature.initSign(privateKey); String requestToSign = SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest + "&" + SSOConstants.RELAY_STATE + "=" + relayState + "&" + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(SSOConstants.RSA_SHA1, UTF_8.name()); signature.update(requestToSign.getBytes(UTF_8)); byte[] signBytes = signature.sign(); if (signBytes[1] != (byte)1) { signBytes[1] = (byte)1; } else { signBytes[1] = (byte)2; } String encodedSignature = Base64.getEncoder().encodeToString(signBytes); String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up?" + SSOConstants.RELAY_STATE + "=" + relayState + "&" + SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest + "&" + SSOConstants.SIGNATURE + "=" + URLEncoder.encode(encodedSignature, UTF_8.name()); final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(USER, PWD)); webClient.getOptions().setJavaScriptEnabled(false); final HtmlPage idpPage = webClient.getPage(url); org.opensaml.saml.saml2.core.Response samlResponse = parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID()); String expected = "urn:oasis:names:tc:SAML:2.0:status:Requester"; Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue()); webClient.close(); }
Example 11
Source File: IdpTest.java From cxf-fediz with Apache License 2.0 | 4 votes |
@org.junit.Test public void testSeparateSignatureWrongSignedContent() throws Exception { OpenSAMLUtil.initSamlEngine(); // Create SAML AuthnRequest String consumerURL = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; AuthnRequest authnRequest = new DefaultAuthnRequestBuilder().createAuthnRequest( null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL ); authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml"); String authnRequestEncoded = encodeAuthnRequest(authnRequest); String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, UTF_8.name()); String relayState = UUID.randomUUID().toString(); // Sign request Crypto crypto = CryptoFactory.getInstance("stsKeystoreA.properties"); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias("realma"); // Get the private key PrivateKey privateKey = crypto.getPrivateKey("realma", "realma"); java.security.Signature signature = java.security.Signature.getInstance("SHA1withRSA"); signature.initSign(privateKey); String requestToSign = SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest + "&" + SSOConstants.RELAY_STATE + "=" + relayState + "&" + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(SSOConstants.RSA_SHA1, UTF_8.name()) + "asf=xyz"; signature.update(requestToSign.getBytes(UTF_8)); byte[] signBytes = signature.sign(); String encodedSignature = Base64.getEncoder().encodeToString(signBytes); String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up?" + SSOConstants.RELAY_STATE + "=" + relayState + "&" + SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest + "&" + SSOConstants.SIGNATURE + "=" + URLEncoder.encode(encodedSignature, UTF_8.name()); final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(USER, PWD)); webClient.getOptions().setJavaScriptEnabled(false); final HtmlPage idpPage = webClient.getPage(url); org.opensaml.saml.saml2.core.Response samlResponse = parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID()); String expected = "urn:oasis:names:tc:SAML:2.0:status:Requester"; Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue()); webClient.close(); }
Example 12
Source File: TrustedIdpSAMLProtocolHandler.java From cxf-fediz with Apache License 2.0 | 4 votes |
/** * Sign a request according to the redirect binding spec for Web SSO */ private void signRequest( String authnRequest, String relayState, Idp config, UriBuilder ub ) throws Exception { Crypto crypto = CertsUtils.getCryptoFromCertificate(config.getCertificate()); if (crypto == null) { LOG.error("No crypto instance of properties file configured for signature"); throw new IllegalStateException("Invalid IdP configuration"); } String alias = crypto.getDefaultX509Identifier(); X509Certificate cert = CertsUtils.getX509CertificateFromCrypto(crypto, alias); if (cert == null) { LOG.error("No cert was found to sign the request using alias: " + alias); throw new IllegalStateException("Invalid IdP configuration"); } String sigAlgo = SSOConstants.RSA_SHA1; String pubKeyAlgo = cert.getPublicKey().getAlgorithm(); String jceSigAlgo = "SHA1withRSA"; LOG.debug("automatic sig algo detection: " + pubKeyAlgo); if ("DSA".equalsIgnoreCase(pubKeyAlgo)) { sigAlgo = SSOConstants.DSA_SHA1; jceSigAlgo = "SHA1withDSA"; } LOG.debug("Using Signature algorithm " + sigAlgo); ub.queryParam(SSOConstants.SIG_ALG, URLEncoder.encode(sigAlgo, "UTF-8")); // Get the password String password = config.getCertificatePassword(); // Get the private key PrivateKey privateKey = crypto.getPrivateKey(alias, password); // Sign the request Signature signature = Signature.getInstance(jceSigAlgo); signature.initSign(privateKey); String requestToSign = SSOConstants.SAML_REQUEST + "=" + authnRequest + "&" + SSOConstants.RELAY_STATE + "=" + relayState + "&" + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(sigAlgo, "UTF-8"); signature.update(requestToSign.getBytes(StandardCharsets.UTF_8)); byte[] signBytes = signature.sign(); String encodedSignature = Base64.getEncoder().encodeToString(signBytes); ub.queryParam(SSOConstants.SIGNATURE, URLEncoder.encode(encodedSignature, "UTF-8")); }
Example 13
Source File: SAMLProcessorImpl.java From cxf-fediz with Apache License 2.0 | 4 votes |
/** * Sign a request according to the redirect binding spec for Web SSO */ private String signRequest( FedizContext config, StringBuilder sb ) throws Exception { Crypto crypto = config.getSigningKey().getCrypto(); if (crypto == null) { LOG.debug("No crypto instance of properties file configured for signature"); throw new ProcessingException("Failed to Sign Request"); } String signatureUser = config.getSigningKey().getKeyAlias(); if (signatureUser == null) { LOG.debug("No user configured for signature"); throw new ProcessingException("Failed to Sign Request"); } String signaturePassword = config.getSigningKey().getKeyPassword(); if (signaturePassword == null) { LOG.debug("No signature password available"); throw new ProcessingException("Failed to Sign Request"); } // Get the private key PrivateKey privateKey = crypto.getPrivateKey(signatureUser, signaturePassword); if (privateKey == null) { LOG.debug("No private key available"); throw new ProcessingException("Failed to Sign Request"); } String sigAlgo = WSConstants.RSA_SHA1; String jceSigAlgo = "SHA1withRSA"; LOG.debug("automatic sig algo detection: " + privateKey.getAlgorithm()); if (privateKey.getAlgorithm().equalsIgnoreCase("DSA")) { sigAlgo = WSConstants.DSA; jceSigAlgo = "SHA1withDSA"; } else { switch(((SAMLProtocol)config.getProtocol()).getSignRequestAlgorithm()) { case RSA_SHA1: sigAlgo = WSConstants.RSA_SHA1; jceSigAlgo = "SHA1withRSA"; break; case RSA_SHA256: sigAlgo = WSConstants.RSA_SHA256; jceSigAlgo = "SHA256withRSA"; break; default: throw new ProcessingException("Unknown sign algorithm"); } } LOG.debug("Using Signature algorithm " + sigAlgo); // Sign the request Signature signature = Signature.getInstance(jceSigAlgo); signature.initSign(privateKey); sb.append('&').append(SAMLSSOConstants.SIG_ALG).append('=').append(URLEncoder.encode(sigAlgo, "UTF-8")); String requestToSign = sb.toString(); signature.update(requestToSign.getBytes(StandardCharsets.UTF_8)); byte[] signBytes = signature.sign(); String encodedSignature = Base64.getEncoder().encodeToString(signBytes); // Clean the private key from memory when we're done try { privateKey.destroy(); } catch (DestroyFailedException ex) { // ignore } return URLEncoder.encode(encodedSignature, "UTF-8"); }