Results 1 to 10 of 10
Like Tree1Likes
  • 1 Post By sabre150

Thread: Encryption Decryption using SHA256And256AES(bouncy castle)

  1. #1
    me.anchit is offline Member
    Join Date
    Jul 2011
    Posts
    26
    Rep Power
    0

    Unhappy Encryption Decryption using SHA256And256AES(bouncy castle)

    Hi,
    I m new to encryption/decryption. I have written a program using bouncy castle provider, but the decryption is not properly done. The file produced after decryption is not the correct one. Please help.

    the code

    Java Code:
    package pack;
    import java.io.*;
    import java.security.MessageDigest;
    import java.security.Provider;
    import java.security.Security;
    import java.security.spec.AlgorithmParameterSpec;
    import java.security.spec.KeySpec;
    import java.util.Arrays;
    
    import javax.crypto.*;
    import javax.crypto.spec.PBEKeySpec;
    import javax.crypto.spec.PBEParameterSpec;
    
    public class Operator
    {
        private final String algo="PBEWITHSHA256AND256BITAES-CBC-BC";
        
        public void encrypt(String src, String dest, String password)
        {
            try
            {
            	Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
                int buffersize=8*1024;
                File input=new File(src);
                File output=new File(dest);
                FileInputStream fis=new FileInputStream(input);
                FileOutputStream fos=new FileOutputStream(output);
                if(input.length()<buffersize)
                {
                    buffersize=(int)input.length();
                }
                byte buffer[]=new byte[buffersize];
                KeySpec ks=new PBEKeySpec(password.toCharArray());
                SecretKeyFactory skf=SecretKeyFactory.getInstance(algo);
                SecretKey key=skf.generateSecret(ks);
                MessageDigest md=MessageDigest.getInstance("SHA-256");
                md.update(password.getBytes());
                byte[] digest=md.digest();
                byte[] salt=new byte[16];
                System.arraycopy(digest, 0, salt, 0, 16);
                System.out.println(Arrays.toString(salt));
                File saltfile=new File("salt.txt");
                FileOutputStream fsalt=new FileOutputStream(saltfile);
                fsalt.write(salt);
                fsalt.close();
                AlgorithmParameterSpec aps=new PBEParameterSpec(salt, 20);
                Cipher cipher=Cipher.getInstance(algo);
                cipher.init(Cipher.ENCRYPT_MODE, key, aps);
                int reader=0;
                CipherInputStream cis=new CipherInputStream(fis, cipher);
                while((reader=cis.read(buffer))!=-1)
                {
                    //System.out.println(reader);
                    fos.write(buffer, 0, reader);
                    fos.flush();
                }
                fos.close();
                cis.close();
                fis.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
        
        public void decrypt(String src, String dest, String password)
        {
            try
            {
            	Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
                int buffersize=8*1024;
                File input=new File(src);
                File output=new File(dest);
                FileInputStream fis=new FileInputStream(input);
                FileOutputStream fos=new FileOutputStream(output);
                if(input.length()<buffersize)
                {
                    buffersize=(int)input.length();
                }
                byte buffer[]=new byte[buffersize];
                KeySpec ks=new PBEKeySpec(password.toCharArray());
                SecretKeyFactory skf=SecretKeyFactory.getInstance(algo);
                SecretKey key=skf.generateSecret(ks);
                byte[] salt=new byte[16];
                File saltfile=new File("salt.txt");
                FileInputStream fsalt=new FileInputStream(saltfile);
                DataInputStream dsalt=new DataInputStream(fsalt);
                dsalt.read(salt);
                dsalt.close();
                fsalt.close();
                System.out.println(Arrays.toString(salt));
                AlgorithmParameterSpec aps=new PBEParameterSpec(salt, 20);
                Cipher cipher=Cipher.getInstance(algo);
                cipher.init(Cipher.DECRYPT_MODE, key, aps);
                int reader=0;
                CipherOutputStream cos=new CipherOutputStream(fos, cipher);
                while((reader=fis.read(buffer))!=-1)
                {
                    //System.out.println(reader);
                    cos.write(buffer, 0, reader);
                    cos.flush();
                }
                cos.close();
                fos.close();
                fis.close();
            }
            catch(Exception e)
            {
                System.out.println(e.toString());
            }
        }
    Thanks.

  2. #2
    sabre150 is offline Member
    Join Date
    Jul 2012
    Location
    Earth
    Posts
    75
    Rep Power
    0

    Default Re: Encryption Decryption using SHA256And256AES(bouncy castle)

    I have tested your code and the decrypted file is exactly the same as the unencrypted file. Having said that there is at least one minor flaw and several 'issues'.

    The minor flaw - when your read the salt you should use readFully() and not just read(). For this small file (16 bytes) you will probably get away with this forever BUT read() does not guarantee to read all the bytes you ask for and returns the number of bytes actually read.

    The 'issues' -

    1) Since the salt is generated from the sha-256 of the password you don't need to save it to a file. Just use
    Java Code:
                MessageDigest md = MessageDigest.getInstance("SHA-256");
                md.update(password.getBytes());
                byte[] salt = Arrays.copyOf(md.digest(), 16);
    in both encryption and decryption.

    2) Since any exception thrown in either the encrypt() or decrypt() method is probably fatal you should not continue. In your position I would wrap the exception in my own exception and throw that.

    3) The Bouncy Castle provider only needs to be added once and this is best done in a static initialiser in the class
    Java Code:
    static {
               Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }
    4) There is no need to adjust the buffer size as a function of the file size. Just leave it at 8*1024.

    5) In a chain of input or output streams you only need to close() the outer one.

    6) There is no need to use flush() in this context. The contract for close() guarantees a flush() prior to the actual close().

    Finally - I never use CipherInputStream or CipherOutputSteam since they swallow any IO exceptions thrown by the wrapped streams. I have written my own version that do not swallow exceptions but you can just use the "read a block, encrypt/decrypt the block, write the encypted/decrypted block" approach.
    Last edited by sabre150; 11-12-2012 at 12:50 PM.
    me.anchit likes this.

  3. #3
    me.anchit is offline Member
    Join Date
    Jul 2011
    Posts
    26
    Rep Power
    0

    Default Re: Encryption Decryption using SHA256And256AES(bouncy castle)

    Thank You very much sabre150. My problem is solved, I learned a lot and understood several of my mistakes.
    I did not want to use CipherInputStream and CipherOutputStream but without that I was getting a 'BadPaddingException:Given final block not properly padded', when using it with 'MD5WithDES' (JCE).
    Besides encryption using CipherInputStream is slow as it reads only 512 bytes block.
    I'll try SHA256And256AES(bouncy castle) without CipherInputStream and CipherOutputStream and post the result if I need further help.
    Regards.

  4. #4
    me.anchit is offline Member
    Join Date
    Jul 2011
    Posts
    26
    Rep Power
    0

    Default Re: Encryption Decryption using SHA256And256AES(bouncy castle)

    "The result after removing CipherInput/OutputStream."
    What is my mistake in the code..?
    In the following code, decryption does not take place.

    Java Code:
        public void encrypt(String src, String dest, String password)
        {
            try
            {
                int buffersize=8*1024;
                File input=new File(src);
                File output=new File(dest);
                FileInputStream fis=new FileInputStream(input);
                FileOutputStream fos=new FileOutputStream(output);
                byte buffer[]=new byte[buffersize];
                KeySpec ks=new PBEKeySpec(password.toCharArray());
                SecretKeyFactory skf=SecretKeyFactory.getInstance(algo);
                SecretKey key=skf.generateSecret(ks);
                MessageDigest md=MessageDigest.getInstance("SHA-256");
                md.update(password.getBytes());
                byte[] digest=md.digest();
                byte[] salt=Arrays.copyOf(digest, 16);
                System.out.println(Arrays.toString(salt));
                AlgorithmParameterSpec aps=new PBEParameterSpec(salt, 20);
                Cipher cipher=Cipher.getInstance(algo);
                cipher.init(Cipher.ENCRYPT_MODE, key, aps);
                int reader=0;
                while((reader=fis.read(buffer))!=-1)
                {
                    //System.out.println(reader);
                    byte[] out=cipher.doFinal(buffer);
                    fos.write(out, 0, reader);
                }
                fos.close();
                fis.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
        
        public void decrypt(String src, String dest, String password)
        {
            try
            {
                int buffersize=8*1024;
                File input=new File(src);
                File output=new File(dest);
                FileInputStream fis=new FileInputStream(input);
                FileOutputStream fos=new FileOutputStream(output);
                byte buffer[]=new byte[buffersize];
                KeySpec ks=new PBEKeySpec(password.toCharArray());
                SecretKeyFactory skf=SecretKeyFactory.getInstance(algo);
                SecretKey key=skf.generateSecret(ks);
                MessageDigest md=MessageDigest.getInstance("SHA-256");
                md.update(password.getBytes());
                byte[] digest=md.digest();
                byte[] salt=Arrays.copyOf(digest, 16);
                System.out.println(Arrays.toString(salt));
                AlgorithmParameterSpec aps=new PBEParameterSpec(salt, 20);
                Cipher cipher=Cipher.getInstance(algo);
                cipher.init(Cipher.DECRYPT_MODE, key, aps);
                int reader=0;
                while((reader=fis.read(buffer))!=-1)
                {
                    System.out.println(reader);
                    byte[] out=cipher.doFinal(buffer);
                    fos.write(out, 0, reader);
                }
                fos.close();
                fis.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    and the following exception is thrown.
    javax.crypto.BadPaddingException: pad block corrupted
    at org.bouncycastle.jce.provider.JCEBlockCipher.engin eDoFinal(Unknown Source)
    at javax.crypto.Cipher.doFinal(Cipher.java:2086)
    at pack.Operator.decrypt(Operator.java:82)
    at pack.EncDec.main(EncDec.java:9)

    Please help me with this one.
    Thank You.

  5. #5
    sabre150 is offline Member
    Join Date
    Jul 2012
    Location
    Earth
    Posts
    75
    Rep Power
    0

    Default Re: Encryption Decryption using SHA256And256AES(bouncy castle)

    You only use doFinal() at the end !!!!!
    Java Code:
           while((reader=fis.read(buffer))!=-1)
            {
                byte[] out=cipher.doUpdate(buffer, 0, reader);
                fos.write(out, 0, reader);
            }
            fos.write(cipher.doFinal());

  6. #6
    me.anchit is offline Member
    Join Date
    Jul 2011
    Posts
    26
    Rep Power
    0

    Default Re: Encryption Decryption using SHA256And256AES(bouncy castle)

    I am still getting exception. First of all I think that it would be:
    Java Code:
    byte[] out=cipher.update(buffer, 0, reader)
    instead of "doUpdate(buffer, 0, reader)"

    The exception I get using your code in both encrypt and decrypt methods:
    java.lang.IndexOutOfBoundsException
    at java.io.FileOutputStream.writeBytes(Native Method)
    at java.io.FileOutputStream.write(FileOutputStream.ja va:318)
    at pack.Operator.encrypt(Operator.java:46)
    at pack.EncDec.main(EncDec.java:8)
    javax.crypto.IllegalBlockSizeException: last block incomplete in decryption
    at org.bouncycastle.jce.provider.JCEBlockCipher.engin eDoFinal(Unknown Source)
    at javax.crypto.Cipher.doFinal(Cipher.java:1969)
    at pack.Operator.decrypt(Operator.java:86)
    at pack.EncDec.main(EncDec.java:9)

    What could be the mistake..?

  7. #7
    sabre150 is offline Member
    Join Date
    Jul 2012
    Location
    Earth
    Posts
    75
    Rep Power
    0

    Default Re: Encryption Decryption using SHA256And256AES(bouncy castle)

    You are right about it being update() rather than doUpdate() - I was going from memory and at my age relying on memory it not a good idea.

    Sorry but without a view of your latest code I can't diagnose what the exceptions are due to.
    Last edited by sabre150; 11-13-2012 at 12:59 PM.

  8. #8
    me.anchit is offline Member
    Join Date
    Jul 2011
    Posts
    26
    Rep Power
    0

    Default Re: Encryption Decryption using SHA256And256AES(bouncy castle)

    Here is the code :
    Java Code:
    public void encrypt(String src, String dest, String password)
        {
            try
            {
                int buffersize=8*1024;
                File input=new File(src);
                File output=new File(dest);
                FileInputStream fis=new FileInputStream(input);
                FileOutputStream fos=new FileOutputStream(output);
                byte buffer[]=new byte[buffersize];
                KeySpec ks=new PBEKeySpec(password.toCharArray());
                SecretKeyFactory skf=SecretKeyFactory.getInstance(algo);
                SecretKey key=skf.generateSecret(ks);
                MessageDigest md=MessageDigest.getInstance("SHA-256");
                md.update(password.getBytes());
                byte[] digest=md.digest();
                byte[] salt=Arrays.copyOf(digest, 16);
                AlgorithmParameterSpec aps=new PBEParameterSpec(salt, 20);
                Cipher cipher=Cipher.getInstance(algo);
                cipher.init(Cipher.ENCRYPT_MODE, key, aps);
                int reader=0;
                while((reader=fis.read(buffer))!=-1)
                {
                    byte[] out=cipher.update(buffer, 0, reader);
                    fos.write(out, 0, reader);
                }
                fos.write(cipher.doFinal());
                fos.close();
                fis.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
        
        public void decrypt(String src, String dest, String password)
        {
            try
            {
                int buffersize=8*1024;
                File input=new File(src);
                File output=new File(dest);
                FileInputStream fis=new FileInputStream(input);
                FileOutputStream fos=new FileOutputStream(output);
                byte buffer[]=new byte[buffersize];
                KeySpec ks=new PBEKeySpec(password.toCharArray());
                SecretKeyFactory skf=SecretKeyFactory.getInstance(algo);
                SecretKey key=skf.generateSecret(ks);
                MessageDigest md=MessageDigest.getInstance("SHA-256");
                md.update(password.getBytes());
                byte[] digest=md.digest();
                byte[] salt=Arrays.copyOf(digest, 16);
                AlgorithmParameterSpec aps=new PBEParameterSpec(salt, 20);
                Cipher cipher=Cipher.getInstance(algo);
                cipher.init(Cipher.DECRYPT_MODE, key, aps);
                int reader=0;
                while((reader=fis.read(buffer))!=-1)
                {
                    byte[] out=cipher.update(buffer, 0, reader);
                    fos.write(out, 0, reader);
                }
                fos.write(cipher.doFinal());
                fos.close();
                fis.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }

  9. #9
    sabre150 is offline Member
    Join Date
    Jul 2012
    Location
    Earth
    Posts
    75
    Rep Power
    0

    Default Re: Encryption Decryption using SHA256And256AES(bouncy castle)

    Looks like I slightly mislead you earlier though I would have thought that a bit of simple investigation on your part should have indicated the problem. Encryption using Java is BIG (you have only scratched the surface) and you need to be able to debug code on your own. I'm happy to help you with Java encryption and will provide code fragments but these are taken from memory and are meant to illustrate concepts for you to investigate and are not to be taken verbatim.

    Most of the information you needed to solve the problem is contained in the exception stack trace and a bit of thought would have provided the rest.
    Java Code:
    while((reader=fis.read(buffer))!=-1)
     {
         byte[] out=cipher.update(buffer, 0, reader);
         fos.write(out);
     }
     fos.write(cipher.doFinal());

  10. #10
    me.anchit is offline Member
    Join Date
    Jul 2011
    Posts
    26
    Rep Power
    0

    Default Re: Encryption Decryption using SHA256And256AES(bouncy castle)

    this solves my problem, thank you very much. I've learned a lot from you.
    Thank you once again.

Similar Threads

  1. Legion of the Bouncy Castle Java Cryptography API 1.47
    By java software in forum Java Software
    Replies: 0
    Last Post: 03-31-2012, 07:49 PM
  2. Bouncy Castle AES wrapper Key issue
    By idtyu in forum New To Java
    Replies: 1
    Last Post: 07-05-2011, 08:52 AM
  3. Legion of the Bouncy Castle Java Cryptography API 1.39
    By Java Tip in forum Java Software
    Replies: 0
    Last Post: 04-03-2008, 05:27 PM
  4. Legion of the Bouncy Castle Java Cryptography API 1.38
    By JavaBean in forum Java Software
    Replies: 0
    Last Post: 11-12-2007, 06:53 PM
  5. Replies: 0
    Last Post: 06-16-2007, 10:42 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •