Quantcast

RC2 Spec in Non-Fips Mode

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

RC2 Spec in Non-Fips Mode

Kamal, Murali
Hi All,

As per the known issues on BC-FIPS, it doesn't support the following

"JCE provider does not support use of legacy RC2ParameterSpec with RC2 MACs."

We have a code using BSAFE for the Cipher suite "RC2-128/CBC/PKCS5Padding", The Cipher Text produced is not matching the Cipher produced using the Bouncy Castle (Non-Fips Version, bcprov.jar).

Even after using the same Serialization key and Initialization Vector, I am not able to match the same Cipher using BC.

I suspect that usage of RC2ParameterSpec will help, but when I include that in the KeyGeneration.init(rc2spec), I get error that algorithm:
java.security.InvalidAlgorithmParameterException: Not Implemented
at org.bouncycastle.jcajce.provider.symmetric.util.BaseKeyGenerator.engineInit(Unknown Source)
       at javax.crypto.KeyGenerator.init(KeyGenerator.java:447)
       at javax.crypto.KeyGenerator.init(KeyGenerator.java:430)

The Same RC2ParameterSpec when used with other invocations like SecretKeySpec() doesn't give me same CipherText.

I have tried bunch of different calls with RC2 but no success. I suspect that before generation of the secret key if I am able to set the RC2Spec, I will get the result, but I get the above Exception.

Can someone point us at what we are missing ?

Thank you,
Murali.

NOTE: Full code ( you may look in to the functions getEncryptedData, generateRC2SecretKey, initCipher & getIV.)

/**
*
*/
package com.netegrity.crypto;

import java.math.BigInteger;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.rsa.jsafe.JSAFE_Exception;
import com.rsa.jsafe.JSAFE_IVException;
import com.rsa.jsafe.JSAFE_InputException;
import com.rsa.jsafe.JSAFE_InvalidKeyException;
import com.rsa.jsafe.JSAFE_InvalidUseException;
import com.rsa.jsafe.JSAFE_PaddingException;
import com.rsa.jsafe.JSAFE_SecretKey;
import com.rsa.jsafe.JSAFE_SecureRandom;
import com.rsa.jsafe.JSAFE_SymmetricCipher;

/**
* @author chara09
*
*/
public final class RC2128CBCPKCS5PaddingHandler extends IAMCrypto {

               private static final String SECRET_KEY_ALG_NAME = "RC2";
    private static String CIPHER_ALG_NAME = "RC2-128/CBC/PKCS5Padding";
    private static final String CIPHER_ALG_NAME_SUFFIX = "/CBC/PKCS5Padding";
    private static final int IV_SIZE = 8;
               private static final Logger _log = Logger.getLogger(RC2128CBCPKCS5PaddingHandler.class);

    private RC2128CBCPKCS5PaddingHandler(Properties p){
        super(p);
        loadMyParameters();
    }

    private RC2128CBCPKCS5PaddingHandler(String envOID){
        super();
        m_envId = envOID;
        loadMyParameters();
    }

    private RC2128CBCPKCS5PaddingHandler(byte[] key){
        super();
        if (key != null) this.m_key = key;
        else loadMyParameters();
    }

    protected void loadMyParameters(){
        byte [] key = null;
        if (parameters.keySet().contains("RCKeySize")) {
            int size = Integer.parseInt(parameters.getProperty("RCKeySize"));
            if (size <= 1024) {
                CIPHER_ALG_NAME = SECRET_KEY_ALG_NAME + "-" + size + CIPHER_ALG_NAME_SUFFIX;
            }
        }
        if (parameters.keySet().contains("RCKey")) {
            key = parameters.getProperty("RCKey").getBytes();
            if (key != null)
                m_defaultKey = key;
        }
    }

               /* (non-Javadoc)
               * @see com.netegrity.crypto.CipherHandler#getInstance()
               */
               public static IAMCrypto getInstance(String envOID) {
                              //if this class is initialized without using IAMCrypto's getInstance().
                              if(isFIPSMode())
                                             return getInstance(envOID, AES_CBC_PKCS5PADDING);

                              return new RC2128CBCPKCS5PaddingHandler(envOID);
               }

