sgoeschl    2005/02/16 03:12:40

  Added:       yaafi/src/java/org/apache/fulcrum/jce/crypto
                        CryptoParameters.java CryptoStreamFactory.java
                        CryptoStreamFactoryImpl.java CryptoUtil.java
                        HexConverter.java PasswordFactory.java
                        PasswordParameters.java
  Log:
  Initial import
  
  Revision  Changes    Path
  1.1                  
jakarta-turbine-fulcrum/yaafi/src/java/org/apache/fulcrum/jce/crypto/CryptoParameters.java
  
  Index: CryptoParameters.java
  ===================================================================
  package org.apache.fulcrum.jce.crypto;
  
  /*
   * Copyright 2004 Apache Software Foundation
   * Licensed  under the  Apache License,  Version 2.0  (the "License");
   * you may not use  this file  except in  compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed  under the  License is distributed on an "AS IS" BASIS,
   * WITHOUT  WARRANTIES OR CONDITIONS  OF ANY KIND, either  express  or
   * implied.
   *
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  
  /**
   * CryptoParameters used for encryption/decrytpion.
   *
   * @author <a href="mailto:[EMAIL PROTECTED]">Siegfried Goeschl</a>
   * @version $Id: CryptoParameters.java,v 1.1 2005/02/16 11:12:40 sgoeschl Exp 
$
   */
  
  public interface CryptoParameters
  {
      /** Parameter for PBEParameterSpec */
      int COUNT = 20;
  
      /**
       * The algorithm being used
       *
       * <ul>
       *   <li>for SunJCE 1.22 (JDK 1.3) :  PBEWithMD5AndDES</li>
       *   <li>for SunJCE 1.42 (JDK 1.4) :  PBEWithMD5AndDES, 
PBEWithMD5AndTripleDES</li>
       * </ul>
       */
      String ALGORITHM = "PBEWithMD5AndDES";
  
      /**
       * The JCE provider name known to work. If the value
       * is set to null an appropriate provider will be
       * used.
       *
       * <ul>
       *  <li>SunJCE<li>
       *  <li>BC (Bouncy Castle Provider)<li>
       * </ul>
       */
      String PROVIDERNAME = null;
  
      /** The password salt */
      byte[] SALT = {
          (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
          (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
          };
  }
  
  
  1.1                  
jakarta-turbine-fulcrum/yaafi/src/java/org/apache/fulcrum/jce/crypto/CryptoStreamFactory.java
  
  Index: CryptoStreamFactory.java
  ===================================================================
  package org.apache.fulcrum.jce.crypto;
  
  /*
   * Copyright 2004 Apache Software Foundation
   * Licensed  under the  Apache License,  Version 2.0  (the "License");
   * you may not use  this file  except in  compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed  under the  License is distributed on an "AS IS" BASIS,
   * WITHOUT  WARRANTIES OR CONDITIONS  OF ANY KIND, either  express  or
   * implied.
   *
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.OutputStream;
  import java.security.GeneralSecurityException;
  
  /**
   * Interface for creating encrypting/decrypting streams.
   * 
   * @author <a href="mailto:[EMAIL PROTECTED]">Siegfried Goeschl </a>
   * @version $Id: CryptoStreamFactory.java,v 1.1 2005/02/16 11:12:40 sgoeschl 
Exp $
   */
  
  public interface CryptoStreamFactory
  {
      /** 
       * Creates an decrypting input stream
       * 
       * @param is the input stream to be wrapped
       * @return an decrypting input stream
       */
      InputStream getInputStream(InputStream is)
        throws GeneralSecurityException, IOException;
  
      /** 
       * Creates an decrypting input stream
       * 
       * @param is the input stream to be wrapped
       * @param password the password to be used
       * @return an decrypting input stream
       */
      InputStream getInputStream(InputStream is, char[] password)
        throws GeneralSecurityException, IOException;
  
      /** 
       * Creates an encrypting output stream
       * 
       * @param os the output stream to be wrapped
       * @param password the password to be used
       * @return an decrypting input stream
       */
      OutputStream getOutputStream(OutputStream os, char[] password) 
        throws GeneralSecurityException, IOException;
  }
  
  
  1.1                  
jakarta-turbine-fulcrum/yaafi/src/java/org/apache/fulcrum/jce/crypto/CryptoStreamFactoryImpl.java
  
  Index: CryptoStreamFactoryImpl.java
  ===================================================================
  package org.apache.fulcrum.jce.crypto;
  
  /*
   * Copyright 2004 Apache Software Foundation
   * Licensed  under the  Apache License,  Version 2.0  (the "License");
   * you may not use  this file  except in  compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed  under the  License is distributed on an "AS IS" BASIS,
   * WITHOUT  WARRANTIES OR CONDITIONS  OF ANY KIND, either  express  or
   * implied.
   *
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.OutputStream;
  import java.security.GeneralSecurityException;
  import java.security.Key;
  
  import javax.crypto.Cipher;
  import javax.crypto.CipherInputStream;
  import javax.crypto.CipherOutputStream;
  import javax.crypto.SecretKeyFactory;
  import javax.crypto.spec.PBEKeySpec;
  import javax.crypto.spec.PBEParameterSpec;
  
  /**
   * Concrete factory for creating encrypting/decrypting streams. The
   * implementation uses the JCE (Java Crypto Extension) either supplied
   * by SUN (using SunJCE 1.42) or an custom provider such as BouncyCastle
   * or the newer Cryptix libraries.
   * 
   * The implementation uses as PBEWithMD5AndTripleDES for encryption which
   * should be sufficent for most applications.
   * 
   * The implementation also supplies a default password in the case that
   * the programmer don't want to have additional hassles. It is easy to
   * reengineer the password being used but much better than a hard-coded
   * password in the application.
   * 
   * The code uses parts from Markus Hahn's Blowfish library found at
   * http://blowfishj.sourceforge.net/
   * 
   * @author <a href="mailto:[EMAIL PROTECTED]">Siegfried Goeschl </a>
   * @author <a href="mailto:[EMAIL PROTECTED]">Markus Hahn</a>
   */
  
  public final class CryptoStreamFactoryImpl implements CryptoStreamFactory
  {
      /** the salt for the PBE algorithm */
      private byte[] salt;
          
      /** the count paramter for the PBE algorithm */
      private int count;
      
      /** the name of the JCE provider */
      private String providerName;
      
      /** the algorithm to use */
      private String algorithm;
      
      /** the default instance */
      private static CryptoStreamFactory instance;
  
      /**
       * Factory method to get a default instance
       */
      public static CryptoStreamFactory getInstance()
      {
          if( CryptoStreamFactoryImpl.instance == null )
          {
              synchronized( CryptoStreamFactory.class )
              {
                  if( CryptoStreamFactoryImpl.instance == null )
                  {
                      CryptoStreamFactoryImpl.instance = new 
CryptoStreamFactoryImpl();
                  }
              }
          }
          
          return instance;
      }
  
      /**
       * Set the default instance from an external application.
       * @param instance the new default instance
       */
      public static void setInstance( CryptoStreamFactory instance )
      {
          CryptoStreamFactoryImpl.instance = instance;
      }
      
      /**
       * Constructor
       */
      public CryptoStreamFactoryImpl()
      {        
          this.salt = CryptoParameters.SALT;
          this.count = CryptoParameters.COUNT;
          this.providerName = CryptoParameters.PROVIDERNAME;
          this.algorithm = CryptoParameters.ALGORITHM;
      }
  
      /**
       * Constructor
       * 
       * @param salt the salt for the PBE algorithm 
       * @param count the iteration for PBEParameterSpec
       * @param algorithm the algorithm to be used
       * @param providerName the name of the JCE provide to b used
       */
      public CryptoStreamFactoryImpl( 
          byte[] salt,  
          int count, 
          String algorithm, 
          String providerName )
      {        
          this.salt = salt;
          this.count = count;
          this.algorithm = algorithm;
          this.providerName = providerName;        
      }
  
      /**
       * @param is the input stream to be wrapped
       * @return a decrypting input stream
       */
      public InputStream getInputStream( InputStream is )     
        throws GeneralSecurityException, IOException
        {
          Cipher cipher = this.createCipher( Cipher.DECRYPT_MODE, 
PasswordFactory.create() );
          CipherInputStream cis = new CipherInputStream( is, cipher );      
          return cis;
        }
  
      
      /**
       * @param is the input stream to be wrapped
       * @param password the password for decryption
       * @return a decrypting input stream
       */
      public InputStream getInputStream( InputStream is, char[] password )     
        throws GeneralSecurityException, IOException
        {
          Cipher cipher = this.createCipher( Cipher.DECRYPT_MODE, password );
          CipherInputStream cis = new CipherInputStream( is, cipher );      
          return cis;
        }
  
      /**
       * @param os the output stream to be wrapped
       * @param password the password for encryption
       *  
       * @return a encrypting output stream
       */
      public OutputStream getOutputStream( OutputStream os, char[] password )   
  
        throws GeneralSecurityException, IOException
        {
          Cipher cipher = this.createCipher( Cipher.ENCRYPT_MODE, password );
          CipherOutputStream cos = new CipherOutputStream( os, cipher );      
            return cos;
        }
         
      /**
       * @return Returns the algorithm.
       */
      private final String getAlgorithm()
      {
          return algorithm;
      }
      
      /**
       * @return Returns the count.
       */
      private final int getCount()
      {
          return count;
      }
      
      /**
       * @return Returns the providerName.
       */
      private final String getProviderName()
      {
          return providerName;
      }
      
      /**
       * @return Returns the salt.
       */
      private final byte [] getSalt()
      {
          return salt;
      }
      
      /**
       * Create a PBE key.
       * 
       * @param password the password to use.
       * @return the key
       * @throws NoSuchAlgorithmException
       * @throws InvalidKeySpecException
       */
      private final Key createKey( char[] password )
        throws GeneralSecurityException
      {
          SecretKeyFactory keyFactory = null;
          String algorithm = this.getAlgorithm();           
            PBEKeySpec keySpec =  new PBEKeySpec(password);                 
            
            if( this.getProviderName() == null )
            {
                keyFactory = SecretKeyFactory.getInstance( algorithm );
            }
            else
            {
                keyFactory = SecretKeyFactory.getInstance( algorithm, 
this.getProviderName() );
            }
            
            Key key = keyFactory.generateSecret(keySpec);
            return key;
      }
      
      /**
       * Create a Cipher. 
       * 
       * @param mode the cipher mode
       * @param password the password
       * @return an instance of a cipher
       */
      private final Cipher createCipher( int mode, char[] password )
        throws GeneralSecurityException, IOException    
      {
          Cipher cipher = null;
            PBEParameterSpec paramSpec = new PBEParameterSpec( this.getSalt(), 
this.getCount() );        
            Key key = this.createKey( password );           
            
            if( this.getProviderName() == null )
            {
                cipher = Cipher.getInstance( this.getAlgorithm() );
            }
            else
            {
                cipher = Cipher.getInstance( this.getAlgorithm(), 
this.getProviderName() );
            }
            
            cipher.init( mode, key, paramSpec );            
            return cipher;    
      }    
  }
  
  
  1.1                  
jakarta-turbine-fulcrum/yaafi/src/java/org/apache/fulcrum/jce/crypto/CryptoUtil.java
  
  Index: CryptoUtil.java
  ===================================================================
  package org.apache.fulcrum.jce.crypto;
  
  /*
   * Copyright 2004 Apache Software Foundation
   * Licensed  under the  Apache License,  Version 2.0  (the "License");
   * you may not use  this file  except in  compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed  under the  License is distributed on an "AS IS" BASIS,
   * WITHOUT  WARRANTIES OR CONDITIONS  OF ANY KIND, either  express  or
   * implied.
   *
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  import java.io.ByteArrayInputStream;
  import java.io.ByteArrayOutputStream;
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.OutputStream;
  import java.security.GeneralSecurityException;
  
  /**
   * Helper class to provde generic functions to work with CryptoStreams.
   * 
   * The code uses parts from Markus Hahn's Blowfish library found at
   * http://blowfishj.sourceforge.net/
   * 
   * @author <a href="mailto:[EMAIL PROTECTED]">Siegfried Goeschl </a>
   * @author <a href="mailto:[EMAIL PROTECTED]">Markus Hahn</a>
   */
  
  public final class CryptoUtil
  {    
      /**
       * Copies from a source to a target object using encryption
       *
       * @param source the source object
       * @param target the target object
       * @param password the password to use for encryption
       * @throws GeneralSecurityException accessing JCE failed
       * @throws IOException accessing the souce failed
       * 
       */
      public static void encrypt( Object source, Object target, char[] password 
)
          throws GeneralSecurityException, IOException
      {
          CryptoUtil.encrypt( 
              CryptoUtil.getCryptoStreamFactory(), 
              source, 
              target, 
              password 
              );
      }
  
      /**
       * Copies from a source to a target object using encryption and a 
       * caller supplied CryptoStreamFactory.
       *
       * @param factory the factory to create the crypto streams
       * @param source the source object
       * @param target the target object
       * @param password the password to use for encryption
       * @throws GeneralSecurityException accessing JCE failed
       * @throws IOException accessing the souce failed 
       */
      public static void encrypt( 
          CryptoStreamFactory factory, Object source, Object target, char[] 
password )
        throws GeneralSecurityException, IOException
      {
          InputStream is = CryptoUtil.createInputStream( source );
          OutputStream os = CryptoUtil.createOutputStream( target );
          OutputStream eos = factory.getOutputStream( os, password );        
          CryptoUtil.copy( is, eos );
      }
  
      /**
       * Copies from a source to a target object using decryption.
       *
       * @param source the source object
       * @param target the target object
       * @param password the password to use for decryption
       * @throws GeneralSecurityException accessing JCE failed
       * @throws IOException accessing the souce failed 
       */
      public static void decrypt( Object source, Object target, char[] password 
)
        throws GeneralSecurityException, IOException
      {
          CryptoUtil.decrypt( 
              CryptoUtil.getCryptoStreamFactory(),
              source,
              target,
              password
              );
      }
  
      /**
       * Copies from a source to a target object using decryption and a 
       * caller-suppier CryptoStreamFactory.
       * 
       * @param factory the factory to create the crypto streams
       * @param source the source object
       * @param target the target object
       * @param password the password to use for decryption
       * @throws GeneralSecurityException accessing JCE failed
       * @throws IOException accessing the souce failed
       */
      public static void decrypt( 
          CryptoStreamFactory factory, Object source, Object target, char[] 
password )
        throws GeneralSecurityException, IOException
      {
          InputStream is = CryptoUtil.createInputStream( source );
          OutputStream os = CryptoUtil.createOutputStream( target ); 
          InputStream dis = factory.getInputStream( is, password );
          CryptoUtil.copy( dis, os );
      }
  
      /**
       * Encrypts a string into a hex string.
       * 
       * @param plainText the plain text to be encrypted
       * @param password the password for encryption
       * @return the encrypted string
       * @throws GeneralSecurityException accessing JCE failed
       * @throws IOException accessing the souce failed
       */
      public static String encryptString( String plainText, char[] password )
        throws GeneralSecurityException, IOException
      {
          return CryptoUtil.encryptString( 
              CryptoUtil.getCryptoStreamFactory(),
              plainText,
              password
              );       
      }
  
      /**
       * Encrypts a string into a hex string.
       * 
       * @param factory the factory to create the crypto streams
       * @param plainText the plain text to be encrypted
       * @param password the password for encryption
       * @return the encrypted string
       * @throws GeneralSecurityException accessing JCE failed
       * @throws IOException accessing the souce failed
       */
      public static String encryptString( 
          CryptoStreamFactory factory, String plainText, char[] password )
        throws GeneralSecurityException, IOException
      {
          ByteArrayOutputStream bais = new ByteArrayOutputStream();        
          CryptoUtil.encrypt( factory, plainText, bais, password );
          return HexConverter.toString( bais.toByteArray() );
      }
  
      /**
       * Decrypts an encrypted string into the plain text. The encrypted
       * string must be a hex string created by encryptString.
       * 
       * @param cipherText the encrypted text to be decrypted
       * @param password the password for decryption
       * @return the decrypted string
       * @throws GeneralSecurityException accessing JCE failed
       * @throws IOException accessing the souce failed
       */
      public static String decryptString( String cipherText, char[] password )
        throws GeneralSecurityException, IOException
        {
          return CryptoUtil.decryptString( 
              CryptoUtil.getCryptoStreamFactory(),
              cipherText,
              password
              );
        }
  
      /**
       * Decrypts an encrypted string into the plain text. The encrypted
       * string must be a hex string created by encryptString.
       * 
       * @param factory the factory to create the crypto streams
       * @param cipherText the encrypted text to be decrypted
       * @param password the password for decryption
       * @return the decrypted string
       * @throws GeneralSecurityException accessing JCE failed
       * @throws IOException accessing the souce failed
       */
      public static String decryptString( 
          CryptoStreamFactory factory, String cipherText, char[] password )
        throws GeneralSecurityException, IOException
        {
          byte[] buffer = HexConverter.toBytes( cipherText );                   
     
            ByteArrayOutputStream bais = new ByteArrayOutputStream();        
            CryptoUtil.decrypt( factory, buffer, bais, password );
            return new String( bais.toByteArray(), "utf-8" );
        }
      
        
///////////////////////////////////////////////////////////////////////////
        // Private Implementation
        
///////////////////////////////////////////////////////////////////////////
        
      /**
       * Create an input stream supporting the following types
       * 
       * <ul>
       *        <li>String</li>
       *  <li>File</li>
       *  <li>byte[]</li> 
       *  <li>char[]</li> 
       *  <li>ByteArrayOutputStream</li>
       *  <li>InputStream</li>
       * </ul>
       */
      private static InputStream createInputStream( Object source )
          throws IOException
      {
          InputStream is = null;
  
          // create an InputStream
  
          if( source instanceof String )
          {
              byte[] content = ((String) source).getBytes("utf-8");
              is = new ByteArrayInputStream( content );
          }
          else if( source instanceof File )
          {
              is = new FileInputStream( (File) source );
          }
          else if( source instanceof byte[] )
          {
              is = new ByteArrayInputStream( (byte[]) source );
          }
          else if( source instanceof char[] )
          {
              byte[] content = new String((char[])source).getBytes("utf-8");
              is = new ByteArrayInputStream( content );
          }
          else if( source instanceof ByteArrayOutputStream )
          {
              byte[] content = ((ByteArrayOutputStream) source).toByteArray();
              is = new ByteArrayInputStream( content );
          }
          else
          {
              is = (InputStream) source;
          }
  
          return is;
      }
  
      /**
       * Create an output stream supporting the following types
       * 
       * <ul>
       *        <li>File</li>
       *  <li>OutputStream</li>
       * </ul>
       */
      private static OutputStream createOutputStream( Object target )
          throws IOException
      {
          OutputStream os = null;
  
          if( target instanceof File )
          {
              os = new FileOutputStream( (File) target );
          }
          else
          {
              os = (OutputStream) target;
          }
  
          return os;
      }
      
      /**
       * Pumps the input stream to the output stream.
       *
       * @param is the source input stream
       * @param os the target output stream
       * @throws IOException the copying failed
       */
      public static void copy( InputStream is, OutputStream os )
          throws IOException
      {
          byte[] buf = new byte[1024];
          int n = 0;
          int total = 0;
  
          while ((n = is.read(buf)) > 0)
          {
              os.write(buf, 0, n);
              total += n;
          }
  
          is.close();
          
          os.flush();
          os.close();
      }    
      
      private static CryptoStreamFactory getCryptoStreamFactory()
      {
          return CryptoStreamFactoryImpl.getInstance();
      }
  }
  
  
  
  1.1                  
jakarta-turbine-fulcrum/yaafi/src/java/org/apache/fulcrum/jce/crypto/HexConverter.java
  
  Index: HexConverter.java
  ===================================================================
  package org.apache.fulcrum.jce.crypto;
  
  /*
   * Copyright 2004 Apache Software Foundation
   * Licensed  under the  Apache License,  Version 2.0  (the "License");
   * you may not use  this file  except in  compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed  under the  License is distributed on an "AS IS" BASIS,
   * WITHOUT  WARRANTIES OR CONDITIONS  OF ANY KIND, either  express  or
   * implied.
   *
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  
  /**
   * Helper class to for HEX conversion.
   * 
   * The code uses parts from Markus Hahn's Blowfish library found at
   * http://blowfishj.sourceforge.net/
   * 
   * @author <a href="mailto:[EMAIL PROTECTED]">Siegfried Goeschl </a>
   * @author <a href="mailto:[EMAIL PROTECTED]">Markus Hahn</a>
   */
  
  public final class HexConverter
  {    
      /**
       * Table for byte to hex conversion
       */
        final private static char[] HEXTAB =
        {
                '0', '1', '2', '3',     '4', '5', '6', '7',
                '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
        };
  
        /**
         * Converts a byte array to a hex string.
         * 
         * @param data the byte array
         * @return the hex string
         */
        public final static String toString( byte[] data )
        {
                return bytesToHexStr(data, 0, data.length);
        }
        
        /**
         * Converts a hex string into a byte[]
         * 
         * @param data the hex string
         * @return the byte[]
         */
        
        public final static byte[] toBytes( String data )
        {
            byte[] result = new byte[data.length()/2];     
            hexStrToBytes( data, result, 0, 0, result.length );  
            return result;
        }
  
        /**
         * Converts a byte array to a hex string.
         * @param data the byte array
         * @param nOfs start index where to get the bytes
         * @param nLen number of bytes to convert
         * @return the hex string
         */
        private final static String bytesToHexStr(
                byte[] data,
                int nOfs,
                int nLen)
        {
                StringBuffer sbuf;
  
                sbuf = new StringBuffer();
                sbuf.setLength(nLen << 1);
  
                int nPos = 0;
                int nC = nOfs + nLen;
  
                while (nOfs < nC)
                {
                        sbuf.setCharAt(nPos++, HEXTAB[(data[nOfs  ] >> 4) & 
0x0f]);
                        sbuf.setCharAt(nPos++, HEXTAB[ data[nOfs++]       & 
0x0f]);
                }
                
                return sbuf.toString();
        }
  
        /**
         * Converts a hex string back into a byte array (invalid codes will be
         * skipped).
         * @param sHex hex string
         * @param data the target array
         * @param nSrcOfs from which character in the string the conversion 
should
         * begin, remember that (nSrcPos modulo 2) should equals 0 normally
         * @param nDstOfs to store the bytes from which position in the array
         * @param nLen number of bytes to extract
         * @return number of extracted bytes
         */
        private final static int hexStrToBytes(
                String sHex,
                byte[] data,
                int nSrcOfs,
                int nDstOfs,
                int nLen)
        {
                int nI, nJ, nStrLen, nAvailBytes, nDstOfsBak;
                byte bActByte;
                boolean blConvertOK;
  
                // check for correct ranges
                
                nStrLen = sHex.length();
  
                nAvailBytes = (nStrLen - nSrcOfs) >> 1;
                if (nAvailBytes < nLen)
                {
                        nLen = nAvailBytes;
                }
  
                int nOutputCapacity = data.length - nDstOfs;
                if (nLen > nOutputCapacity)
                {
                        nLen = nOutputCapacity;
                }
  
                // convert now
  
                nDstOfsBak = nDstOfs;
  
                for (nI = 0; nI < nLen; nI++)
                {
                        bActByte = 0;
                        blConvertOK = true;
  
                        for (nJ = 0; nJ < 2; nJ++)
                        {
                                bActByte <<= 4;
                                char cActChar = sHex.charAt(nSrcOfs++);
  
                                if ((cActChar >= 'a') && (cActChar <= 'f'))
                                {
                                        bActByte |= (byte) (cActChar - 'a') + 
10;
                                }
                                else
                                {
                                        if ((cActChar >= '0') && (cActChar <= 
'9'))
                                        {
                                                bActByte |= (byte) (cActChar - 
'0');
                                        }
                                        else
                                        {
                                                blConvertOK = false;
                                        }
                                }
                        }
                        if (blConvertOK)
                        {
                                data[nDstOfs++] = bActByte;
                        }
                }
  
                return (nDstOfs - nDstOfsBak);
        }
  }
  
  
  
  1.1                  
jakarta-turbine-fulcrum/yaafi/src/java/org/apache/fulcrum/jce/crypto/PasswordFactory.java
  
  Index: PasswordFactory.java
  ===================================================================
  package org.apache.fulcrum.jce.crypto;
  
  /*
   * Copyright 2004 Apache Software Foundation
   * Licensed  under the  Apache License,  Version 2.0  (the "License");
   * you may not use  this file  except in  compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed  under the  License is distributed on an "AS IS" BASIS,
   * WITHOUT  WARRANTIES OR CONDITIONS  OF ANY KIND, either  express  or
   * implied.
   *
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  import java.io.UnsupportedEncodingException;
  import java.security.MessageDigest;
  import java.security.NoSuchAlgorithmException;
  
  /** 
   * The implementation supplies a default password in the case that
   * the programmer don't want to have additional hassles. It is easy to
   * reengineer the password being used but much better than a hard-coded
   * password in the application.
   * 
   * The code uses parts from Markus Hahn's Blowfish library found at
   * http://blowfishj.sourceforge.net/
   * 
   * @author <a href="mailto:[EMAIL PROTECTED]">Siegfried Goeschl </a>
   * @author <a href="mailto:[EMAIL PROTECTED]">Markus Hahn</a>
   */
  
  public class PasswordFactory implements PasswordParameters
  {      
      /**
       * @return a default password using "xxxx-xxxx-xxxx-xxxxx"
       */
      public static final char[] create() 
        throws NoSuchAlgorithmException, UnsupportedEncodingException
        {
          return create( 
              PasswordParameters.DEFAULTPASSWORD,
              PasswordParameters.SALT,
              PasswordParameters.COUNT
              );
        }
  
      /**
       * @param seed the default password supplied by the caller
       * @return a password using "xxxx-xxxx-xxxx-xxxxx"
       */
      public static final char[] create( String seed ) 
        throws NoSuchAlgorithmException, UnsupportedEncodingException
        {
          return create( 
              seed.toCharArray()
              );
        }
  
      /**
       * @param the default password supplied by the caller
       * @return a password using "xxxx-xxxx-xxxx-xxxxx"
       */
      public static final char[] create( char[] seed ) 
        throws NoSuchAlgorithmException, UnsupportedEncodingException
        {
          return create( 
              seed,
              PasswordParameters.SALT,
              PasswordParameters.COUNT
              );
        }
  
      /**
       * Creates a default password using "xxxx-xxxx-xxxx-xxxxx".
       * 
       * @param salt the password salt
       * @param password the default password
       * @param count number of MessageDigest iterations
       * @return the default password
       * @throws NoSuchProviderException
       * @throws NoSuchAlgorithmException
       * @throws UnsupportedEncodingException
       */
      public static final char [] create( char[] password, byte[] salt, int 
count ) 
        throws NoSuchAlgorithmException, UnsupportedEncodingException
      {
          char [] result = null;
          MessageDigest sha1 = MessageDigest.getInstance( "SHA1" );
          byte [] passwordMask = new String( password ).getBytes( "UTF-8" );
          byte [] temp = new byte[salt.length + passwordMask.length];
          byte [] digest = null;
          
          StringBuffer stringBuffer = new StringBuffer();
  
          // combine the password with the salt string into a byte[9
  
          System.arraycopy( passwordMask, 0, temp, 0, passwordMask.length );
          System.arraycopy( salt, 0, temp, passwordMask.length, salt.length );
  
          // create a hash over and over to make it a bit random
  
          digest = temp;
  
          for (int i = 0; i < count; i++)
          {
              sha1.update( digest );
              digest = sha1.digest();
          }
  
          // build a well-formed password string to be usable 
          // by a human
  
          long long1 = createLong( digest, 0 );
          long long2 = createLong( digest, 4 );
          long long3 = createLong( digest, 8 );
          long long4 = createLong( digest, 12 );
  
          stringBuffer.append( Long.toHexString( long1 ).substring( 0, 4 ) );
          stringBuffer.append( '-' );
          stringBuffer.append( Long.toHexString( long2 ).substring( 0, 4 ) );
          stringBuffer.append( '-' );
          stringBuffer.append( Long.toHexString( long3 ).substring( 0, 4 ) );
          stringBuffer.append( '-' );
          stringBuffer.append( Long.toHexString( long4 ).substring( 0, 5 ) );
  
          // copy the password
  
          result = new char[stringBuffer.length()];
  
          for (int i = 0; i < stringBuffer.length(); i++)
          {
              result[i] = stringBuffer.charAt( i );
          }
  
          // wipe out the StringBuffer
  
          for (int i = 0; i < stringBuffer.length(); i++)
          {
              stringBuffer.setCharAt( i, ' ' );
          }
  
          return result;
      }
  
      /**
       * Gets bytes from an array into a long.
       * 
       * @param buf where to get the bytes
       * @param nOfs index from where to read the data
       * @return the 64bit integer
       */
      private static final long createLong(byte [] buf, int nOfs)
      {
                return
                        ((long)(( buf[nOfs    ]          << 24) |
                            ((buf[nOfs + 1] & 0x0ff) << 16) |
                                    ((buf[nOfs + 2] & 0x0ff) <<  8) |
                                    ( buf[nOfs + 3] & 0x0ff       )) << 32) |
                    ((long)(( buf[nOfs + 4]          << 24) |
                            ((buf[nOfs + 5] & 0x0ff) << 16) |
                            ((buf[nOfs + 6] & 0x0ff) <<  8) |
                            ( buf[nOfs + 7] & 0x0ff       )) & 0x0ffffffffL);
      }        
  }
  
  
  1.1                  
jakarta-turbine-fulcrum/yaafi/src/java/org/apache/fulcrum/jce/crypto/PasswordParameters.java
  
  Index: PasswordParameters.java
  ===================================================================
  package org.apache.fulcrum.jce.crypto;
  
  /*
   * Copyright 2004 Apache Software Foundation
   * Licensed  under the  Apache License,  Version 2.0  (the "License");
   * you may not use  this file  except in  compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed  under the  License is distributed on an "AS IS" BASIS,
   * WITHOUT  WARRANTIES OR CONDITIONS  OF ANY KIND, either  express  or
   * implied.
   *
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  /**
   * Parameters for creating a password.
   *
   * @author <a href="mailto:[EMAIL PROTECTED]">Siegfried Goeschl</a>
   * @version $Id: PasswordParameters.java,v 1.1 2005/02/16 11:12:40 sgoeschl 
Exp $
   */
  
  public interface PasswordParameters
  {
      /** Parameter for the number of SHA1 invocation */
      int COUNT = 20;
  
      /** The default password used for creating the internal password */
      char[] DEFAULTPASSWORD = {
          (char) 'f', (char) 'u', (char) 'l', (char) 'c',
          (char) 'r', (char) 'u', (char) 'm', (char) '-',
          (char) 'y', (char) 'a', (char) 'a', (char) 'f',
          (char) 'i'
          };
  
      /** The password salt */
      byte[] SALT = {
          (byte)0xc6, (byte)0x74, (byte)0x81, (byte)0x8a,
          (byte)0x7b, (byte)0xe8, (byte)0xfe, (byte)0x99
          };
  }
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to