[jboss-identity-commits] JBoss Identity SVN: r219 - in identity-federation/trunk: identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/idp and 7 other directories.

jboss-identity-commits at lists.jboss.org jboss-identity-commits at lists.jboss.org
Thu Jan 15 13:28:01 EST 2009


Author: anil.saldhana at jboss.com
Date: 2009-01-15 13:28:01 -0500 (Thu, 15 Jan 2009)
New Revision: 219

Added:
   identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/idp/IDPRedirectWithSignatureValve.java
   identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/util/RedirectBindingUtil.java
   identity-federation/trunk/identity-bindings/src/test/java/org/jboss/test/identity/federation/bindings/util/KeystoreUtilUnitTestCase.java
   identity-federation/trunk/identity-bindings/src/test/resources/keystore/
   identity-federation/trunk/identity-bindings/src/test/resources/keystore/jbid_test_keystore.jks
Modified:
   identity-federation/trunk/identity-bindings/.classpath
   identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/idp/IDPRedirectValve.java
   identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/sp/SPRedirectFormAuthenticator.java
   identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/sp/SPRedirectValve.java
   identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/util/RedirectBindingSignatureUtil.java
   identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/util/cert/KeyStoreUtil.java
   identity-federation/trunk/identity-fed-core/src/main/java/org/jboss/identity/federation/core/saml/v2/util/SignatureUtil.java
Log:
additional keystore/sig work

Modified: identity-federation/trunk/identity-bindings/.classpath
===================================================================
--- identity-federation/trunk/identity-bindings/.classpath	2009-01-15 01:15:52 UTC (rev 218)
+++ identity-federation/trunk/identity-bindings/.classpath	2009-01-15 18:28:01 UTC (rev 219)
@@ -1,6 +1,8 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <classpath>
 	<classpathentry kind="src" path="src/main/java"/>
+	<classpathentry kind="src" path="src/main/resources"/>
+	<classpathentry kind="src" path="src/test/resources"/>
 	<classpathentry kind="src" path="src/test/java"/>
 	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
 	<classpathentry kind="var" path="M2_REPO/apache-tomcat/catalina/5.5.12/catalina-5.5.12.jar"/>

Modified: identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/idp/IDPRedirectValve.java
===================================================================
--- identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/idp/IDPRedirectValve.java	2009-01-15 01:15:52 UTC (rev 218)
+++ identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/idp/IDPRedirectValve.java	2009-01-15 18:28:01 UTC (rev 219)
@@ -21,10 +21,10 @@
  */
 package org.jboss.identity.federation.bindings.tomcat.idp;
 
+import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.StringWriter;
-import java.net.URLEncoder;
 import java.security.Principal;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -44,9 +44,8 @@
 import org.jboss.identity.federation.api.saml.v2.common.IDGenerator;
 import org.jboss.identity.federation.api.saml.v2.request.SAML2Request;
 import org.jboss.identity.federation.api.saml.v2.response.SAML2Response;
-import org.jboss.identity.federation.api.util.Base64;
-import org.jboss.identity.federation.api.util.DeflateUtil;
 import org.jboss.identity.federation.bindings.util.HTTPRedirectUtil;
+import org.jboss.identity.federation.bindings.util.RedirectBindingUtil;
 import org.jboss.identity.federation.core.saml.v2.constants.JBossSAMLURIConstants;
 import org.jboss.identity.federation.core.saml.v2.holders.IDPInfoHolder;
 import org.jboss.identity.federation.core.saml.v2.holders.IssuerInfoHolder;
@@ -82,10 +81,8 @@
    @Override
    public void invoke(Request request, Response response) throws IOException, ServletException
    {
-      //request.setCharacterEncoding("UTF-8");
+      boolean containsSAMLRequestMessage = this.hasSAMLRequestMessage(request);
 
-      boolean containsSAMLRequestMessage = this.isSAMLRequestMessage(request);
-
       //Lets check if the user has been authenticated
       Principal userPrincipal = request.getUserPrincipal();
       if(userPrincipal == null)
@@ -114,35 +111,38 @@
                      SAML2Response saml2Response = new SAML2Response();
                      
                      ResponseType responseType = this.getResponse(request, userPrincipal);
-                     StringWriter stringWriter = new StringWriter();
-                     saml2Response.marshall(responseType, stringWriter);
+                     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
+                     saml2Response.marshall(responseType, baos);
 
-                     String responseMessage = stringWriter.toString();
-
-                     //Deflate encoding
-                     byte[] deflatedMsg = DeflateUtil.encode(responseMessage); 
-
-                     String base64Response = Base64.encodeBytes(deflatedMsg, Base64.DONT_BREAK_LINES); 
-
+                     String encodedResponse = RedirectBindingUtil.deflateBase64URLEncode(baos.toByteArray());
+ 
                      String destination = responseType.getDestination();
                      log.trace("IDP:Destination=" + destination);
-                     base64Response = URLEncoder.encode(base64Response, "UTF-8");
-
-                     HTTPRedirectUtil.sendRedirectForRequestor(destination + "?SAMLResponse=" + base64Response,response); 
+                     
+                     HTTPRedirectUtil.sendRedirectForResponder(destination + "?SAMLResponse=" + encodedResponse,response); 
                   }
                   catch (Exception e)
                   { 
                      log.error("Exception:" ,e);
                      throw new ServletException(e.getLocalizedMessage());
                   } 
-               }         
+               }
+               else
+               {
+                  throw new ServletException("No SAML Request Message");
+               }
             }
          }
       }   
    }
 
-   private boolean isSAMLRequestMessage(Request request)
+   protected boolean validate(Request request) throws Exception
    {
+     return this.hasSAMLRequestMessage(request);     
+   }
+   
+   private boolean hasSAMLRequestMessage(Request request)
+   {
       return request.getParameter("SAMLRequest") != null;
    }
 
@@ -150,9 +150,8 @@
    {
       ResponseType responseType = null;
 
-      byte[] decodedMessage = Base64.decode(getSAMLMessage(request));
-
-      InputStream is = DeflateUtil.decode(decodedMessage); 
+      String samlMessage = getSAMLMessage(request);
+      InputStream is = RedirectBindingUtil.urlBase64DeflateDecode(samlMessage); 
       SAML2Request saml2Request = new SAML2Request();
       
       AuthnRequestType authnRequestType = saml2Request.getAuthnRequestType(is);
@@ -225,9 +224,8 @@
             }
          }
       return userRoles;
-   }
+   } 
 
-
    private String getSAMLMessage(Request request)
    {
       return request.getParameter("SAMLRequest");

Added: identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/idp/IDPRedirectWithSignatureValve.java
===================================================================
--- identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/idp/IDPRedirectWithSignatureValve.java	                        (rev 0)
+++ identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/idp/IDPRedirectWithSignatureValve.java	2009-01-15 18:28:01 UTC (rev 219)
@@ -0,0 +1,96 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.identity.federation.bindings.tomcat.idp;
+
+import java.security.KeyStore;
+import java.security.PublicKey;
+
+import org.apache.catalina.connector.Request;
+import org.jboss.identity.federation.bindings.util.RedirectBindingSignatureUtil;
+import org.jboss.identity.federation.bindings.util.cert.KeyStoreUtil;
+import org.jboss.identity.federation.core.saml.v2.util.SignatureUtil;
+
+
+/**
+ * Valve at the Identity Provider that supports
+ * SAML2 HTTP/Redirect binding with digital signature support
+ * @author Anil.Saldhana at redhat.com
+ * @since Jan 14, 2009
+ */
+public class IDPRedirectWithSignatureValve extends IDPRedirectValve
+{  
+   private String keyStore;
+   private char[] keypass;
+   private String alias;
+
+   public void setKeyStore(String keyStore)
+   {
+      this.keyStore = keyStore;
+   }
+   
+   public void setKeyStorePassword(String keypass)
+   {
+      this.keypass = keypass.toCharArray();
+   }
+   
+   public void setAlias(String alias)
+   {
+      this.alias = alias;
+   }
+   
+   protected boolean validate(Request request) throws Exception
+   {
+      boolean result = super.validate(request);
+      if( result == false)
+         return result;
+      
+      String queryString = request.getQueryString();
+      //Check if there is a signature   
+      byte[] sigValue = RedirectBindingSignatureUtil.getSignatureValueFromSignedURL(queryString);
+      if(sigValue == null)
+         return false;
+      
+      //Construct the url again
+      String reqFromURL = RedirectBindingSignatureUtil.getTokenValue(queryString, "SAMLRequest"); 
+      String relayStateFromURL = RedirectBindingSignatureUtil.getTokenValue(queryString, "RelayState");
+      String sigAlgFromURL = RedirectBindingSignatureUtil.getTokenValue(queryString, "SigAlg"); 
+
+      StringBuilder sb = new StringBuilder();
+      sb.append("SAMLRequest=").append(reqFromURL);
+       
+      if(relayStateFromURL != null && relayStateFromURL.length() > 0)
+      {
+         sb.append("&RelayState=").append(relayStateFromURL);
+      }
+      sb.append("&SigAlg=").append(sigAlgFromURL);
+      
+      PublicKey validatingKey = getValidatingKey();
+      boolean isValid = SignatureUtil.validate(sb.toString().getBytes("UTF-8"), sigValue, validatingKey);
+      return isValid;     
+   }
+   
+   private PublicKey getValidatingKey() throws Exception
+   {
+      KeyStore ks = KeyStoreUtil.getKeyStore(keyStore, keypass);
+      return KeyStoreUtil.getPublicKey(ks, alias, keypass);
+   }
+}
\ No newline at end of file

Modified: identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/sp/SPRedirectFormAuthenticator.java
===================================================================
--- identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/sp/SPRedirectFormAuthenticator.java	2009-01-15 01:15:52 UTC (rev 218)
+++ identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/sp/SPRedirectFormAuthenticator.java	2009-01-15 18:28:01 UTC (rev 219)
@@ -40,7 +40,7 @@
 import org.jboss.identity.federation.api.util.Base64;
 import org.jboss.identity.federation.api.util.DeflateUtil;
 import org.jboss.identity.federation.bindings.util.HTTPRedirectUtil;
-import org.jboss.identity.federation.bindings.util.RedirectBindingSignatureUtil;
+import org.jboss.identity.federation.bindings.util.RedirectBindingUtil;
 import org.jboss.identity.federation.core.saml.v2.exceptions.AssertionExpiredException;
 import org.jboss.identity.federation.saml.v2.protocol.AuthnRequestType;
 import org.jboss.identity.federation.saml.v2.protocol.ResponseType;
@@ -90,7 +90,7 @@
          if(p == null)
          {
             String destination = createSAMLRequestMessage("someuser", relayState, response); 
-            HTTPRedirectUtil.sendRedirectForResponder(destination, response);
+            HTTPRedirectUtil.sendRedirectForRequestor(destination, response);
             
             return false;
          }
@@ -108,7 +108,7 @@
          try
          {
             String destination = createSAMLRequestMessage("someuser", relayState, response); 
-            HTTPRedirectUtil.sendRedirectForResponder(destination, response);
+            HTTPRedirectUtil.sendRedirectForRequestor(destination, response);
          }
          catch (Exception e)
          {
@@ -144,7 +144,7 @@
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       saml2Request.marshall(authnRequest, baos);
  
-      String base64Request = RedirectBindingSignatureUtil.deflateBase64URLEncode(baos.toByteArray());
+      String base64Request = RedirectBindingUtil.deflateBase64URLEncode(baos.toByteArray());
       String destination = authnRequest.getDestination() + getDestination(base64Request, relayState); 
       log.debug("Sending to destination="+destination);
          

Modified: identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/sp/SPRedirectValve.java
===================================================================
--- identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/sp/SPRedirectValve.java	2009-01-15 01:15:52 UTC (rev 218)
+++ identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/sp/SPRedirectValve.java	2009-01-15 18:28:01 UTC (rev 219)
@@ -38,7 +38,7 @@
 import org.jboss.identity.federation.api.saml.v2.request.SAML2Request;
 import org.jboss.identity.federation.api.saml.v2.response.SAML2Response;
 import org.jboss.identity.federation.bindings.util.HTTPRedirectUtil;
-import org.jboss.identity.federation.bindings.util.RedirectBindingSignatureUtil;
+import org.jboss.identity.federation.bindings.util.RedirectBindingUtil;
 import org.jboss.identity.federation.saml.v2.protocol.AuthnRequestType;
 import org.jboss.identity.federation.saml.v2.protocol.ResponseType;
 
@@ -77,7 +77,7 @@
             if(samlResponse != null && samlResponse.length() > 0 )
             {
                //deal with saml response from IDP 
-               InputStream is = RedirectBindingSignatureUtil.urlBase64DeflateDecode(samlResponse); 
+               InputStream is = RedirectBindingUtil.urlBase64DeflateDecode(samlResponse); 
 
                SAML2Response saml2Response = new SAML2Response();
                
@@ -106,8 +106,9 @@
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                saml2Request.marshall(authnRequest, baos);
  
-               String base64Request = RedirectBindingSignatureUtil.deflateBase64URLEncode(baos.toByteArray());
-               String destination = authnRequest.getDestination() + "?SAMLRequest=" + base64Request; 
+               String base64Request = RedirectBindingUtil.deflateBase64URLEncode(baos.toByteArray());
+               String destination = authnRequest.getDestination() + 
+                  getDestinationURL(base64Request, null); 
                log.trace("Sending to destination="+destination);
                log.trace("                                                           ");
                
@@ -132,4 +133,14 @@
       response.recycle();
       getNext().invoke(request, response);
    }
+   
+   
+   protected String getDestinationURL(String urlEncodedRequest, String urlEncodedRelayState)
+   {
+     StringBuilder sb = new StringBuilder();
+     sb.append("SAMLRequest=").append(urlEncodedRequest);
+     if(urlEncodedRelayState != null && urlEncodedRelayState.length() > 0)
+        sb.append("&RelayState=").append(urlEncodedRelayState);
+     return sb.toString();
+   }
 }
\ No newline at end of file

Modified: identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/util/RedirectBindingSignatureUtil.java
===================================================================
--- identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/util/RedirectBindingSignatureUtil.java	2009-01-15 01:15:52 UTC (rev 218)
+++ identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/util/RedirectBindingSignatureUtil.java	2009-01-15 18:28:01 UTC (rev 219)
@@ -21,15 +21,11 @@
  */
 package org.jboss.identity.federation.bindings.util;
 
-import java.io.InputStream;
 import java.io.StringWriter;
-import java.net.URLDecoder;
 import java.net.URLEncoder;
 import java.security.PrivateKey;
 
 import org.jboss.identity.federation.api.saml.v2.request.SAML2Request;
-import org.jboss.identity.federation.api.util.Base64;
-import org.jboss.identity.federation.api.util.DeflateUtil;
 import org.jboss.identity.federation.core.saml.v2.util.SignatureUtil;
 import org.jboss.identity.federation.saml.v2.protocol.AuthnRequestType;
  
@@ -59,7 +55,7 @@
       saml2Request.marshall(authRequest, sw);
       
       //URL Encode the Request
-      String urlEncodedRequest = deflateBase64URLEncode(sw.toString()); 
+      String urlEncodedRequest = RedirectBindingUtil.deflateBase64URLEncode(sw.toString()); 
     
       String urlEncodedRelayState = null;
       if(relayState != null && relayState.length() > 0 )
@@ -97,7 +93,7 @@
       String samlRequestTokenValue =  getTokenValue(signedURL, "SAMLRequest");
       
       SAML2Request saml2Request = new SAML2Request();
-      return saml2Request.getAuthnRequestType(urlBase64DeflateDecode(samlRequestTokenValue));
+      return saml2Request.getAuthnRequestType(RedirectBindingUtil.urlBase64DeflateDecode(samlRequestTokenValue));
    }
 
    /**
@@ -110,69 +106,11 @@
    { 
       String sigValueTokenValue =  getTokenValue(signedURL,"Signature");
       
-      return urlBase64Decode(sigValueTokenValue); 
+      return RedirectBindingUtil.urlBase64Decode(sigValueTokenValue); 
    }
    
-   /**
-    * On the byte array, apply base64 encoding following by URL encoding
-    * @param stringToEncode
-    * @return
-    * @throws Exception
-    */
-   public static String base64URLEncode(byte[] stringToEncode) throws Exception
-   {
-      String base64Request = Base64.encodeBytes(stringToEncode, Base64.DONT_BREAK_LINES); 
-      return URLEncoder.encode(base64Request, "UTF-8");
-   }
    
    /**
-    * On the byte array, apply URL decoding followed by base64 decoding
-    * @param encodedString
-    * @return
-    * @throws Exception
-    */
-   public static byte[] urlBase64Decode(String encodedString) throws Exception
-   {
-      String decodedString = URLDecoder.decode(encodedString, "UTF-8");
-      return Base64.decode(decodedString);
-   } 
-   
-   /**
-    * Apply deflate compression followed by base64 encoding and URL encoding
-    * @param stringToEncode
-    * @return
-    * @throws Exception
-    */
-   public static String deflateBase64URLEncode(String stringToEncode) throws Exception
-   {
-      return deflateBase64URLEncode(stringToEncode.getBytes("UTF-8")); 
-   }
-   
-   /**
-    * Apply deflate compression followed by base64 encoding and URL encoding
-    * @param stringToEncode
-    * @return
-    * @throws Exception
-    */
-   public static String deflateBase64URLEncode(byte[] stringToEncode) throws Exception
-   {
-      byte[] deflatedMsg = DeflateUtil.encode(stringToEncode); 
-      return base64URLEncode(deflatedMsg); 
-   }
-   
-   /**
-    * Apply URL decoding, followed by base64 decoding followed by deflate decompression
-    * @param encodedString
-    * @return
-    * @throws Exception
-    */
-   public static InputStream urlBase64DeflateDecode(String encodedString) throws Exception
-   {
-      byte[] deflatedString  = urlBase64Decode(encodedString);
-      return DeflateUtil.decode(deflatedString);
-   }
-   
-   /**
     * From the query string that contains key/value pairs, get the value of a key
     * <b>Note:</b> if the token is null, a null value is returned
     * @param queryString
@@ -226,7 +164,7 @@
       sb.append("&").append("SigAlg=").append(sigAlg);
       
       //Encode the signature value
-      String encodedSig = base64URLEncode(signature);
+      String encodedSig = RedirectBindingUtil.base64URLEncode(signature);
       
       sb.append("&").append("Signature=").append(encodedSig);
       

Added: identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/util/RedirectBindingUtil.java
===================================================================
--- identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/util/RedirectBindingUtil.java	                        (rev 0)
+++ identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/util/RedirectBindingUtil.java	2009-01-15 18:28:01 UTC (rev 219)
@@ -0,0 +1,96 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.identity.federation.bindings.util;
+
+import java.io.InputStream;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+
+import org.jboss.identity.federation.api.util.Base64;
+import org.jboss.identity.federation.api.util.DeflateUtil;
+
+/**
+ * Utility class for SAML HTTP/Redirect binding
+ * @author Anil.Saldhana at redhat.com
+ * @since Jan 14, 2009
+ */
+public class RedirectBindingUtil
+{
+   /**
+    * On the byte array, apply base64 encoding following by URL encoding
+    * @param stringToEncode
+    * @return
+    * @throws Exception
+    */
+   public static String base64URLEncode(byte[] stringToEncode) throws Exception
+   {
+      String base64Request = Base64.encodeBytes(stringToEncode, Base64.DONT_BREAK_LINES); 
+      return URLEncoder.encode(base64Request, "UTF-8");
+   }
+   
+   /**
+    * On the byte array, apply URL decoding followed by base64 decoding
+    * @param encodedString
+    * @return
+    * @throws Exception
+    */
+   public static byte[] urlBase64Decode(String encodedString) throws Exception
+   {
+      String decodedString = URLDecoder.decode(encodedString, "UTF-8");
+      return Base64.decode(decodedString);
+   } 
+   
+   /**
+    * Apply deflate compression followed by base64 encoding and URL encoding
+    * @param stringToEncode
+    * @return
+    * @throws Exception
+    */
+   public static String deflateBase64URLEncode(String stringToEncode) throws Exception
+   {
+      return deflateBase64URLEncode(stringToEncode.getBytes("UTF-8")); 
+   }
+   
+   /**
+    * Apply deflate compression followed by base64 encoding and URL encoding
+    * @param stringToEncode
+    * @return
+    * @throws Exception
+    */
+   public static String deflateBase64URLEncode(byte[] stringToEncode) throws Exception
+   {
+      byte[] deflatedMsg = DeflateUtil.encode(stringToEncode); 
+      return base64URLEncode(deflatedMsg); 
+   }
+   
+   /**
+    * Apply URL decoding, followed by base64 decoding followed by deflate decompression
+    * @param encodedString
+    * @return
+    * @throws Exception
+    */
+   public static InputStream urlBase64DeflateDecode(String encodedString) throws Exception
+   {
+      byte[] deflatedString  = urlBase64Decode(encodedString);
+      return DeflateUtil.decode(deflatedString);
+   }
+}
\ No newline at end of file

Modified: identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/util/cert/KeyStoreUtil.java
===================================================================
--- identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/util/cert/KeyStoreUtil.java	2009-01-15 01:15:52 UTC (rev 218)
+++ identity-federation/trunk/identity-bindings/src/main/java/org/jboss/identity/federation/bindings/util/cert/KeyStoreUtil.java	2009-01-15 18:28:01 UTC (rev 219)
@@ -24,10 +24,16 @@
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
 import java.security.GeneralSecurityException;
+import java.security.Key;
 import java.security.KeyPair;
 import java.security.KeyPairGenerator;
 import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.cert.Certificate;
 
 /**
  * Utility to handle Java Keystore
@@ -36,20 +42,94 @@
  */
 public class KeyStoreUtil
 { 
-   public static KeyStore getKeyStore(String url, char[] password) throws GeneralSecurityException, IOException
+   /**
+    * Get the Keystore given the url to the keystore file as a string
+    * @param fileURL
+    * @param password
+    * @return
+    * @throws GeneralSecurityException
+    * @throws IOException
+    */
+   public static KeyStore getKeyStore(String fileURL, char[] password) throws GeneralSecurityException, IOException
    {
-      File file = new File(url);
+      if(fileURL == null)
+         throw new IllegalArgumentException("fileURL is null");
+      
+      File file = new File(fileURL);
       FileInputStream fis = new FileInputStream(file);
+      return getKeyStore(fis,password);
+   }
+   
+   /**
+    * Get the Keystore given the URL to the keystore
+    * @param url
+    * @param password
+    * @return
+    * @throws GeneralSecurityException
+    * @throws IOException
+    */
+   public static KeyStore getKeyStore(URL url, char[] password) throws GeneralSecurityException, IOException
+   {
+      if(url == null)
+         throw new IllegalArgumentException("url is null");
       
+      return getKeyStore(url.openStream(), password);
+   }
+   
+   /**
+    * Get the Key Store
+    * <b>Note:</b> This method wants the InputStream to be not null. 
+    * @param ksStream
+    * @param password
+    * @return
+    * @throws GeneralSecurityException
+    * @throws IOException
+    * @throws IllegalArgumentException if ksStream is null
+    */
+   public static KeyStore getKeyStore(InputStream ksStream, char[] password) throws GeneralSecurityException, IOException
+   {
+      if(ksStream == null)
+         throw new IllegalArgumentException("InputStream for the KeyStore is null");
       KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
-      ks.load(fis, password);
+      ks.load(ksStream, password);
       return ks;
    }
    
+   /**
+    * Generate a Key Pair
+    * @param algo (RSA, DSA etc)
+    * @return
+    * @throws Exception
+    */
    public static KeyPair generateKeyPair(String algo) throws Exception
    {
       KeyPairGenerator kpg = KeyPairGenerator.getInstance(algo);
       return kpg.genKeyPair();
    }
    
+   /**
+    * Get the Public Key from the keystore
+    * @param ks
+    * @param alias
+    * @param password
+    * @return
+    * @throws Exception
+    */
+   public static PublicKey getPublicKey(KeyStore ks, String alias, char[] password) throws Exception
+   {
+      PublicKey publicKey = null;
+      
+      // Get private key
+      Key key = ks.getKey(alias, password);
+      if (key instanceof PrivateKey) 
+      {
+         // Get certificate of public key
+         Certificate cert = ks.getCertificate(alias);
+
+         // Get public key
+         publicKey = cert.getPublicKey();
+      }
+      
+      return publicKey;      
+   }
 }
\ No newline at end of file

Added: identity-federation/trunk/identity-bindings/src/test/java/org/jboss/test/identity/federation/bindings/util/KeystoreUtilUnitTestCase.java
===================================================================
--- identity-federation/trunk/identity-bindings/src/test/java/org/jboss/test/identity/federation/bindings/util/KeystoreUtilUnitTestCase.java	                        (rev 0)
+++ identity-federation/trunk/identity-bindings/src/test/java/org/jboss/test/identity/federation/bindings/util/KeystoreUtilUnitTestCase.java	2009-01-15 18:28:01 UTC (rev 219)
@@ -0,0 +1,93 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.identity.federation.bindings.util;
+
+import java.io.InputStream;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.util.Enumeration;
+
+import junit.framework.TestCase;
+
+import org.jboss.identity.federation.bindings.util.cert.KeyStoreUtil;
+import org.jboss.identity.federation.core.saml.v2.util.SignatureUtil;
+
+/**
+ * Test the KeyStore Util
+ * @author Anil.Saldhana at redhat.com
+ * @since Jan 15, 2009
+ */
+public class KeystoreUtilUnitTestCase extends TestCase
+{
+
+   /**
+    * Keystore (created 15Jan2009 and valid for 200K days)
+    * The Keystore has been created with the command (all in one line) 
+keytool -genkey -alias servercert 
+                -keyalg RSA 
+                -keysize 1024 
+                -dname "CN=jbossidentity.jboss.org,OU=RD,O=JBOSS,L=Chicago,S=Illinois,C=US" 
+                -keypass test123 
+                -keystore jbid_test_keystore.jks 
+                -storepass store123 
+                -validity 200000
+    */
+   private String keystoreLocation = "keystore/jbid_test_keystore.jks";
+   private String keystorePass = "store123";
+   private String alias = "servercert";
+   private String keyPass = "test123";
+   
+   
+   /**
+    Generated a selfsigned cert
+    keytool -selfcert 
+             -alias servercert 
+             -keypass test123 
+             -keystore jbid_test_keystore.jks  
+             -dname "cn=jbid test, ou=JBoss, o=JBoss, c=US" 
+             -storepass store123 
+    */
+   public void testSignatureValidationInvalidation() throws Exception
+   {
+      ClassLoader tcl = Thread.currentThread().getContextClassLoader();
+      InputStream ksStream = tcl.getResourceAsStream(keystoreLocation);
+      assertNotNull("Input keystore stream is not null", ksStream);
+      
+      KeyStore ks = KeyStoreUtil.getKeyStore(ksStream, keystorePass.toCharArray());
+      assertNotNull("KeyStore is not null",ks);
+         
+      //Check that there are aliases in the keystore
+      Enumeration<String> aliases = ks.aliases();
+      assertTrue("Aliases are not empty", aliases.hasMoreElements());
+      
+      PublicKey publicKey = KeyStoreUtil.getPublicKey(ks, alias, keyPass.toCharArray());
+      assertNotNull("Public Key is not null", publicKey);
+      
+      PrivateKey privateKey = (PrivateKey) ks.getKey(alias, keyPass.toCharArray());
+ 
+      String content = "Hello";
+      byte[] sigValue = SignatureUtil.sign(content, privateKey);
+      boolean isValid = SignatureUtil.validate(content.getBytes("UTF-8"), sigValue, publicKey);
+      assertTrue("Valid sig?", isValid);
+   }
+}
\ No newline at end of file

Added: identity-federation/trunk/identity-bindings/src/test/resources/keystore/jbid_test_keystore.jks
===================================================================
(Binary files differ)


Property changes on: identity-federation/trunk/identity-bindings/src/test/resources/keystore/jbid_test_keystore.jks
___________________________________________________________________
Name: svn:mime-type
   + application/octet-stream

Modified: identity-federation/trunk/identity-fed-core/src/main/java/org/jboss/identity/federation/core/saml/v2/util/SignatureUtil.java
===================================================================
--- identity-federation/trunk/identity-fed-core/src/main/java/org/jboss/identity/federation/core/saml/v2/util/SignatureUtil.java	2009-01-15 01:15:52 UTC (rev 218)
+++ identity-federation/trunk/identity-fed-core/src/main/java/org/jboss/identity/federation/core/saml/v2/util/SignatureUtil.java	2009-01-15 18:28:01 UTC (rev 219)
@@ -37,6 +37,11 @@
  */
 public class SignatureUtil
 { 
+   /**
+    * Get the XML Signature URI for the algo (RSA, DSA)
+    * @param algo
+    * @return
+    */
    public static String getXMLSignatureAlgorithmURI(String algo)
    {
       String xmlSignatureAlgo = null;
@@ -53,6 +58,13 @@
       return xmlSignatureAlgo ;
    }
    
+   /**
+    * Sign a string using the private key
+    * @param stringToBeSigned
+    * @param signingKey
+    * @return
+    * @throws Exception
+    */
    public static byte[] sign(String stringToBeSigned, PrivateKey signingKey)
    throws Exception
    {
@@ -68,6 +80,14 @@
       return sig.sign(); 
    }
    
+   /**
+    * Validate the signed content with the signature value
+    * @param signedContent
+    * @param signatureValue
+    * @param validatingKey
+    * @return
+    * @throws Exception
+    */
    public static boolean validate(byte[] signedContent,
          byte[] signatureValue, PublicKey validatingKey) throws Exception
    {
@@ -88,6 +108,15 @@
       return sig.verify(signatureValue); 
    }
    
+   /**
+    * Validate the signature using a x509 certificate
+    * @param signedContent
+    * @param signatureValue
+    * @param signatureAlgorithm
+    * @param validatingCert
+    * @return
+    * @throws Exception
+    */
    public static boolean validate(byte[] signedContent,
          byte[] signatureValue, 
          String signatureAlgorithm,




More information about the jboss-identity-commits mailing list