    public static IAMCrypto getInstance(String envOID, byte[] key)
    {
        if(isFIPSMode())
            return getInstance(envOID, AES_CBC_PKCS5PADDING);

        return new RC2128CBCPKCS5PaddingHandler(key);
    }

    public static IAMCrypto getInstance(Properties p)
    {
        return new RC2128CBCPKCS5PaddingHandler(p);
    }

    public byte[] getDecryptedData(String encrypteddata)
    {
        // We don't decrypt NULL or empty string
        if ((encrypteddata == null) || (encrypteddata.length() == 0)) {
            return null;
        }
        return getDecryptedDataWithKey(encrypteddata.getBytes());
    }

               /* (non-Javadoc)
               * @see com.netegrity.crypto.CipherHandler#getDecryptedData(byte[])
               */
               public byte[] getDecryptedData(byte[] encrypteddata) {
                   return getDecryptedData(encrypteddata, true);
               }

    public byte[] getDecryptedDataWithKey(byte[] encrypteddata) {
        return getDecryptedData(encrypteddata, true);
    }

               /* (non-Javadoc)
               * @see com.netegrity.crypto.CipherHandler#getEncryptedData(byte[])
               */
               public byte[] getEncryptedData(byte[] plainText) {
                   return getEncryptedData(plainText, true);
               }

    public byte[] getEncryptedDataWithKey(byte[] plaindata) {
        setCurrentSecretKeyPasswordAndId();
        return getEncryptedData(plaindata, true);
    }

               public byte[] getDecryptedData(byte[] encrypteddata, boolean decodeData)
               {   
        byte[] decrypted = null;

        try
        {
            if (decodeData) {
                //*************************************
                encrypteddata = decodeBase64(encrypteddata);//Base64.decode(encrypteddata, 0, encrypteddata.length);
                //*************************************
            }
           
            // first decrypt in normal byte order form
            try
            {
               decrypted = decryptData(encrypteddata, false);
            }
            catch (Exception e)
            {
               // do nothing
            }
           
            // the previous decrypt operation failed, retry again using the swap byte order method
            if (decrypted == null)
            {
               try
               {
                             decrypted = decryptData(encrypteddata, true);
                }
                catch (Exception e)
                {
                             _log.error(e);
                }
            }
        }
        catch (Exception e)
        {
            _log.error(e);
        }

        return decrypted;
    }

               public byte[] decryptData(byte[] encrypteddata, boolean useSwapOrder) throws Exception
               {
                              JSAFE_SymmetricCipher decryptor = null;
        JSAFE_SecretKey key = null;
        
        //set the initialization vector.
        byte[] ivData = getIV(useSwapOrder);
        byte[] decrypted = null;
       
        int encryptedLength = encrypteddata.length;
       
                              try
                              {
                       decryptor = initCipher(ivData);
                       key = generateRC2SecretKey(useSwapOrder);
                       decryptor.decryptInit(key);
                      
                       byte[] decrypted_temp = new byte[decryptor.getOutputBufferSize(encryptedLength)];
                       int bytes_written = decryptor.decryptUpdate(encrypteddata, 0, encryptedLength, decrypted_temp, 0);
              
                       //this should be a zero byte array leftover...
                       int should_be_zero = decryptor.decryptFinal(decrypted_temp, bytes_written);
              
                       //copy the correct amount of bytes into the array.
                       int len = bytes_written + should_be_zero;
                       decrypted = new byte[len];
                       System.arraycopy(decrypted_temp, 0, decrypted, 0, len);
                              }
                              finally
                              {
                       //Clean up for the decryptor
                                             if (decryptor != null)
                                                            decryptor.clearSensitiveData();
                                             if (key != null)
                                                            key.clearSensitiveData();
                              }
        return decrypted;
               }
              
