PBE Blowfish

I use a code to crypt a string , but I'dont undertand if is 128 bit encryption or not, and if is not how i can change my code
thanks
import org.bouncycastle.crypto.*;
import org.bouncycastle.crypto.engines.*;
import org.bouncycastle.crypto.modes.*;
import org.bouncycastle.crypto.params.*;
public class Encryptor {
private BufferedBlockCipher cipher;
private KeyParameter key;
// Initialize the cryptographic engine.
// The key array should be at least 8 bytes long.
public Encryptor( byte[] key ){
cipher = new PaddedBlockCipher(
new CBCBlockCipher(
new BlowfishEngine() ) );
this.key = new KeyParameter( key );
// Initialize the cryptographic engine.
// The string should be at least 8 chars long.
public Encryptor( String key ){
this( key.getBytes() );
// Private routine that does the gritty work.
private byte[] callCipher( byte[] data )
throws CryptoException {
int size =
cipher.getOutputSize( data.length );
byte[] result = new byte[ size ];
int olen = cipher.processBytes( data, 0,
data.length, result, 0 );
olen += cipher.doFinal( result, olen );
if( olen < size ){
byte[] tmp = new byte[ olen ];
System.arraycopy(
result, 0, tmp, 0, olen );
result = tmp;
return result;
// Encrypt arbitrary byte array, returning the
// encrypted data in a different byte array.
public synchronized byte[] encrypt( byte[] data )
throws CryptoException {
if( data == null || data.length == 0 ){
return new byte[0];
cipher.init( true, key );
return callCipher( data );
// Encrypts a string.
public byte[] encryptString( String data )
throws CryptoException {
if( data == null || data.length() == 0 ){
return new byte[0];
return encrypt( data.getBytes() );
// Decrypts arbitrary data.
public synchronized byte[] decrypt( byte[] data )
throws CryptoException {
if( data == null || data.length == 0 ){
return new byte[0];
cipher.init( false, key );
return callCipher( data );
// Decrypts a string that was previously encoded
// using encryptString.
public String decryptString( byte[] data )
throws CryptoException {
if( data == null || data.length == 0 ){
return "";
return new String( decrypt( data ) );
Martina

please help me!
thanks

Similar Messages

  • PBE with blowfish : is this solution secure

    Hi,
    I have designed a solution do do PBE with blowfish. Assuming there is no weak keys in Blowfish, and using a 160bits key (due to SHA-1) is this code secure ?
    MessageDigest md = MessageDigest.getInstance("SHA-1");         
    byte[] password = "here is the password I use !".getBytes();   
    byte[] key = md.digest(password);                                // hash the password on 160bits
    SecretKeySpec skspec = new SecretKeySpec(key, "Blowfish");       // prepare the key for the cipher
    Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding"); // create the cipher
    cipher.init(Cipher.ENCRYPT_MODE,skspec);
    byte[] someCipherText = cipher.doFinal(somePlainText);           Thanks
    Oliver.

    Also, Sun should better add public final static constants in the String class to have the names of encodings supported on all platforms:
    class String {
        public static final String ASCII = "US-ASCII";
        public static final String ISOLAT1 = "ISO8859_1";
        public static final String UTF8 = "UTF-8";
    }This would be a strong sign that at least these minimum encodings will be supported. Alternatively, these constants could be placed in a separate new class or interface (named for example Encoding).
    May be there should exist a valid value allowing to specify explicitly the native platform encoding if we still need it.
        public static final String NATIVE;Then there would be no more excuse to not use an explicit encoding:
        byte[] buffer = new byte[] { (byte)64, (byte)65 (byte)66 };
        String abc = new String(buffer, Encoding.ASCII); // returns a string equal to "ABC"
        buffer = new byte[] { (byte)0xc4, (byte)0x80, (byte)0 };
        abc = new String(buffer, Encoding.UTF8); // returns a string equal to "\u0100\u0000"

  • Basic PBE questions and clarifications

    I have some basic questions about PBE and java.
    My first question is how do I determine the size of the derived key that will actually be used? Do we have any control over that? I guess that the password strength is probably more important than size of derived key in PBE(?), but I'd still like to understand what's happening.
    Following on that - do the characteristics of the initial PBE password have any bearing on the strength of the encryption (ie the size of the derived key), when using PBE?
    Finally with standard install of Sun 1.5 JRE, the security jurisdication policy files prohibit the use of PBEWithMD5AndTripleDES. However the Sun JDK from 1.5 supports PBEWithSHA1AndDESede and this appears to work with the standard (strong), policy files.
    This being the case (and please correct if this is wrong), what is the difference between TripleDES and DESede - I thought they were analogous. Why is one PBE scheme available with standard (strong), 1.5 policy files and the other prohibited?

    peckham wrote:
    Thanks for response - cleared some things up. My focus now is on why PBEWithMD5AndTripleDES fails with 1.5 strong policy files whereas PBEWithSHA1AndDESede appears to work.
    You said:
    ... The only difference I can imagine is that TripleDES could use the two key version which has only 2*56 bits for a key but this would still require the 'unlimited strength files.To clarify do you mean to say DESede could use the two key 2*56 version? I ask because DESede is the one that seems to work so I would expect that to be the one using the smaller key size.
    Could you also explain why you would expect 2*56 version to require unlimited strength files - I thought 128 bits was the limit for DESede keys with Strong Jurisdiction Policy files.I thought the threshold was lower than 128 bits but I can't be certain.
    >
    >>
    Why is one PBE scheme available with standard (strong), 1.5 policy files and the other prohibited?As I said, they are they should be the same.
    Note - there was a bug in earlier JRE whereby if one used the key.getAlgorithm() method to use to create a Cipher i.e.
    Cipher cipher = Cipher.getInstance(key.getAlgorithm());one always got PBEWithMD5AndDES. This, of course, does not require the 'unlimited strength' files.
    I found [this posting |http://forums.sun.com/thread.jspa?threadID=5129170&start=0&tstart=0] that you (sabre150), contributed to back in 2007. I've modified the JDKIssueTestCase to use:
    Cipher cipher = Cipher.getInstance(algorithm);Running this under 1.5 with 'strong' policy files PBEWithMD5AndTripleDES fails but PBEWithSHA1AndDESede succeeds. Here is the output:
    JVM Name: "Java HotSpot(TM) Client VM"  Version: "1.5.0_10-b03"  Vendor: "Sun Microsystems Inc."
    OS Name: "Windows XP"  Version: "5.1"  Architecture: "x86"
    Sun JCE: [SunJCE version 1.5]  Info: [SunJCE Provider (implements RSA, DES, Triple DES, AES, Blowfish, ARCFOUR, RC2, PBE, Diffie-Hellman, HMAC)]
    Algorithm: [PBEWITHMD5ANDTRIPLEDES]  Max key length: [128]
    Result Failed: [java.security.InvalidKeyException: Illegal key size]
    Algorithm: [PBEWITHSHA1ANDDESEDE]  Max key length: [128]
    Result Encrypted: [-70, -45, 57, 35, -29, 5, -113, -118, 102, 14, -119, -81, 125, 8, 56, -8]
    Algorithm: [PBEWITHMD5ANDDES]  Max key length: [128]
    Result Encrypted: [-56, -33, -40, -75, -41, 48, -39, 83, 122, 88, -70, 27, -69, 55, 85, -18]
    Algorithm: [PBEWITHSHA1ANDRC2_40]  Max key length: [128]
    Result Encrypted: [50, 66, -63, -84, -123, 13, -113, 77, 67, 80, -66, -70, 90, 23, -53, 13]
    Interesting.
    So I'd still like to know what is happening here especially in light of the bug highlighted in thread 5129170 - if I use PBEWithSHA1AndDESede without unlimited strength jurisdiction files what encryption strength am I actually getting? No real idea. Research is required.
    >
    I know that most people won't care about this but I work in a monolithic organisation where 1.4 is still the default JRE. There may be other unfortunates out there in similarly constrained environments so this might still be of some benefit.:-)

  • PBE with JCE

    Hello, I am using password-based encryptation and I would like to know which posibilities does JCE offer.
    Just PBEWithMD5AndDES and PBEWithMD5AndTripleDES???
    In that case, which one would you recommend me?
    Thanks!

    Which you use depends on how secure you need it to be. Of the two I would use DESede but if your application is of low security you can use DES.
    Remember that the encryption is only as good as your passphrase.
    To see which PBE alorithms you have available you can run the following.
    import java.security.*;
    import java.util.Enumeration;
    //import org.bouncycastle.jce.provider.BouncyCastleProvider;
    public class ListAlgorithms
        public static void main(String[] args)
            Security.addProvider(new com.sun.crypto.provider.SunJCE());
            //Security.addProvider(new BouncyCastleProvider());
            System.out.println("Providers -");
            Provider[] providers = java.security.Security.getProviders();
            for (int index = 0; index < providers.length; index++)
                System.out.println("    " + providers[index].getName());
                Enumeration en = providers[index].propertyNames();
                while (en.hasMoreElements())
                    String alg = (String)en.nextElement();
                    //if (alg.toLowerCase().matches(".*pbe.*") && (alg.toLowerCase().matches(".*aes.*") || alg.toLowerCase().matches(".*blowfish.*")))
                    if (alg.matches("(?i).*pbe.*"))
                        System.out.println("        Alg = " + alg);
    }

  • Getting Error while decrypt a file using Blowfish algorithm

    I am using blowfish algorithm for encrypt and decrypt my file. this is my code for encrypting decrypting .
    while i am running program i am getting an Exception
    Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.BlowfishCipher.engineDoFinal(DashoA6275)
    at javax.crypto.Cipher.doFinal(DashoA12275)
    at Blowfishexe.main(Blowfishexe.java:65)
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.io.*;
    import org.bouncycastle.crypto.CryptoException;
    import org.bouncycastle.crypto.KeyGenerationParameters;
    import org.bouncycastle.crypto.engines.DESedeEngine;
    import org.bouncycastle.crypto.generators.DESedeKeyGenerator;
    import org.bouncycastle.crypto.modes.CBCBlockCipher;
    import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
    import org.bouncycastle.crypto.params.DESedeParameters;
    import org.bouncycastle.crypto.params.KeyParameter;
    import org.bouncycastle.util.encoders.Hex;
    public class Blowfishexe {
    public static void main(String[] args) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("Blowfish");
              kgen.init(128);
              String keyfile="C:\\Encryption\\BlowfishKey.dat";
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");
              System.out.println("key"+raw);
                   byte[] keyBytes = skey.getEncoded();
                   byte[] keyhex = Hex.encode(keyBytes);
                   BufferedOutputStream keystream =
    new BufferedOutputStream(new FileOutputStream(keyfile));
                        keystream.write(keyhex, 0, keyhex.length);
    keystream.flush();
    keystream.close();
    Cipher cipher = Cipher.getInstance("Blowfish");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
              System.out.println("secretKey"+skeySpec);
    FileOutputStream fos=new FileOutputStream("C:\\Encryption\\credit11.txt");
              BufferedReader br=new BufferedReader(new FileReader("C:\\Encryption\\credit.txt"));
              String text=null;
              byte[] plainText=null;
              byte[] cipherText=null;
              while((text=br.readLine())!=null)
              System.out.println(text);
              plainText = text.getBytes();
              cipherText = cipher.doFinal(plainText);
              fos.write(cipherText);
              br.close();
              fos.close();
              cipher.init(Cipher.DECRYPT_MODE, skeySpec);
              FileOutputStream fos1=new FileOutputStream("C:\\Encryption\\BlowfishOutput.txt");
              BufferedReader br1=new BufferedReader(new FileReader("C:\\Encryption\\credit11.txt"));
              String text1=null;
              /*while((text1=br1.readLine())!=null)
                   System.out.println("text is"+text1);
                   plainText=text1.getBytes("UTF8");
                   cipherText=cipher.doFinal(plainText);
                   fos1.write(cipherText);
              br1.close();
              fos1.close();
    //byte[] encrypted = cipher.doFinal("This is just an example".getBytes());
              //System.out.println("encrypted value"+encrypted);*/
    Any one pls tell me how to slove my problem
    thanks in advance

    hi
    i got the solution. its working now
    but blowfish key ranges from 56 to448
    while i am writing the code as
    KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
    keyGenerator.init(448);
    this code is generating the key upto 448 bits
    but coming to encoding or decode section key length is not accepting
    cipher.init(Cipher.ENCRYPT_MODE, key);
    Exception in thread "main" java.security.InvalidKeyException: Illegal key size or default parameters
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.init(DashoA12275)
    at javax.crypto.Cipher.init(DashoA12275)
    at Blowfish1.main(Blowfish1.java:46)
    i am getting this error
    what is the solution for this type of exception.
    thank you

  • Invalid stream header Exception - AES PBE with SealedObject

    I am trying to do an PBE encryption with AES algorithm and SunJCE provider, using the SealedObject class to encrypt/decrypt the data...
    And Im still getting the "invalid stream header" exception. Ive searched this forum, readed lots of posts, examples etc...
    Here is my code for encryption (i collected it from more classes, so hopefully I didnt forget anything...):
        //assume that INPUT_STREAM is the source of plaintext
        //and OUTPUT_STREAM is the stream to save the ciphertext data to
        char[] pass; //assume initialized password
        SecureRandom r = new SecureRandom();
        byte[] salt = new byte[20];
        r.nextBytes(salt);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec keySpec = new PBEKeySpec(pass, salt, 1536, 128);
        SecretKey pbKey = factory.generateSecret(keySpec);
        SecretKeySpec key = new SecretKeySpec(pbKey.getEncoded(), "AES");
        Cipher ciph = Cipher.getInstance("AES/CTR/NoPadding");
        ciph.init(Cipher.ENCRYPT_MODE, key);
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        int ch;
        while ((ch = INPUT_STREAM.read()) >= 0) {
          byteOut.write(ch);
        SealedObject sealed = new SealedObject(byteOut.toByteArray(), ciph);
        BufferedOutputStream bufOut = new BufferedOutputStream(OUTPUTSTREAM);
        ObjectOutputStream objOut = new ObjectOutputStream(bufOut);   
        objOut.writeObject(sealed);
        objOut.close();
      }And here is my code for decrypting:
        //assume that INPUT_STREAM is the source of ciphertext
        //and OUTPUT_STREAM is the stream to save the plaintext data to
        char[] pass; //assume initialized password
        SecureRandom r = new SecureRandom();
        byte[] salt = new byte[20];
        r.nextBytes(salt);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec keySpec = new PBEKeySpec(pass, salt, 1536, 128);
        SecretKey pbKey = factory.generateSecret(keySpec);
        SecretKeySpec key = new SecretKeySpec(pbKey.getEncoded(), "AES");
        BufferedInputStream bufIn = new BufferedInputStream(INPUT_STREAM);    //MARK #1
        ObjectInputStream objIn = new ObjectInputStream(bufIn);   
        SealedObject sealed = (SealedObject) objIn.readObject();   
        byte[] unsealed = (byte[]) sealed.getObject(key);          //MARK #2
        ByteArrayInputStream byteIn = new ByteArrayInputStream(unsealed);
        int ch;
        while ((ch = byteIn.read()) >= 0) {
          OUTPUT_STREAM.write(ch);
        OUTPUT_STREAM.close();Everytime I run it, it gives me this exception:
    Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: B559ADBE
         at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:783)
         at java.io.ObjectInputStream.<init>(ObjectInputStream.java:280)
         at javax.crypto.SunJCE_i.<init>(DashoA13*..)
         at javax.crypto.SealedObject.unseal(DashoA13*..)
         at javax.crypto.SealedObject.getObject(DashoA13*..)
         at oopsifrovanie.engine.ItemToCrypt.decrypt(ItemToCrypt.java:91)  //MARKED AS #2
         at oopsifrovanie.Main.main(Main.java:37)    //The class with all code below MARK #1I've also found out that the hashCode of the generated "key" object in the decrypting routine is not the same as the hashCode of the "key" object in the ecrypting routine. Can this be a problem? I assume that maybe yes... but don't know what to do...
    When I delete the r.nextBytes(salt); from both routines, the hashCodes are the same, but that's not the thing I want to do...
    I think, that the source of problem can be this part of code (generating the key):
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec keySpec = new PBEKeySpec(pass, salt, 1536, 128);
        SecretKey pbKey = factory.generateSecret(keySpec);
        SecretKeySpec key = new SecretKeySpec(pbKey.getEncoded(), "AES");But I derived it from posts like: [http://forums.sun.com/thread.jspa?threadID=5307763] and [http://stackoverflow.com/questions/992019/java-256bit-aes-encryption] and they claimed it's working there...
    Is there anyone that can help me?
    Btw, I don't want to use any other providers like Bouncycastle etc. and I want to use PBE with AES and also SealedObject to store the parameters of encryption...

    Yes, it really uses only one Cipher object, but it does decoding in a little nonstandard (not often used) way, by using the SealedObject class and its getObject(Key key) method. You can check these links for documentation: [http://java.sun.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#SealedObject] and [http://java.sun.com/javase/6/docs/api/javax/crypto/SealedObject.html] So the question is, why it doesn't work also with the AES routines, because it should.
    Btw, according to [http://java.sun.com/javase/6/docs/technotes/guides/security/SunProviders.html#SunJCEProvider] PBEWithSHA1AndDESede/CBC/PKCS5Padding is a valid JCE algorithm for the Cipher class.
    Firstly, I was generating the key for AES enc./decryption this way and it was working:
    char[] pass; //assume initialized password
    byte[] bpass = new byte[pass.length];
        for (int i = 0; i < pass.length; i++) {
          bpass[i] = (byte) pass;
    SecretKeySpec key = new SecretKeySpec(bpass, "AES");
    But I think, that it really wasn't secure, so I wanted to build a key from the password using the PBE.
    Maybe there's also a way how to do this part of my AES PBE algorithm: *KeySpec keySpec = new PBEKeySpec(pass, salt, 1536, 128);* manually (with my own algorithm), but I dont know how to do it and I'd like it to be really secure.
    Btw, thanks for your will to help.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Can't decrypt binary file with PBE

    Hi,
    I'm writing an simple file transfer application using UDP that encrypts the data
    before sending it with PBEWithMD5AndDES. Text files are encrypted and
    decrypted fine, but binary files such as a JPG/EXE/DOC... are messed up
    and an application can't open them on the other side. Has anyone experienced
    such a problem?
    Thanks

    Below are my encrypt and decrypt functions.
    Thanks in advance.
            public  byte[] encrypt(byte[] data)
                 PBEKeySpec pbeKeySpec;
                 PBEParameterSpec pbeParamSpec;
                 SecretKeyFactory keyFac;
                 ByteArrayOutputStream b=null;
                 DataOutputStream d =null;
                 //      Salt
                 byte[] salt = {
                           (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
                        (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
                 //      Iteration count
                 int count = 1000;
                 // Create PBE parameter set
                 pbeParamSpec = new PBEParameterSpec(salt, count);
                 try{
                      pbeKeySpec = new PBEKeySpec(sessionPassword.toCharArray());
                      keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES","SunJCE");
                      SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
                      // Create PBE Cipher
                      Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES","SunJCE");
                      // Initialize PBE Cipher with key and parameters
                      pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
                      b = new ByteArrayOutputStream();
                      d = new DataOutputStream(b);
                      // create CipherOutputStream
                      CipherOutputStream out = new CipherOutputStream( b, pbeCipher );
                      // write contents to file and close
                      try {
                           for ( int i = 0; i < data.length; i++ )
                                out.write(data);
                             out.flush();
                        out.close();
                   // handle IOException
                   catch ( IOException exception ) {
                        exception.printStackTrace();
              catch(Exception e){}
              return(b.toByteArray());
         public byte[] decrypt(byte[] data)
              PBEKeySpec pbeKeySpec;
              PBEParameterSpec pbeParamSpec;
              SecretKeyFactory keyFac;
              byte[] decryptedData=null;
              //      Salt
              byte[] salt = {
                        (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
                        (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
              //      Iteration count
              int count = 1000;
              // Create PBE parameter set
              pbeParamSpec = new PBEParameterSpec(salt, count);
              try{
                   pbeKeySpec = new PBEKeySpec(sessionPassword.toCharArray());
                   keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES","SunJCE");
                   SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
                   // Create PBE Cipher
                   Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES","SunJCE");
                   // Initialize PBE Cipher with key and parameters
                   pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);
                   Vector fileBytes = new Vector();
                   ByteArrayInputStream b = new ByteArrayInputStream(data);
                   CipherInputStream in = new CipherInputStream( b, pbeCipher );
                   byte contents = ( byte ) in.read();
                   while ( contents != -1 )
                        fileBytes.add( new Byte( contents ) );
                        contents = ( byte ) in.read();
                   in.close();
                   decryptedData = new byte[ fileBytes.size() ];
                   for ( int i = 0; i < fileBytes.size(); i++ )
                        decryptedData[ i ] = (( Byte )fileBytes.elementAt( i )).byteValue();
              catch(Exception e){Gui.chatArea.append("exception:"+e+"\n");}
              return(decryptedData);

  • Why is the Hootie and the Blowfish album Cracked Rear View not uploaded?

    I'm specifically looking for the song "let her cry" by Hootie and the Blowfish. I've also noticed the album Cracked Rear View is not uploaded either.

    It's a bug. And you don't have to reset the phone, just exit to the Home screen, then press HOME twice to bring up the Quick Launch bar. Hold a finger on the Photo app until it wriggles, then tap the "-" to close the app. When you relaunch it the problem will be gone (until next time)

  • Very urgent : please help !!!! Blowfish problem

    Greetings people,
    I have devised an application which reads the value from file and encrypts it (using Blowfish)......The file is then read and decrypted accordingly..............
    Problem : I seem to be able to encrypt and further decrypt file(s) which size is below 100 bytes. Anything beyond that will trigger the following :
    javax.crypto.IllegalBlockSizeException: Input length (with padding) not multiple of 8 bytes
    at com.sun.crypto.provider.SunJCE_h.a(DashoA6275)
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.BlowfishCipher.engineDoFinal(DashoA6275)
    at javax.crypto.Cipher.doFinal(DashoA6275)
    at LockDownBase.decrypt(LockDownBase.java:144)
    Could someone please help me with this dilemma as time is of the essence at this point and I really need to get this thing up and running. (ps. It is necessary for me to retain the usage of the Base64 Encoder as I am conducting a study on the usage of this Encoder).
    Thank you for the help
    <code>
    import java.io.*;
    import java.math.*;
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import sun.misc.*;
    public class LockDownBase {
    private static String keyFile = "c:\\encode\\blowfishbase.txt";
    public static String new_key (String me) throws Exception {
    //Get a blowfish key
    KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
    keyGenerator.init(128);
    SecretKey key = keyGenerator.generateKey();
    System.out.println("OK");
    byte [] encoded = key.getEncoded();
    FileOutputStream fos = new FileOutputStream(keyFile);
    fos.write(encoded);
    fos.close();
    return me;
    //initKey
    public static Key initKey() throws Exception{
    FileInputStream in = new FileInputStream(keyFile);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int i;
    while((i=in.read()) != -1){
    baos.write(i);
    in.close();
    byte [] keys = baos.toByteArray();
    SecretKeySpec key = new SecretKeySpec(keys,"Blowfish");
    Key keyword = key;
    return key;
    public static String encrypt (String location) throws Exception{
    //PrintStream is deprecated, but works fine in jdk1.1.7b
    //PrintStream output1 = new PrintStream(outFile1);
    //get_key
    String testme = "dummy";
    Key key = initKey();
    Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    // read in the input file
    String line;
    StringBuffer buffer = new StringBuffer();
    FileInputStream fis = new FileInputStream(location);
    InputStreamReader isr = new InputStreamReader(fis);
    Reader in = new BufferedReader(isr);
    int ch;
    while ((ch = in.read()) > -1) {
    buffer.append((char)ch);
    in.close();
    line = buffer.toString();
    byte [] cipherText = cipher.doFinal(line.getBytes("UTF8"));
    //output1.print(" ");
    // output1.println("ciphertext.length = " + cipherText.length);
    // print out representation of ciphertext to general output file
    BASE64Encoder encoding = new BASE64Encoder();
    String feed = encoding.encode(cipherText);
    FileOutputStream outFile2 = new FileOutputStream(location);
    PrintStream output2 = new PrintStream(outFile2);
    output2.close();
    String dir = location;
    FileOutputStream outFile3 = new FileOutputStream(dir);
    PrintStream output3 = new PrintStream(outFile3);
    output3.println(feed);
    output3.close();
    return location;
    public static String decrypt (String location) throws Exception{
    Key key = initKey();
    String line;
    String dir = location;
    FileReader far = new FileReader (dir);
    BufferedReader stdin = new BufferedReader(far,8192);
    String line = null;
    while ((line = stdin.readLine()) != null){
    BASE64Decoder decoding = new BASE64Decoder();
    byte[] decrypted = decoding.decodeBuffer(line);
    Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte [] decryptedtext = cipher.doFinal(decrypted);
    String output = new String (decryptedtext,"UTF8");
    System.out.println(output);
    FileOutputStream outFile1 = new FileOutputStream(location);
    PrintStream output1 = new PrintStream(outFile1);
    output1.println(output);
    output1.close();
    return location;
    </code>

    The error message says it all.
    Input length (with padding) not multiple of 8 bytes
    As you are using PKCS5Padding you will have an output data whose length is padded with 1 a 8 bytes. For instance, if your original data have 1023 bytes, it is padded with 1 byte - total length = 1024. It your original data have 1024 bytes, it will be padded with 8 bytes (not 0 as you could think).
    You have some problem encoding and decoding Base-64 - it is not yielding the original encrypted results. Your best friend is System.out.println of the length of the original and encrypted data.

  • Some clarification needed on PKCS #5 PBE

    Hi all,
    This is my first time posting on SUN Forums. Hope to be able to get your assistance in the programming field.
    I have questions about PKCS #5, as I couldn't understand how it can help improve security when using salt and iteration count.
    PKCS #5 states that salt and iteration count does not need to be kept secret as it is normally appended with the encrypted data.
    To my understanding,
    On encryption side, user will input a password and salt will be appended to the password, followed by a hashing algorithm.
    key[1] = SHA-1(password+salt)
    Iteration count addeds to key strengthening by:
    Key [1] = SHA-1(password+salt)
    key[2] = SHA-1(Key[1])
    Key[i] = SHA-1 (Key[i-1]
    Encrypted Data will then be obtained by:
    Ciphertext = AES(Key[i] and Plaintext)
    Hence the data payload will be as follows:
    || Encrypted Data+Salt+Iteration Count ||.
    When the receiver receives the message, the decryption is similar.
    key[1]= (password+obtained salt) from Payload
    Key[i] will then be obtained depends on the Iteration Count,
    and encrypted Data will be decrypted with Key.
    My lack of understanding here is how does using salt increases security when the salt is public?
    If a 56bit salt is used and only available to the receiver, any attacker who wants to decrypt the message might need to try 2^56 possible keys using a SINGLE password.
    But if the salt is public, the only difference from adding salt and not adding salt is the key strengthening process.
    How is password based encryption safer when comparing to AES-128 when the password the user input maybe commonly 48 bits?
    Thank you all in advance! Hope to receive replies!
    Regards,
    Brandon

    barnnod wrote:
    Hi Sabre150,
    Thank you for your suggestion. My application is enterprise based hence I think it is okay that the password is made known to employees only. (E.g one password per day, different department deploys different password each day). So each day each department has to distribute it's daily password to each department it needs to communicate with. So not just once every now and then do you have a key distribution problem you have one every day.
    >
    My actual scenario given by the school is:
    "An organisation's daily operations involve frequent data messaging among mobile devices. The data transmitted are confidential and recently it has been observed that there is an increased number of incidents involving unauthorised tapping of data signals from unknown sources. Due to the sensitivity of data, the senior management has commissioned its IT security team to propose a prototype for a secured messaging application to enhance data transmittion security. The solution must also fufil operational needs such as response time and peak traffic tranmission."
    I am very glad that you are helping me in this. What kind of encryption scheme do you think I can adopt? As I said. I would use Public Key cryptography probably using RSA.
    What I have thought about is:
    1) PBE I view PBE as suitable for personal use only. For example - if I want to encrypt data just for myself then using a password based approach makes sense since I don't have to distribute the key. I just keep it in my head.
    2) PKCSYou would need to elaborate on this since PKCS is a broad brush.
    3) Create a messaging server who can help distribute public keys. (But I left with 3 weeks upon completion and im not very confident of this because i dont know how to :( )Public Key distribution is fairly easy since you want everybody to have access to your public key. The public key could be broadcast as an SMS message or posted on a web server for people to download. I publish my public key on my web server.
    So as what I derived from your post, the key distribution problem can be solved using asymmetric key algorithm. Pretty much so but not completely. One needs to be able to verify that a particular public key belongs to who you think it does. This process is normally done by distributing a certificate that contains the Public Key. The certificate is signed by a Certification Authority who does checks to make sure the purported owner is actually the owner. Since this is for internal use, rather than paying a fortune to a third party CA, one can use one of the free ones. You might want to take a look at [http://www.devx.com/Java/Article/10185|http://www.devx.com/Java/Article/10185] but there are others out there.
    >
    Meaning the Sender A uses Receiver A's public key and using RSA(randomly generated symmetric key), and send the ciphertext over to Receiver A. Receiver A uses it's own private key to decrypt the ciphertext, and obtain the private symmetric key between Sender A and Receiver A. Sender A and Receiver A .That is the way I would do it
    then can securely do messaging from then on. The session keys would not be used more than once. Each message would use a different random session key.
    But I do not know how can I derive the Receiver A's public key. I guess the use of a messaging server can solve this.Yes. Or a simple Web server. An admin person just publishes the public keys for each user and each user just sends his public key to the admin person just once.
    >
    Please advice!
    Thank you :)You background makes doing the whole thing in 3 weeks a bit tight so you should leverage any third party software you can.
    Since this is a school/university project you might just want to use PBE for the moment and then in your report explain the key distribution problem and explain how to a more comprehensive and secure system could be achieved. That way you get to do the work and to show your examiners that you have thought about the problems associated with your naive PBE based solution and can propose a better solution. In your position I would ask my Tutor for advice on this - it could save you a load of effort.
    I don't work with Mobile devices so I don't know what libraries are available. I suspect you may need design your solution around what tools you have available.
    Edited by: sabre150 on Sep 27, 2009 12:45 PM

  • Password choice for PBE

    Hi everybody,
    I'm writing a little webproject which is writing encrypted texts into a database using PBE (with Jasypt packages) and displaying it decrypted. I'm using "PBEWITHSHA256AND256BITAES-CBC-BC" (BouncyCastleProvider).
    Everthing is working fine, but I have a question regarding the password which used to generate the key.
    How can make sure that my password is complex enough to make real use of the 256bit AES?
    The password is saved as cleartext in my javacode cause I' have to decrypt the texts as well.
    The second questions is if it is common to "store" the password as cleartext in my WebApplication or are there other more secure ways to do it?
    sorry for my bad english.
    greetings philipp

    Don't worry about your english, Philip; you're getting your meaning across :-).
    David Hook - the creator of BouncyCastle - wrote in his book that you have to question the effectiveness of your encryption if you're using strong ciphers like 3DES or AES-256, but using weak passwords to protect the symmetric keys. His point - and every experienced security practitioners' - is that the overall security of a system is ultimately dependent on the weakest link in the chain. And in PBE, the typical weak link is the password and how you protect that password.
    I would encourage you to do the following:
    1) Write - or lookup - a password routine that requires strong passwords (a combination of alpha, numeric and special characters);
    2) Not store the password in a file at all, but have the Servlet/J2EE container prompt for the password upon startup. If the business requirements will not allow for an SA to supply the password upon startup (because they want an automatic restart), then make it clear that the system has a residual vulnerability that can potentially be exploited by an attacker who compromises the machine.
    You cannot have an automatic restart of an application with cryptography modules in it, and robust security at the same time. You have to protect that weak link in the chain using an external process or control. Businesses need to understand this. As long as security programmers and practitioners keep delivering code/systems that gives the impression of security without actually providing it, the bad guys always win.

  • PBE; final block not properly padded help!

    Hi there,
    I'm having problems decrypting passwords using password based encryption (PBE), throwing me a "final block not properly padded" exception.
    The passwords are also encrypted uses PBE in a seperate class called the PasswordEncryption. The code necessary to generate the Cipher is in a seperate method which is passed a String to determined if it would be initialized in "encrypt" or "decrypt" mode.
    The class where the passwords are decrypted, UserManager, is passed the encrypted passwords as a String. It calls the PasswordEncryption class gets getcipher() to get the Cipher, and then decrypts the password. The data is read from the database by another class which reads database info, and passed in as a string to the decrypting class. The decrypting class converts the string to a byte[].
    Below I have the UserManager class and PasswordEncryption class:
    public class UserManager
    implements SecurityServerInterface, PETComponent {
    public UserManager() {
    private static String decryptPassword(String asPassword) throws
    SecurityException {
    PasswordEncryption passwordEncryption = new PasswordEncryption();
    Cipher pbeCipher = passwordEncryption.getCipher("decrypt");
    String clearText = new String();
    byte[] encryptedPassword = asPassword.getBytes();
    try {
    //This is where decryption failed! Given final block not properly padded
    byte[] cipherText = pbeCipher.doFinal(encryptedPassword);
    System.out.println(cipherText);
    System.out.println("test cipher text");
    clearText = new String(cipherText);
    System.out.println("original:" + asPassword);
    System.out.println("decrypted:" + clearText);
    catch (IllegalBlockSizeException e) {
    System.out.println(e.getMessage());
    String illegalBlock = e.getMessage();
    throw new SecurityException(illegalBlock);
    catch (BadPaddingException e) {
    System.out.println(e.getMessage());
    String badPadding = e.getMessage();
    throw new SecurityException(badPadding);
    catch(Exception e) {
    System.out.println(e.getMessage());
    String exception = e.getMessage();
    throw new SecurityException(exception);
    System.out.println(clearText);
    return clearText;
    public class PasswordEncryption {
    public static void main(String[] args) throws PETDBException,
    SecurityEncryptionException {
    PasswordEncryption encryptor = new PasswordEncryption();
    ArrayList mainList = encryptor.getAllPasswords();
    mainList = encryptor.encryptAllPasswords(mainList);
    encryptor.updateAllPasswords(mainList);
    public PasswordEncryption() {
    //Get passwords from the user table of the database, e.g, loginName and passwords
    private ArrayList getAllPasswords() throws PETDBException {
    ArrayList passwordList = new ArrayList();
    DBConnection.setConnection("jdbc:mysql://localhost/Mysql/data/pet?user=root&password=");
    DBConnection dbCon = DBConnection.createConnection();
    Connection con = dbCon.getConnection();
    System.out.println(con);
    try {
    String allPasswordQuery = " SELECT " + DBColumns.USPASSWD.trim() + " , " +
    DBColumns.USLOGINNAME.trim() + " from " + DBColumns.USER;
    Statement stmt = con.createStatement();
    ResultSet rs;
    rs = stmt.executeQuery(allPasswordQuery);
    if (rs.isFirst()) {
    throw new PETDBException("No password found in the database.");
    while (rs.next()) {
    UserDO loUserDO = new UserDO();
    loUserDO.setPassword(rs.getString(DBColumns.USPASSWD));
    loUserDO.setLoginName(rs.getString(DBColumns.USLOGINNAME));
    passwordList.add(loUserDO);
    catch (SQLException sql) {
    String sqlError = sql.getMessage();
    throw new PETDBException(sqlError);
    return passwordList;
    private ArrayList encryptAllPasswords(ArrayList aoPasswordList) throws
    SecurityEncryptionException {
    // Encrypt the password
    Cipher pbeCipher = getCipher("encrypt");
    Iterator passwordIterator = aoPasswordList.iterator();
    UserDO loUserDO = new UserDO();
    try {
    while (passwordIterator.hasNext()) {
    loUserDO = (UserDO) passwordIterator.next();
    String lsPassword = loUserDO.getPassword();
    byte[] clearTextPassword = lsPassword.getBytes();
    byte[] cipherText = pbeCipher.doFinal(clearTextPassword);
    String cipherString = new String(cipherText);
    loUserDO.setPassword(cipherString);
    System.out.println(cipherString);
    catch (IllegalBlockSizeException e) {
    throw new SecurityException("Can't encrypt password, illegal block size");
    catch (BadPaddingException e) {
    throw new SecurityException("Can't encrypt password, bad padding");
    System.out.println(aoPasswordList);
    return aoPasswordList;
    public Cipher getCipher(String mode) {
    PBEKeySpec pbeKeySpec;
    PBEParameterSpec pbeParamSpec;
    SecretKeyFactory keyFac;
    // Salt
    byte[] salt = {
    (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
    (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
    // Iteration count
    int count = 20;
    // Create PBE parameter set & a SecretKey
    pbeParamSpec = new PBEParameterSpec(salt, count);
    SecretKey pbeKey;
    // Use our own encryption password.
    // Collect the password as char array and convert
    // it into a SecretKey object, using a PBE key
    // factory.
    char[] password = new String("cmuw-team5").toCharArray();
    pbeKeySpec = new PBEKeySpec(password);
    try {
    keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    pbeKey = keyFac.generateSecret(pbeKeySpec);
    catch (NoSuchAlgorithmException e) {
    throw new SecurityException("Can't collect password as a char array");
    catch (InvalidKeySpecException e) {
    throw new SecurityException("Can't convert password into a SecretKey Object");
    // Create PBE Cipher
    Cipher pbeCipher;
    try {
    pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
    catch(NoSuchAlgorithmException e) {
    throw new SecurityException("Can't create a PBE Cipher, no such algorithm");
    catch(NoSuchPaddingException e) {
    throw new SecurityException("Can't create a PBE Cipher, no such padding");
    // Initialize PBE Cipher with key and parameters
    if (mode == "encrypt") {
    try {
    pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
    catch(InvalidKeyException e) {
    throw new SecurityException("Can't initialize PBE Cipher with key");
    catch(InvalidAlgorithmParameterException e) {
    throw new SecurityException("Can't initialize PBE Cipher with parameters");
    if (mode == "decrypt") {
    try {
    pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);
    catch(InvalidKeyException e) {
    throw new SecurityException("Can't initialize PBE Cipher with key");
    catch(InvalidAlgorithmParameterException e) {
    throw new SecurityException("Can't initialize PBE Cipher with parameters");
    return pbeCipher;
    //Get encrypted passwords out of the ArrayList and update the database
    private void updateAllPasswords(ArrayList aoUpdatePasswordList) throws
    PETDBException {
    DataService dataService = new DataService();
    Iterator getEncryptPassword = aoUpdatePasswordList.iterator();
    String lsUpdatePassword = new String();
    String lsUserName = new String();
    Statement stmt;
    DBConnection dbCon = DBConnection.createConnection();
    Connection con = dbCon.getConnection();
    try {
    stmt = con.createStatement();
    System.out.println(stmt);
    catch (SQLException sql) {
    String sqlError = sql.getMessage();
    System.out.println(sqlError);
    throw new PETDBException(sqlError);
    while (getEncryptPassword.hasNext()) {
    UserDO loUser = (UserDO) getEncryptPassword.next();
    lsUpdatePassword = loUser.getPassword();
    lsUserName = loUser.getLoginName();
    String allUpdatePassword = " UPDATE " + DBColumns.USER + " SET " +
    DBColumns.USPASSWD + " = " + "'" + lsUpdatePassword + "'" + " WHERE "
    + DBColumns.USLOGINNAME + " = " + "'" + lsUserName + "'";
    System.out.println(allUpdatePassword);
    try {
    int returnValue = stmt.executeUpdate(allUpdatePassword);
    System.out.println(returnValue);
    catch (SQLException sql) {
    String sqlError = sql.getMessage();
    throw new PETDBException(sqlError);
    try {
    con.commit();
    con.close();
    catch (SQLException sql) {
    String sqlError = sql.getMessage();
    throw new PETDBException(sqlError);

    Thanks for the prompt response! I got this example
    from the Sun Java cryptography extensions web page at:
    http://java.sun.com/j2se/1.4.2/docs/guide/security/jce/
    CERefGuide.html#PBEExThe code I'm pointing out did not come from there. Nowhere in Sun's examples do you see them creating Strings directly from ciphertext. (Which is good, because if you did, their examples wouldn't work). To give some more context on where the problem is:private ArrayList encryptAllPasswords(ArrayList aoPasswordList) throws SecurityEncryptionException {
      // Encrypt the password
      Cipher pbeCipher = getCipher("encrypt");
      Iterator passwordIterator = aoPasswordList.iterator();
      UserDO loUserDO = new UserDO();
      try {
        while (passwordIterator.hasNext()) {
          loUserDO = (UserDO) passwordIterator.next();
          String lsPassword = loUserDO.getPassword();
          byte[] clearTextPassword = lsPassword.getBytes();
          byte[] cipherText = pbeCipher.doFinal(clearTextPassword);
          // DOING THE FOLLOWING TO CIPHERTEXT TURNS IT INTO GARBAGE!
          String cipherString = new String(cipherText);
          loUserDO.setPassword(cipherString);
          System.out.println(cipherString);
      } catch (IllegalBlockSizeException e) {
        throw new SecurityException("Can't encrypt password, illegal block size");
      } catch (BadPaddingException e) {
        throw new SecurityException("Can't encrypt password, bad padding");
      System.out.println(aoPasswordList);
      return aoPasswordList;
    }(Note: Please use the [ code ] tags when you post code - it makes it MUCH easier to figure out what you're doing.)
    Also, my decryption code in the UserManager class does
    work for two out of 8 users....I can't really figure
    out why it's working for Only 2 users, and not the
    rests. It's possible that the ciphertext is successfully string-able in those two cases (although I doubt it). But I can absolutely guarantee to you that trying to treat ciphertext as a String will turn your ciphertext into grabage, and that will result in a BadPaddingException when you decrypt. You need to stop doing that.
    If you need to treat ciphertext or keys as Strings, the right way to do it is to Base64-encode the byte[] into a String, and then Base64-decode when you want to decrypt.
    Grant

  • NoSuchAlgorithmException with 1.5.0Beta2 and Blowfish

    Hi,
    I try to use the Blowfish algorithm with jdk 1.5.0Beta2.
    When I run the following code (the standard code from http://sourceforge.net/snippet/detail.php?type=snippet&id=100808)
    I get a NoSuchAlgorithmException
    // Install SunJCE provider
    Provider sunJce = new SunJCE();
    Security.addProvider(sunJce);
    KeyGenerator kgen = KeyGenerator.getInstance("Blowfish");
    The line
    Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
    does not work either
    When I print out the installed providers and services I get the following output:
    Blowfish
    SunJCE: Cipher.Blowfish -> com.sun.crypto.provider.BlowfishCipher
    attributes: {SupportedModes=ECB|CBC|PCBC|CTR|CFB|OFB|CFB8|CFB16|CFB24|CFB32|CFB40|CFB48|CFB56|CFB64|OFB8|OFB16|OFB24|OFB32|OFB40|OFB48|OFB56|OFB64, SupportedPaddings=NOPADDING|PKCS5PADDING|ISO10126PADDING, SupportedKeyFormats=RAW}
    Blowfish
    SunJCE: KeyGenerator.Blowfish -> com.sun.crypto.provider.BlowfishKeyGenerator
    So I think the JCE Provider which provides the Blowfish algorithm and key generator is installed correctly.
    What causes the exception then?
    I also installed the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 1.5.0 Beta 2      
    I use WinXP SP1
    What is wrong?
    Thanks, Markus

    I tried your code and it worked fine on JRE 1.5.0 beta2 as well as on JRE 1.4.2_02.

  • NIS passwords and blowfish

    I've posted this in a different forum as it exists in 10.3 and 10.4, but that area has less traffic and I hope a larger audience will have the answer.
    NIS in 10.4.6 will check DES passwords ok, but will not do blowfish passwords. Is there a way to get Tiger to correctly authenticate blowfish passwords?
    I've gotten OpenBSD, Linux, and Solaris to do so, so I hope Mac OS X has the ability too.

    Make sure that you not run Firefox in (permanent) [[Private Browsing]] mode
    See also http://kb.mozillazine.org/signon.autofillForms

  • Decryption of Blowfish key

    All,
    I have a Blowfish key that was originally generated elsewhere, I assume with PHP. I need to use this key like so:
    1. Do mysql query from db for username and password.
    2. Decrypt username and password.
    I am new to encryption. Not sure of a key is a keystore, a key a certifcate, etc..?
    How can I load this baby and use it? I am doing my own research, but I am new to encryption, so this will take a while : (
    M

    I have adjusted my method, there are no exceptions, but my decrypted string looks funny:
    1kgZslMOZl6M9A7AW0OpzeReMeedZ4iUqEdIw4r8zAQ=
    Also, when I try to decrypt field from mysql in the same row, with the same key, I get invalid padding errors.
    I get the encrypted data from mysql using:
    public static Hashtable<String,String> Info(String coId)throws Exception {
              boolean isConnected = false;
            // TODO Auto-generated method stub
            Hashtable<String, String> Info = new Hashtable<String,String>();
            if (!isConnected) {
                  // Makes connection
                  try {
                        Class.forName("com.mysql.jdbc.Driver");
                        Connection connect = DriverManager.getConnection("fdfsdfdfsd","sdasd","sdad");
                  isConnected = true;
                  PreparedStatement s = connect.prepareStatement("SELECT ID, PASSWORD FROM  WHERE CoID=? AND ID IS NOT NULL AND PASSWORD IS NOT NULL;");
                  s.setString(1, coId);
                  BASE64Decoder base64 = new BASE64Decoder();
                  ResultSet rs = s.executeQuery();
                  int keyIndex = 0;
                  while (rs.next()) {
                       Blob idBlob = rs.getBlob("ID");
                       Blob passBlob = rs.getBlob("PASSWORD");
                      (int)passBlob.length());
                       InputStream inP = passBlob.getBinaryStream();
                       InputStream inID = idBlob.getBinaryStream();
                       byte[] p = base64.decodeBuffer(inP);
                       byte[] id = base64.decodeBuffer(inID);
                       String pp = new String(p, "UTF8");
                       String idid = new String(id, "UTF8");
                      Info.put("ID", idid);
                      Info.put("PASSWORD", pp);Main Method:
    public static void main(String[] args)throws Exception{
              BlowfishWorker blowfish = new BlowfishWorker();
              Hashtable<String, String> login = new Hashtable<String, String>();
              login =  blowfish.salesForceInfo("Company");
              String id = login.get("ID");
              //System.out.println("print id"+id);
              String password = login.get("PASSWORD");
              //System.out.println("Before decryption");
              //String passwordDB = new String(password);
              System.out.println("----------------------------");
              System.out.println("After decryption");
              String p = blowfish.decrypt(password);
              //I get1kgZslMOZl6M9A7AW0OpzeReMeedZ4iUqEdIw4r8zAQ= for p
              System.out.println("Pass: "+p);
              System.out.println("------------------------------------");
              }Method:
    public String decrypt(String item)throws Exception{
              FileReader fileReader = new FileReader("C:\\Documents and Settings\\mike\\Desktop\\key");
              BufferedReader reader = new BufferedReader(fileReader);
              String line="";
              String actualKey = null;
              String[] parts;
              Hashtable<String, String> keyLine = new Hashtable<String, String>();
              int rowCount =0;
              while((line = reader.readLine())!= null){
                   //System.out.println(line);
                   keyLine.put("key"+rowCount, line);
                   rowCount++;
              for(int i =0;i<keyLine.size();i++){
                   if(i==1){
                        parts = keyLine.get("key"+i).split("=");
                        actualKey = parts[1];
              //System.out.println("key:"+actualKey);
              Cipher cipher = Cipher.getInstance("Blowfish/CBC/NoPadding");
              byte[] keyBytes = actualKey.getBytes("UTF8");
              byte[] incomingBytes = item.getBytes("UTF8");
              Key myKey = new SecretKeySpec(keyBytes, "Blowfish");
              String keyAlg = myKey.getAlgorithm();
              System.out.println("Algorithm:"+keyAlg);
              String keyFormat = myKey.getFormat();
              System.out.println(keyFormat);
              AlgorithmParameterSpec iv = new IvParameterSpec(new byte[8]); // Create an IV of all zeros.
              cipher.init(Cipher.DECRYPT_MODE, myKey,iv);
              BASE64Encoder encoder = new BASE64Encoder();
              byte[] result = cipher.doFinal(incomingBytes);
              String finalResult = encoder.encode(result);
              return finalResult;
         }Edited by: ink86 on Jan 18, 2008 11:46 AM
    Edited by: ink86 on Jan 18, 2008 11:50 AM

Maybe you are looking for

  • Display problem after RAM Upgrade to MS6712

    Hi there, after a RAM upgrade (512mb to 3GB) my PC has developed a display problem. The graphics are slow / rippled and video playback is very poor. In device manager no "display adapters" are present and there is also an error mesage referring to th

  • How to configure for a remote TM backup?

    Hi, I have TM working in my home office but there are times that I have to spend extended periods away, I would like to know how I can configure my equipment and network to allow me to access the TM backup when not actually on my home LAN. Ben

  • Autosaving to drafts folder

    Hi all, not sure if this should be in this forum or workspace but i was just wondering if there was a feature to automatically save a form periodically into the drafts folder (to avoid losing work if the session times out, or power loss, etc). I'm ho

  • Migrating to new Mac Book Air using time machine and seems stuck?

    I am transferring my data my  5 year old Mac Book Pro to new Mac Book Air via Time Machine because other methods were not working due to technology out of date incompatibility and my old computer is on its last legs here.  Need to get moving on this.

  • Error FRM-40012 Form was created by a new version of Oracle Forms.

    Hi, I install my db, AS and Developer Suite in the same machine. When I run the forms by Developer, it keep complaining report server unaccessable. Someone told me to run it by AS. When I try, the error FRM-40012 prompts out. I check the version of F