0

In my application is using sensitive data. I have my initial database inside the assest folder. The asset folder contain encrypted database when I copy database to installation location i need to decrypt. When decrypt the database I got following error

     10-17 16:30:25.878: W/System.err(15231): java.io.IOException: pad block corrupted
10-17 16:30:25.889: W/System.err(15231):    at javax.crypto.CipherInputStream.read(CipherInputStream.java:102)
10-17 16:30:25.889: W/System.err(15231):    at javax.crypto.CipherInputStream.read(CipherInputStream.java:134)
10-17 16:30:25.898: W/System.err(15231):    at java.io.InputStream.read(InputStream.java:163)
10-17 16:30:25.898: W/System.err(15231):    at xont.virtusel.v4.controller.syn.DBEncript.ReadEncryptedFile(DBEncript.java:178)
10-17 16:30:25.898: W/System.err(15231):    at xont.virtusel.v4.controller.syn.DBEncript.callRead(DBEncript.java:247)
10-17 16:30:25.898: W/System.err(15231):    at xont.virtusel.v4.db.DataBaseHelper.extarctDataBase(DataBaseHelper.java:116)
10-17 16:30:25.898: W/System.err(15231):    at xont.virtusel.v4.db.DataBaseHelper.copyDataBase(DataBaseHelper.java:104)
10-17 16:30:25.908: W/System.err(15231):    at xont.virtusel.v4.db.DataBaseHelper.createDataBase(DataBaseHelper.java:59)
10-17 16:30:25.908: W/System.err(15231):    at xont.virtusel.v4.controller.syn.DatabaseSetupActivity$1.onItemClick(DatabaseSetupActivity.java:43)
10-17 16:30:25.908: W/System.err(15231):    at android.widget.AdapterView.performItemClick(AdapterView.java:292)
10-17 16:30:25.908: W/System.err(15231):    at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
10-17 16:30:25.908: W/System.err(15231):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
10-17 16:30:25.908: W/System.err(15231):    at android.widget.AbsListView$1.run(AbsListView.java:3168)
10-17 16:30:25.908: W/System.err(15231):    at android.os.Handler.handleCallback(Handler.java:605)
10-17 16:30:25.908: W/System.err(15231):    at android.os.Handler.dispatchMessage(Handler.java:92)
10-17 16:30:25.919: W/System.err(15231):    at android.os.Looper.loop(Looper.java:137)
10-17 16:30:25.919: W/System.err(15231):    at android.app.ActivityThread.main(ActivityThread.java:4340)
10-17 16:30:25.919: W/System.err(15231):    at java.lang.reflect.Method.invokeNative(Native Method)
10-17 16:30:25.928: W/System.err(15231):    at java.lang.reflect.Method.invoke(Method.java:511)
10-17 16:30:25.928: W/System.err(15231):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-17 16:30:25.928: W/System.err(15231):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-17 16:30:25.928: W/System.err(15231):    at dalvik.system.NativeStart.main(Native Method)

My code is same like URL

public class DBEncript {

    String mPassword = null;
    public final static int SALT_LEN = 8;
    byte [] mInitVec = null;
    byte [] mSalt = null;
    Cipher mEcipher = null;
    Cipher mDecipher = null;
    private final int KEYLEN_BITS = 128; // see notes below where this is used.
    private final int ITERATIONS = 65536;
    private final int MAX_FILE_BUF = 1024;

    public DBEncript (String password){
        mPassword = password;
    }

    public byte [] getSalt (){
        return (mSalt);
    }

    public byte [] getInitVec (){
        return (mInitVec);
    }

    private void Db (String msg){
        System.out.println ("** DBEncript ** " + msg);
    }

