Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source.
   * Copyright 2006, 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.resource.security;
 
 import java.util.Map;
 
 import  javax.resource.spi.security.PasswordCredential;
 
 import  org.jboss.logging.Logger;
An example of how one could encrypt the database password for a jca connection factory. The corresponding login config entry illustrates the usage: <application-policy name = "testPBEIdentityLoginModule"> <authentication> <login-module code = "org.jboss.resource.security.PBEIdentityLoginModule" flag = "required"> <module-option name = "principal">sa</module-option> <module-option name = "userName">sa</module-option> <module-option name = "password">3fp7R/7TMjyTTxhmePdJVk</module-option> <module-option name = "ignoreMissigingMCF">true</module-option> <module-option name = "pbealgo">PBEWithMD5AndDES</module-option> <module-option name = "pbepass">testPBEIdentityLoginModule</module-option> <module-option name = "salt">abcdefgh</module-option> <module-option name = "iterationCount">19</module-option> <module-option name = "managedConnectionFactoryName">jboss.jca:service=LocalTxCM,name=DefaultDS</module-option> </login-module> </authentication> </application-policy> This uses password based encryption (PBE) with algorithm parameters dervived from pbealgo, pbepass, salt, iterationCount options: + pbealgo - the PBE algorithm to use. Defaults to PBEwithMD5andDES. + pbepass - the PBE password to use. Can use the JaasSecurityDomain {CLASS} and {EXT} syntax to obtain the password from outside of the configuration. Defaults to "jaas is the way". + salt - the PBE salt as a string. Defaults to {1, 7, 2, 9, 3, 11, 4, 13}. + iterationCount - the PBE iterationCount. Defaults to 37.

Author(s):
Scott.Stark@jboss.org
Noel Rocher 29, june 2004 username & userName issue
Version:
$Revision: 57189 $
 
 public class PBEIdentityLoginModule
 {
   
Class logger
 
    private static final Logger log = Logger.getLogger(SecureIdentityLoginModule.class);
    private boolean trace = .isTraceEnabled();
 
    private String username;
    private String password;
   
The Blowfish key material
 
    private char[] pbepass = "jaas is the way".toCharArray();
    private String pbealgo = "PBEwithMD5andDES";
    private byte[] salt = {1, 7, 2, 9, 3, 11, 4, 13};
    private int iterationCount = 37;
    private PBEParameterSpec cipherSpec;
 
   {
   }
   PBEIdentityLoginModule(String algochar[] passbyte[] pbesaltint iter)
   {
      ifpass != null )
          = pass;
      ifalgo != null )
          = algo;
      ifpbesalt != null )
          = pbesalt;
      ifiter > 0 )
          = iter;
   }
   @SuppressWarnings("unchecked")
   public void initialize(Subject subjectCallbackHandler handlerMap sharedStateMap options)
   {
      super.initialize(subjecthandlersharedStateoptions);
      // NR : we keep this username for compatibility
       = (Stringoptions.get("username");
      if == null )
      {
      	// NR : try with userName
         = (Stringoptions.get("userName");      	
        if == null )
        {
         throw new IllegalArgumentException("The user name is a required option");
        }
     }
       = (Stringoptions.get("password");
      if == null )
      {
         throw new IllegalArgumentException("The password is a required option");
      }
      // Look for the cipher password and algo parameters
      String tmp = (Stringoptions.get("pbepass");
      iftmp != null )
      {
         try
         {
             = Util.loadPassword(tmp);
         }
         catch(Exception e)
         {
            throw new IllegalStateException(e);
         }
      }
      tmp = (Stringoptions.get("pbealgo");
      iftmp != null )
          = tmp;
      tmp = (Stringoptions.get("salt");
      iftmp != null )
          = tmp.substring(0, 8).getBytes();
      tmp = (Stringoptions.get("iterationCount");
      iftmp != null )
          = Integer.parseInt(tmp);
   }
   public boolean login() throws LoginException
   {
      if()
         .trace("login called");
      ifsuper.login() == true )
         return true;
      super. = true;
      return true;
   }
   @SuppressWarnings("unchecked")
   public boolean commit() throws LoginException
   {
      Principal principal = new SimplePrincipal();
      SubjectActions.addPrincipals(subject, principal);
      sharedState.put("javax.security.auth.login.name");
      // Decode the encrypted password
      try
      {
         char[] decodedPassword = decode();
         PasswordCredential cred = new PasswordCredential(decodedPassword);
         cred.setManagedConnectionFactory(getMcf());
         SubjectActions.addCredentials(subject, cred);
      }
      catch(Exception e)
      {
         if()
            .trace("Failed to decode password"e);
         throw new LoginException("Failed to decode password: "+e.getMessage());
      }
      return true;
   }
   public boolean abort()
   {
       = null;
       = null;
      return true;
   }
   protected Principal getIdentity()
   {
      if()
         .trace("getIdentity called, username="+);
      Principal principal = new SimplePrincipal();
      return principal;
   }
   protected Group[] getRoleSets() throws LoginException
   {
      Group[] empty = new Group[0];
      return empty;
   }
   private String encode(String secret)
      throws Exception
   {
      // Create the PBE secret key
      PBEKeySpec keySpec = new PBEKeySpec();
      SecretKeyFactory factory = SecretKeyFactory.getInstance();
      SecretKey cipherKey = factory.generateSecret(keySpec);
      // Decode the secret
      Cipher cipher = Cipher.getInstance();
      cipher.init(.cipherKey);
      byte[] encoding = cipher.doFinal(secret.getBytes());
      return Base64Utils.tob64(encoding);
   }
   private char[] decode(String secret)
      throws Exception
   {
      // Create the PBE secret key
      PBEKeySpec keySpec = new PBEKeySpec();
      SecretKeyFactory factory = SecretKeyFactory.getInstance();
      SecretKey cipherKey = factory.generateSecret(keySpec);
      // Decode the secret
      byte[] encoding = Base64Utils.fromb64(secret);
      Cipher cipher = Cipher.getInstance();
      cipher.init(.cipherKey);
      byte[] decode = cipher.doFinal(encoding);
      return new String(decode).toCharArray();
   }

   
Main entry point to encrypt a password using the hard-coded pass phrase

Parameters:
args - [0] = the password to encode [1] = PBE password [2] = PBE salt [3] = PBE iterationCount [4] = PBE algo
Throws:
Exception
 
   public static void main(String[] argsthrows Exception
   {
      String algo = null;
      char[] pass = "jaas is the way".toCharArray();
      byte[] salt = null;
      int iter = -1;
      ifargs.length >= 2 )
         pass = args[1].toCharArray();
      ifargs.length >= 3 )
         salt = args[2].getBytes();
      ifargs.length >= 4 )
         iter = Integer.decode(args[3]).intValue();
      ifargs.length >= 5 )
         algo = args[4];
      PBEIdentityLoginModule pbe = new PBEIdentityLoginModule(algopasssaltiter);
      String encode = pbe.encode(args[0]);
      ..println("Encoded password: "+encode);
   }
New to GrepCode? Check out our FAQ X