               public byte[] getEncryptedData(byte[] plainText, boolean encodeData) {
        //set the initialization vector.
        byte [] ivData = getIV(false);
        //Initialize the Pseudo Random Number Generator.
        JSAFE_SecureRandom random = getRandomGenerator();
        //Initialize the Symmetric Cipher.
        JSAFE_SymmetricCipher encryptor = initCipher(ivData);
        //Perform the encryption.
        byte [] cipherText = encryptData(encryptor, random, plainText, encodeData);

        //clean up the cipher
        encryptor.clearSensitiveData();
        return cipherText;
    }

               public byte[] generateSecretKey()
               {
                              JSAFE_SecretKey key = generateRC2SecretKey(false);
                              byte[] keybytes = key.getSecretKeyData();
                              key.clearSensitiveData();
                              return keybytes;
               }

               /**
               * Initializes cipher object using initialization vector.
               * @param iv - Initialization vector.
               * @return cipher object.
               */
               private JSAFE_SymmetricCipher initCipher(byte[] iv)
               {
                              JSAFE_SymmetricCipher encryptor = null;
                              try
                              {
                       encryptor = JSAFE_SymmetricCipher.getInstance(CIPHER_ALG_NAME, "Java");
                       encryptor.setIV(iv, 0, iv.length);
                              }
                              catch (Exception anyException) {
                                             _log.error("Exception caught while creating cipher object.");
                                             _log.error(anyException.toString());
                              }                             return encryptor;
               }

               /**
               * Generates JSAFE_SecureRandon object.  Not suppoted for this algorithm.
               * @return random object.
               */
               private JSAFE_SecureRandom getRandomGenerator()
               {
                              //NOT SUPPORTED.
                              JSAFE_SecureRandom random = null;
                              return random;
               }

               /**
               * Encrypts the plain text using cipher, key and
               * @param encryptor - Cipher
               * @param random - SecureRandom object
               * @param plainText - plain text
               * @param encodeData - Encode data after encrypting it.
               * @return encrypted data.
               */
               private byte[] encryptData(JSAFE_SymmetricCipher encryptor,
                                                                                                                        JSAFE_SecureRandom random,
                                                                                                                        byte[] plainText, boolean encodeData)
               {
                              JSAFE_SecretKey key = generateRC2SecretKey(false);
                              int plainTextLen = plainText.length;
                              byte[] cipherText = null;
        try {
                                             encryptor.encryptInit(key);
                                             cipherText = new byte[encryptor.getOutputBufferSize(plainTextLen)];
                                             int bytes_written = encryptor.encryptUpdate(plainText, 0, plainTextLen, cipherText, 0);

                                             encryptor.encryptFinal(cipherText, bytes_written);
                                             if (encodeData) {
                                                            //********************************************
                                                            cipherText = encodeBase64(cipherText, cipherText.length);//Base64.encode(cipherText).getBytes();
                                                            //********************************************
                                             }
                              } catch (JSAFE_InvalidUseException e) {
                                             _log.error(e);
                              } catch (JSAFE_InvalidKeyException e) {
                                             _log.error(e);
                              } catch (JSAFE_IVException e) {
                                             _log.error(e);
                              } catch (JSAFE_InputException e) {
                                             _log.error(e);
                              } catch (JSAFE_PaddingException e) {
                                             _log.error(e);
                              } catch (JSAFE_Exception e) {
                                             _log.error(e);
                              }
                              finally{
                                             if(key != null)
                                                            key.clearSensitiveData();
                              }

                              return cipherText;
               }

               private byte[] getIV(boolean useSwapOrder)
               {
                              JSAFE_SecretKey key = generateRC2SecretKey(useSwapOrder);
                              byte[] secret = key.getSecretKeyData();
                              if(secret == null)
                              {
                                             _log.error("The secret key is not available for this handler. Encryption failed");
                                             return null;
                              }

                              //set the initialization vector.
                              byte [] ivData = new byte[IV_SIZE];
                              System.arraycopy(secret, 0, ivData, 0, IV_SIZE < secret.length ? IV_SIZE : secret.length);
                              key.clearSensitiveData();
                              return ivData;
               }
   
               private JSAFE_SecretKey generateRC2SecretKey(boolean useSwapOrder)
               {
                              JSAFE_SecretKey key = null;
        try {
            byte[] serializationKey = new byte [24];
            if (m_key != null) serializationKey = m_key;
            else if (m_defaultKey != null) serializationKey = m_defaultKey;
            else {
                BigInteger [] staticBytes = new BigInteger[12];
                staticBytes[0] = new BigInteger(Integer.toBinaryString(0x103f), 2);
                staticBytes[1] = new BigInteger(Integer.toBinaryString(0xe982), 2);
                staticBytes[2] = new BigInteger(Integer.toBinaryString(0x28fc), 2);
                staticBytes[3] = new BigInteger(Integer.toBinaryString(0xa7b4), 2);
                staticBytes[4] = new BigInteger(Integer.toBinaryString(0xdd52), 2);
                staticBytes[5] = new BigInteger(Integer.toBinaryString(0x8e8f), 2);
                staticBytes[6] = new BigInteger(Integer.toBinaryString(0x1749), 2);
                staticBytes[7] = new BigInteger(Integer.toBinaryString(0xe3ca), 2);
                staticBytes[8] = new BigInteger(Integer.toBinaryString(0x11bc), 2);
                staticBytes[9] = new BigInteger(Integer.toBinaryString(0x2341), 2);
                staticBytes[10] = new BigInteger(Integer.toBinaryString(0x7bd4), 2);
                staticBytes[11] = new BigInteger(Integer.toBinaryString(0x38a2), 2);

                if (!useSwapOrder) {
                    //UNIX
                    for (int j = 0; j < 12; j++) {

                        byte [] buf1 = staticBytes[j].toByteArray();
                        System.arraycopy(buf1, buf1.length - 2, serializationKey, j * 2, 2);

                    }
                } else {
                    //NT
                    for (int j = 0; j < 12; j += 2) {
                        byte [] buf1 = staticBytes[j].toByteArray();
                        byte [] buf2 = staticBytes[j + 1].toByteArray();

                        for (int k = 0; k < 4; k++) {
                            int index = ((j / 2) * 4) + k;
                            if (k < 2) {
                                System.arraycopy(buf2, 1 - k + (buf2.length - 2), serializationKey, index, 1);
                            } else {
                                System.arraycopy(buf1, 3 - k + (buf1.length - 2), serializationKey, index, 1);
                            }
                        }
                    }
                }
            }

            key = JSAFE_SecretKey.getInstance(SECRET_KEY_ALG_NAME, "Java");
            key.setSecretKeyData(serializationKey, 0, serializationKey.length);

        } catch (Exception e) {
               _log.error(e);
        }

        return key;
               }

               public int getHandlerType()
               {
                              return RC2_128_CBC_PKCS5PADDING;
               }

               public String getHandlerTag()
               {
                              //this will be overridden
                              return IAMCrypto.RC2_128_CBC_PKCS5PADDING_TAG;
               }             

}

Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: RC2 Spec in Non-Fips Mode

David Hook

Normally the RC2ParameterSpec would be passed to the Cipher.init() it's
not involved in key generation, but provides a means of interpreting the
key as well as an IV to use for CBC mode. You need to be careful with
the effectiveKeyBits parameter - it really does change the way the world
works.

Have you tried using it with Cipher.init()? What value is the
effectiveKeyBits meant to be?

Regards,

David

On 27/01/17 21:33, Kamal, Murali wrote:

> Hi All,
>
> As per the known issues on BC-FIPS, it doesn't support the following
>
> "JCE provider does not support use of legacy RC2ParameterSpec with RC2 MACs."
>
> We have a code using BSAFE for the Cipher suite "RC2-128/CBC/PKCS5Padding", The Cipher Text produced is not matching the Cipher produced using the Bouncy Castle (Non-Fips Version, bcprov.jar).
>
> Even after using the same Serialization key and Initialization Vector, I am not able to match the same Cipher using BC.
>
> I suspect that usage of RC2ParameterSpec will help, but when I include that in the KeyGeneration.init(rc2spec), I get error that algorithm:
> java.security.InvalidAlgorithmParameterException: Not Implemented
> at org.bouncycastle.jcajce.provider.symmetric.util.BaseKeyGenerator.engineInit(Unknown Source)
>        at javax.crypto.KeyGenerator.init(KeyGenerator.java:447)
>        at javax.crypto.KeyGenerator.init(KeyGenerator.java:430)
>
> The Same RC2ParameterSpec when used with other invocations like SecretKeySpec() doesn't give me same CipherText.
>
> I have tried bunch of different calls with RC2 but no success. I suspect that before generation of the secret key if I am able to set the RC2Spec, I will get the result, but I get the above Exception.
>
> Can someone point us at what we are missing ?
>
> Thank you,
> Murali.
>
> NOTE: Full code ( you may look in to the functions getEncryptedData, generateRC2SecretKey, initCipher & getIV.)
>
> /**
> *
> */
> package com.netegrity.crypto;
>
> import java.math.BigInteger;
> import java.util.Properties;
>
> import org.apache.log4j.Logger;
>
> import com.rsa.jsafe.JSAFE_Exception;
> import com.rsa.jsafe.JSAFE_IVException;
> import com.rsa.jsafe.JSAFE_InputException;
> import com.rsa.jsafe.JSAFE_InvalidKeyException;
> import com.rsa.jsafe.JSAFE_InvalidUseException;
> import com.rsa.jsafe.JSAFE_PaddingException;
> import com.rsa.jsafe.JSAFE_SecretKey;
> import com.rsa.jsafe.JSAFE_SecureRandom;
> import com.rsa.jsafe.JSAFE_SymmetricCipher;
>
> /**
> * @author chara09
> *
> */
> public final class RC2128CBCPKCS5PaddingHandler extends IAMCrypto {
>
>                private static final String SECRET_KEY_ALG_NAME = "RC2";
>     private static String CIPHER_ALG_NAME = "RC2-128/CBC/PKCS5Padding";
>     private static final String CIPHER_ALG_NAME_SUFFIX = "/CBC/PKCS5Padding";
>     private static final int IV_SIZE = 8;
>                private static final Logger _log = Logger.getLogger(RC2128CBCPKCS5PaddingHandler.class);
>
>     private RC2128CBCPKCS5PaddingHandler(Properties p){
>         super(p);
>         loadMyParameters();
>     }
>
>     private RC2128CBCPKCS5PaddingHandler(String envOID){
>         super();
>         m_envId = envOID;
>         loadMyParameters();
>     }
>
>     private RC2128CBCPKCS5PaddingHandler(byte[] key){
>         super();
>         if (key != null) this.m_key = key;
>         else loadMyParameters();
>     }
>
>     protected void loadMyParameters(){
>         byte [] key = null;
>         if (parameters.keySet().contains("RCKeySize")) {
>             int size = Integer.parseInt(parameters.getProperty("RCKeySize"));
>             if (size <= 1024) {
>                 CIPHER_ALG_NAME = SECRET_KEY_ALG_NAME + "-" + size + CIPHER_ALG_NAME_SUFFIX;
>             }
>         }
>         if (parameters.keySet().contains("RCKey")) {
>             key = parameters.getProperty("RCKey").getBytes();
>             if (key != null)
>                 m_defaultKey = key;
>         }
>     }
>
>                /* (non-Javadoc)
>                * @see com.netegrity.crypto.CipherHandler#getInstance()
>                */
>                public static IAMCrypto getInstance(String envOID) {
>                               //if this class is initialized without using IAMCrypto's getInstance().
>                               if(isFIPSMode())
>                                              return getInstance(envOID, AES_CBC_PKCS5PADDING);
>
>                               return new RC2128CBCPKCS5PaddingHandler(envOID);
>                }
>
>     public static IAMCrypto getInstance(String envOID, byte[] key)
>     {
>         if(isFIPSMode())
>             return getInstance(envOID, AES_CBC_PKCS5PADDING);
>
>         return new RC2128CBCPKCS5PaddingHandler(key);
>     }
>
>     public static IAMCrypto getInstance(Properties p)
>     {
>         return new RC2128CBCPKCS5PaddingHandler(p);
>     }
>
>     public byte[] getDecryptedData(String encrypteddata)
>     {
>         // We don't decrypt NULL or empty string
>         if ((encrypteddata == null) || (encrypteddata.length() == 0)) {
>             return null;
>         }
>         return getDecryptedDataWithKey(encrypteddata.getBytes());
>     }
>
>                /* (non-Javadoc)
>                * @see com.netegrity.crypto.CipherHandler#getDecryptedData(byte[])
>                */
>                public byte[] getDecryptedData(byte[] encrypteddata) {
>                    return getDecryptedData(encrypteddata, true);
>                }
>
>     public byte[] getDecryptedDataWithKey(byte[] encrypteddata) {
>         return getDecryptedData(encrypteddata, true);
>     }
>
>                /* (non-Javadoc)
>                * @see com.netegrity.crypto.CipherHandler#getEncryptedData(byte[])
>                */
>                public byte[] getEncryptedData(byte[] plainText) {
>                    return getEncryptedData(plainText, true);
>                }
>
>     public byte[] getEncryptedDataWithKey(byte[] plaindata) {
>         setCurrentSecretKeyPasswordAndId();
>         return getEncryptedData(plaindata, true);
>     }
>
>                public byte[] getDecryptedData(byte[] encrypteddata, boolean decodeData)
>                {    
>         byte[] decrypted = null;
>
>         try
>         {
>             if (decodeData) {
>                 //*************************************
>                 encrypteddata = decodeBase64(encrypteddata);//Base64.decode(encrypteddata, 0, encrypteddata.length);
>                 //*************************************
>             }
>            
>             // first decrypt in normal byte order form
>             try
>             {
>                decrypted = decryptData(encrypteddata, false);
>             }
>             catch (Exception e)
>             {
>                // do nothing
>             }
>            
>             // the previous decrypt operation failed, retry again using the swap byte order method
>             if (decrypted == null)
>             {
>                try
>                {
>                              decrypted = decryptData(encrypteddata, true);
>                 }
>                 catch (Exception e)
>                 {
>                              _log.error(e);
>                 }
>             }
>         }
>         catch (Exception e)
>         {
>             _log.error(e);
>         }
>
>         return decrypted;
>     }
>
>                public byte[] decryptData(byte[] encrypteddata, boolean useSwapOrder) throws Exception
>                {
>                               JSAFE_SymmetricCipher decryptor = null;
>         JSAFE_SecretKey key = null;
>        
>         //set the initialization vector.
>         byte[] ivData = getIV(useSwapOrder);
>         byte[] decrypted = null;
>        
>         int encryptedLength = encrypteddata.length;
>        
>                               try
>                               {
>                        decryptor = initCipher(ivData);
>                        key = generateRC2SecretKey(useSwapOrder);
>                        decryptor.decryptInit(key);
>                        
>                        byte[] decrypted_temp = new byte[decryptor.getOutputBufferSize(encryptedLength)];
>                        int bytes_written = decryptor.decryptUpdate(encrypteddata, 0, encryptedLength, decrypted_temp, 0);
>                
>                        //this should be a zero byte array leftover...
>                        int should_be_zero = decryptor.decryptFinal(decrypted_temp, bytes_written);
>                
>                        //copy the correct amount of bytes into the array.
>                        int len = bytes_written + should_be_zero;
>                        decrypted = new byte[len];
>                        System.arraycopy(decrypted_temp, 0, decrypted, 0, len);
>                               }
>                               finally
>                               {
>                        //Clean up for the decryptor
>                                              if (decryptor != null)
>                                                             decryptor.clearSensitiveData();
>                                              if (key != null)
>                                                             key.clearSensitiveData();
>                               }
>         return decrypted;
>                }
>                
>                public byte[] getEncryptedData(byte[] plainText, boolean encodeData) {
>         //set the initialization vector.
>         byte [] ivData = getIV(false);
>         //Initialize the Pseudo Random Number Generator.
>         JSAFE_SecureRandom random = getRandomGenerator();
>         //Initialize the Symmetric Cipher.
>         JSAFE_SymmetricCipher encryptor = initCipher(ivData);
>         //Perform the encryption.
>         byte [] cipherText = encryptData(encryptor, random, plainText, encodeData);
>
>         //clean up the cipher
>         encryptor.clearSensitiveData();
>         return cipherText;
>     }
>
>                public byte[] generateSecretKey()
>                {
>                               JSAFE_SecretKey key = generateRC2SecretKey(false);
>                               byte[] keybytes = key.getSecretKeyData();
>                               key.clearSensitiveData();
>                               return keybytes;
>                }
>
>                /**
>                * Initializes cipher object using initialization vector.
>                * @param iv - Initialization vector.
>                * @return cipher object.
>                */
>                private JSAFE_SymmetricCipher initCipher(byte[] iv)
>                {
>                               JSAFE_SymmetricCipher encryptor = null;
>                               try
>                               {
>                        encryptor = JSAFE_SymmetricCipher.getInstance(CIPHER_ALG_NAME, "Java");
>                        encryptor.setIV(iv, 0, iv.length);
>                               }
>                               catch (Exception anyException) {
>                                              _log.error("Exception caught while creating cipher object.");
>                                              _log.error(anyException.toString());
>                               }                             return encryptor;
>                }
>
>                /**
>                * Generates JSAFE_SecureRandon object.  Not suppoted for this algorithm.
>                * @return random object.
>                */
>                private JSAFE_SecureRandom getRandomGenerator()
>                {
>                               //NOT SUPPORTED.
>                               JSAFE_SecureRandom random = null;
>                               return random;
>                }
>
>                /**
>                * Encrypts the plain text using cipher, key and
>                * @param encryptor - Cipher
>                * @param random - SecureRandom object
>                * @param plainText - plain text
>                * @param encodeData - Encode data after encrypting it.
>                * @return encrypted data.
>                */
>                private byte[] encryptData(JSAFE_SymmetricCipher encryptor,
>                                                                                                                         JSAFE_SecureRandom random,
>                                                                                                                         byte[] plainText, boolean encodeData)
>                {
>                               JSAFE_SecretKey key = generateRC2SecretKey(false);
>                               int plainTextLen = plainText.length;
>                               byte[] cipherText = null;
>         try {
>                                              encryptor.encryptInit(key);
>                                              cipherText = new byte[encryptor.getOutputBufferSize(plainTextLen)];
>                                              int bytes_written = encryptor.encryptUpdate(plainText, 0, plainTextLen, cipherText, 0);
>
>                                              encryptor.encryptFinal(cipherText, bytes_written);
>                                              if (encodeData) {
>                                                             //********************************************
>                                                             cipherText = encodeBase64(cipherText, cipherText.length);//Base64.encode(cipherText).getBytes();
>                                                             //********************************************
>                                              }
>                               } catch (JSAFE_InvalidUseException e) {
>                                              _log.error(e);
>                               } catch (JSAFE_InvalidKeyException e) {
>                                              _log.error(e);
>                               } catch (JSAFE_IVException e) {
>                                              _log.error(e);
>                               } catch (JSAFE_InputException e) {
>                                              _log.error(e);
>                               } catch (JSAFE_PaddingException e) {
>                                              _log.error(e);
>                               } catch (JSAFE_Exception e) {
>                                              _log.error(e);
>                               }
>                               finally{
>                                              if(key != null)
>                                                             key.clearSensitiveData();
>                               }
>
>                               return cipherText;
>                }
>
>                private byte[] getIV(boolean useSwapOrder)
>                {
>                               JSAFE_SecretKey key = generateRC2SecretKey(useSwapOrder);
>                               byte[] secret = key.getSecretKeyData();
>                               if(secret == null)
>                               {
>                                              _log.error("The secret key is not available for this handler. Encryption failed");
>                                              return null;
>                               }
>
>                               //set the initialization vector.
>                               byte [] ivData = new byte[IV_SIZE];
>                               System.arraycopy(secret, 0, ivData, 0, IV_SIZE < secret.length ? IV_SIZE : secret.length);
>                               key.clearSensitiveData();
>                               return ivData;
>                }
>    
>                private JSAFE_SecretKey generateRC2SecretKey(boolean useSwapOrder)
>                {
>                               JSAFE_SecretKey key = null;
>         try {
>             byte[] serializationKey = new byte [24];
>             if (m_key != null) serializationKey = m_key;
>             else if (m_defaultKey != null) serializationKey = m_defaultKey;
>             else {
>                 BigInteger [] staticBytes = new BigInteger[12];
>                 staticBytes[0] = new BigInteger(Integer.toBinaryString(0x103f), 2);
>                 staticBytes[1] = new BigInteger(Integer.toBinaryString(0xe982), 2);
>                 staticBytes[2] = new BigInteger(Integer.toBinaryString(0x28fc), 2);
>                 staticBytes[3] = new BigInteger(Integer.toBinaryString(0xa7b4), 2);
>                 staticBytes[4] = new BigInteger(Integer.toBinaryString(0xdd52), 2);
>                 staticBytes[5] = new BigInteger(Integer.toBinaryString(0x8e8f), 2);
>                 staticBytes[6] = new BigInteger(Integer.toBinaryString(0x1749), 2);
>                 staticBytes[7] = new BigInteger(Integer.toBinaryString(0xe3ca), 2);
>                 staticBytes[8] = new BigInteger(Integer.toBinaryString(0x11bc), 2);
>                 staticBytes[9] = new BigInteger(Integer.toBinaryString(0x2341), 2);
>                 staticBytes[10] = new BigInteger(Integer.toBinaryString(0x7bd4), 2);
>                 staticBytes[11] = new BigInteger(Integer.toBinaryString(0x38a2), 2);
>
>                 if (!useSwapOrder) {
>                     //UNIX
>                     for (int j = 0; j < 12; j++) {
>
>                         byte [] buf1 = staticBytes[j].toByteArray();
>                         System.arraycopy(buf1, buf1.length - 2, serializationKey, j * 2, 2);
>
>                     }
>                 } else {
>                     //NT
>                     for (int j = 0; j < 12; j += 2) {
>                         byte [] buf1 = staticBytes[j].toByteArray();
>                         byte [] buf2 = staticBytes[j + 1].toByteArray();
>
>                         for (int k = 0; k < 4; k++) {
>                             int index = ((j / 2) * 4) + k;
>                             if (k < 2) {
>                                 System.arraycopy(buf2, 1 - k + (buf2.length - 2), serializationKey, index, 1);
>                             } else {
>                                 System.arraycopy(buf1, 3 - k + (buf1.length - 2), serializationKey, index, 1);
>                             }
>                         }
>                     }
>                 }
>             }
>
>             key = JSAFE_SecretKey.getInstance(SECRET_KEY_ALG_NAME, "Java");
>             key.setSecretKeyData(serializationKey, 0, serializationKey.length);
>
>         } catch (Exception e) {
>                _log.error(e);
>         }
>
>         return key;
>                }
>
>                public int getHandlerType()
>                {
>                               return RC2_128_CBC_PKCS5PADDING;
>                }
>
>                public String getHandlerTag()
>                {
>                               //this will be overridden
>                               return IAMCrypto.RC2_128_CBC_PKCS5PADDING_TAG;
>                }              
>
> }
>
>


Loading...