    /**
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws NoSuchPaddingException
     * @throws InvalidParameterSpecException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws UnsupportedEncodingException
     * @throws InvalidKeyException
     */
    public void setupEncrypt () throws NoSuchAlgorithmException, 
                                                           InvalidKeySpecException, 
                                                           NoSuchPaddingException, 
                                                           InvalidParameterSpecException, 
                                                           IllegalBlockSizeException, 
                                                           BadPaddingException, 
                                                           UnsupportedEncodingException, 
                                                           InvalidKeyException {
        SecretKeyFactory factory = null;
        SecretKey tmp = null;
        mSalt = new byte [SALT_LEN];
        SecureRandom rnd = new SecureRandom ();
        rnd.nextBytes (mSalt);
        Db ("generated salt :" + Hex.encodeHex (mSalt));

        factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

        KeySpec spec = new PBEKeySpec (mPassword.toCharArray (), mSalt, ITERATIONS, KEYLEN_BITS);
        tmp = factory.generateSecret (spec);
        SecretKey secret = new SecretKeySpec (tmp.getEncoded(), "AES");

        mEcipher = Cipher.getInstance ("AES/CBC/PKCS5Padding");
        mEcipher.init (Cipher.ENCRYPT_MODE, secret);
        AlgorithmParameters params = mEcipher.getParameters ();

        mInitVec = params.getParameterSpec (IvParameterSpec.class).getIV();

        Db ("mInitVec is :" + Hex.encodeHex (mInitVec));
    }

    public void setupDecrypt (String initvec, String salt) throws NoSuchAlgorithmException,InvalidKeySpecException,NoSuchPaddingException, 
                                                                                       InvalidKeyException,InvalidAlgorithmParameterException,DecoderException{
        SecretKeyFactory factory = null;
        SecretKey tmp = null;
        SecretKey secret = null;

        mSalt = Hex.decodeHex (salt.toCharArray ());
        Db ("got salt " + Hex.encodeHex (mSalt));

        mInitVec = Hex.decodeHex (initvec.toCharArray ());
        Db ("got initvector :" + Hex.encodeHex (mInitVec));


        factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(mPassword.toCharArray (), mSalt, ITERATIONS, KEYLEN_BITS);

        tmp = factory.generateSecret(spec);
        secret = new SecretKeySpec(tmp.getEncoded(), "AES");

        mDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        mDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(mInitVec));
    }


    public void WriteEncryptedFile (File input, File output) throws IOException, IllegalBlockSizeException,BadPaddingException{
        FileInputStream fin;
        FileOutputStream fout;
        long totalread = 0;
        int nread = 0;
        byte [] inbuf = new byte [MAX_FILE_BUF];

        fout = new FileOutputStream (output);
        fin = new FileInputStream (input);

        while ((nread = fin.read (inbuf)) > 0 )
        {
           // Db ("read " + nread + " bytes");
            totalread += nread;
            byte [] trimbuf = new byte [nread];
            for (int i = 0; i < nread; i++)
                trimbuf[i] = inbuf[i];

            byte [] tmp = mEcipher.update (trimbuf);

            if (tmp != null)
                fout.write (tmp);
        }

        byte [] finalbuf = mEcipher.doFinal ();
        if (finalbuf != null)
            fout.write (finalbuf);

        fout.flush();
        fin.close();
        fout.close();
        fout.close ();

        Db ("wrote " + totalread + " encrypted bytes");
    }



    public void ReadEncryptedFile (File input, File output) throws IllegalBlockSizeException,BadPaddingException, IOException{

        FileInputStream fin; 
        FileOutputStream fout;
        CipherInputStream cin;
        long totalread = 0;
        int nread = 0;
        byte [] inbuf = new byte [MAX_FILE_BUF];

        fout = new FileOutputStream (output);
        fin = new FileInputStream (input);

        cin = new CipherInputStream (fin, mDecipher);
        while ((nread = cin.read (inbuf)) > 0 )
        {
            //Db ("read " + nread + " bytes");
            totalread += nread;

            byte [] trimbuf = new byte [nread];
            for (int i = 0; i < nread; i++)
                trimbuf[i] = inbuf[i];

            fout.write (trimbuf);
        }

        fout.flush();
        cin.close();
        fin.close ();       
        fout.close();   

    }


    public void callRead(File input, File output) {
        String iv = null;
        String salt = null;
        DBEncript en = new DBEncript ("123");
        try{
            en.setupEncrypt ();
            iv = new String(Hex.encodeHex(en.getInitVec())).toUpperCase ();
            salt = new String(Hex.encodeHex(en.getSalt())).toUpperCase ();
          }catch (InvalidKeyException e){
            e.printStackTrace();
          }catch (NoSuchAlgorithmException e){
            e.printStackTrace();
          }catch (InvalidKeySpecException e){
            e.printStackTrace();
          }catch (NoSuchPaddingException e){
            e.printStackTrace();
          }catch (InvalidParameterSpecException e){
            e.printStackTrace();
          }catch (IllegalBlockSizeException e){
            e.printStackTrace();
          }catch (BadPaddingException e){
            e.printStackTrace();
          }catch (UnsupportedEncodingException e){
            e.printStackTrace();
          }


          /*
           * decrypt file
           */
          DBEncript dc = new DBEncript ("123");
          try{
            dc.setupDecrypt (iv, salt);
          }catch (InvalidKeyException e){
            e.printStackTrace();
          }catch (NoSuchAlgorithmException e){
            e.printStackTrace();
          }catch (InvalidKeySpecException e){
            e.printStackTrace();
          }catch (NoSuchPaddingException e){
            e.printStackTrace();
          }catch (InvalidAlgorithmParameterException e){
            e.printStackTrace();
          }catch (DecoderException e){
            e.printStackTrace();
          }


          try{
              dc.ReadEncryptedFile (input, output);
              System.out.println ("decryption finished to " + output.getName ());
            }catch (IllegalBlockSizeException e){
              e.printStackTrace();
            }catch (BadPaddingException e){
              e.printStackTrace();
            }catch (IOException e){
              e.printStackTrace();
            }
    }



}

EDIT This is my calling place:

  private void extarctDataBase() throws IOException {
    // Open your local db as the input stream
    String outFileName = DB_PATH + DB_NAME;
    String extFileName = DB_PATH + SEC_NAME;
    DBEncript dc = new DBEncript ("xont@123");
    File eoutput = new File (extFileName);
    File doutput = new File (outFileName);
    System.out.println("==START===");
    dc.callRead(eoutput, doutput);
    System.out.println ("decryption finished to " + doutput.getName ());

}
4
  • Where in method "ReadEncryptedFile" does it crash? And show some code how you use this method from another class. Commented Oct 17, 2013 at 11:22
  • I have added calling place code. Not crashed ` pad block corrupted` Commented Oct 17, 2013 at 11:25
  • Which code causes the crash? see "DBEncript.java:178" Commented Oct 17, 2013 at 11:29
  • I have added line number blow comment Commented Oct 17, 2013 at 11:38

1 Answer 1

1

Change this

mDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

to

mDecipher = Cipher.getInstance("AES/CFB8/NoPadding");

And you should do the same for mEcipher.

Sign up to request clarification or add additional context in comments.

3 Comments

Error is ReadEncryptedFile() when its start while loop. it throw error. ` while ((nread = cin.read (inbuf)) > 0 ) { //Db ("read " + nread + " bytes"); totalread += nread; byte [] trimbuf = new byte [nread]; for (int i = 0; i < nread; i++) trimbuf[i] = inbuf[i]; fout.write (trimbuf); }` this line
This say like this 10-17 17:17:50.266: E/SqliteDatabaseCpp(10831): CREATE TABLE android_metadata failed 10-17 17:17:50.266: E/DefaultDatabaseErrorHandler(10831): Corruption reported by sqlite on database: /data/data/xont.virtusel.v4.controller/databases/VirtuselVentura.db 10-17 17:17:50.267: E/DefaultDatabaseErrorHandler(10831): deleting the database file: /data/data/xont.virtusel.v4.controller/databases/VirtuselVentura.db
Why its deleting file. Android_metadata is available in encrypted database

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.