繁体   English   中英

InvalidKeyException加密 - 解密文件 - Java / Android

[英]InvalidKeyException Encrypting-Decrypting a file - Java / Android

我正在使用以下示例:

http://compscipleslab.wordpress.com/category/java/

但我得到一个异常,当我记录异常时,它出现在我的logcat中:声明:InvalidKeyException

我不确定我做错了什么。 我还没有真正修改教程中的方法(也许这就是问题),所以我不确定为什么我会收到这个错误。

资源:

   public class FileChooser extends ListActivity {

    private File currentDir;
    private File moveToDir;
    private FileArrayAdapter adapter;
    public static String TAG = "DEBUG THIS:";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        currentDir = new File("/sdcard/");
        fill(currentDir);
        registerForContextMenu(getListView());
        // get the attachment's filename
        SharedPreferences preferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        String attachmentFileName = preferences.getString("fileName", "");

        // save the attachment
        try {
            InputStream attachment = getContentResolver().openInputStream(
                    getIntent().getData());

            File savedFile = new File(Environment.getExternalStorageDirectory()
                    .getAbsolutePath(), attachmentFileName);
            FileOutputStream f = new FileOutputStream(savedFile);
            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = attachment.read(buffer)) > 0) {
                f.write(buffer);
            }
            f.close();
        } catch (Exception e) {
        }
    }

    // File Manager Source to view SD Card or Internal Storage Contents
    private void fill(File f) {
        File[] dirs = f.listFiles();
        this.setTitle("Current Dir: " + f.getName());
        List<Item> dir = new ArrayList<Item>();
        List<Item> fls = new ArrayList<Item>();
        try {
            for (File ff : dirs) {
                Date lastModDate = new Date(ff.lastModified());
                DateFormat formater = DateFormat.getDateTimeInstance();
                String date_modify = formater.format(lastModDate);
                if (ff.isDirectory()) {

                    File[] fbuf = ff.listFiles();
                    int buf = 0;
                    if (fbuf != null) {
                        buf = fbuf.length;
                    } else
                        buf = 0;
                    String num_item = String.valueOf(buf);
                    if (buf == 0)
                        num_item = num_item + " item";
                    else
                        num_item = num_item + " items";

                    // String formated = lastModDate.toString();
                    dir.add(new Item(ff.getName(), num_item, date_modify, ff
                            .getAbsolutePath(), "directory_icon"));
                } else {

                    fls.add(new Item(ff.getName(), ff.length() + " Byte",
                            date_modify, ff.getAbsolutePath(), "file_icon"));
                }
            }
        } catch (Exception e) {

        }
        Collections.sort(dir);
        Collections.sort(fls);
        dir.addAll(fls);
        if (!f.getName().equalsIgnoreCase("sdcard"))
            dir.add(0, new Item("..", "Parent Directory", "", f.getParent(),
                    "directory_up"));
        adapter = new FileArrayAdapter(FileChooser.this, R.layout.file_view,
                dir);
        this.setListAdapter(adapter);
    }

    // onClick listener to move back one directory
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
        Item o = adapter.getItem(position);
        if (o.getImage().equalsIgnoreCase("directory_icon")
                || o.getImage().equalsIgnoreCase("directory_up")) {
            currentDir = new File(o.getPath());
            fill(currentDir);
        } else {
            onFileClick(o);
        }
    }

    // open file onClick
    private void onFileClick(Item o) {

        Intent intent = new Intent();
        intent.putExtra("GetPath", currentDir.toString());
        intent.putExtra("GetFileName", o.getName());
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("Context Menu");
        menu.add(0, v.getId(), 0, "Copy");
        menu.add(0, v.getId(), 0, "Paste");
        menu.add(0, v.getId(), 0, "Delete");
        menu.add(0, v.getId(), 0, "Encrypt");
        menu.add(0, v.getId(), 0, "Decrypt");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (item.getTitle() == "Copy") {
            function1(item.getItemId());
        }
        if (item.getTitle() == "Paste") {
            function2(item.getItemId());
        }
        if (item.getTitle() == "Delete") {
            function3(item.getItemId());
        }
        if (item.getTitle() == "Encrypt") {
            function4(item.getItemId());
        }
        if (item.getTitle() == "Decrypt") {
            function5(item.getItemId());
        } else {
        }
        return false;

    }

    public void function1(int id) {
        Toast.makeText(this, "Copy", Toast.LENGTH_SHORT).show();

        try {

            File sd = Environment.getExternalStorageDirectory();
            currentDir = new File(sd.getAbsolutePath());
            moveToDir = new File(sd.getAbsolutePath());
            copyDirectoryOneLocationToAnotherLocation(currentDir, currentDir);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void function2(int id) {

        Toast.makeText(this, "Paste", Toast.LENGTH_SHORT).show();
    }

    public void function3(int id) {
        Toast.makeText(this, "Delete", Toast.LENGTH_SHORT).show();
        DeleteRecursive(currentDir);
    }

    public void function4(int id) {
        Toast.makeText(this, "Encrypt", Toast.LENGTH_SHORT).show();
        //encrypt(null, null, null);
        // encrypt(String PlaintextFile, String Key, String CiphertextFile);
          encrypt("D:\\plaintext.txt", "testkey", "D:\\ciphertext.txt");
    }

    public void function5(int id) {
        Toast.makeText(this, "Decrypt", Toast.LENGTH_SHORT).show();
        decrypt(null, null, null);
        // decrypt(String PlaintextFile, String Key, String CiphertextFile);

    }

    private void DeleteRecursive(File fileOrDirectory) {

        if (fileOrDirectory.isDirectory()) {
            File[] children = fileOrDirectory.listFiles();
            if (null != children) {
                for (File child : children)
                    DeleteRecursive(child);
            }
        }

        fileOrDirectory.delete();

    }

    public static void copyDirectoryOneLocationToAnotherLocation(
            File sourceLocation, File targetLocation) throws IOException {

        if (sourceLocation.isDirectory()) {
            if (!targetLocation.exists()) {
                targetLocation.mkdir();
            }

            String[] children = sourceLocation.list();
            for (int i = 0; i < sourceLocation.listFiles().length; i++) {

                copyDirectoryOneLocationToAnotherLocation(new File(
                        sourceLocation, children[i]), new File(targetLocation,
                        children[i]));
            }
        } else {

            InputStream in = new FileInputStream(Environment
                    .getExternalStorageDirectory().getPath());

            OutputStream out = new FileOutputStream(Environment
                    .getExternalStorageDirectory().getPath());
            Log.d("TEST", "source: " + in);
            Log.d("TEST", "target: " + out);

            // Copy the bits from instream to outstream
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        }

    }

    public static void encrypt(String PlaintextFile, String Key,
            String CiphertextFile) {
        try {
            byte[] KeyData = Key.getBytes();
            SecretKeySpec KS = new SecretKeySpec(KeyData, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, KS);
            FileInputStream fis = new FileInputStream(PlaintextFile);
            CipherInputStream cis = new CipherInputStream(fis, cipher);
            FileOutputStream fos = new FileOutputStream(CiphertextFile);
            byte[] b = new byte[1024];
            int i = cis.read(b);
            while (i != -1) {
                fos.write(b, 0, i);
                i = cis.read(b);
            }
            fos.flush();
            fos.close();
            fis.close();
            cis.close();
            System.out.println("Encryption Successfull !!!");

        } catch (NoSuchAlgorithmException exception) {
            // do something.

            Thread.currentThread().getStackTrace();
        } catch (NoSuchPaddingException exception) {
            // do something (else?).
            Thread.currentThread().getStackTrace();
        } catch (InvalidKeyException exception) {
            // do something.
            Thread.currentThread().getStackTrace();
        } catch (IOException exception) {
            // do something (else?).
            Thread.currentThread().getStackTrace();

        }

    }

    public static void decrypt(String CiphertextFile, String Key,
            String DecipheredFile) {
        try {
            byte[] KeyData = Key.getBytes();
            SecretKeySpec KS = new SecretKeySpec(KeyData, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, KS);
            FileInputStream fis = new FileInputStream(CiphertextFile);
            FileOutputStream fos = new FileOutputStream(DecipheredFile);
            CipherOutputStream cos = new CipherOutputStream(fos, cipher);
            byte[] b = new byte[1024];
            int i = fis.read(b);
            while (i != -1) {
                cos.write(b, 0, i);
                i = fis.read(b);
            }
            fos.flush();
            fos.close();
            fis.close();
            cos.flush();
            cos.close();
            System.out.println("Decryption Successfull !!!");

        } catch (NoSuchAlgorithmException exception) {
            // do something.

            Thread.currentThread().getStackTrace();
        } catch (NoSuchPaddingException exception) {
            // do something (else?).
            Thread.currentThread().getStackTrace();
        } catch (InvalidKeyException exception) {
            // do something.
            Thread.currentThread().getStackTrace();
        } catch (IOException exception) {
            // do something (else?).
            Thread.currentThread().getStackTrace();

        }

    }
     public static void main(String[] args) {
            encrypt("D:\\plaintext.txt", "testkey", "D:\\ciphertext.txt");
            decrypt("D:\\ciphertext.txt", "testkey", "D:\\originaltext.txt");
        }
}

logcat的:

01-14 17:53:07.904: I/SurfaceTextureClient(9545): [STC::queueBuffer] (this:0x5f1c6d58) fps:6.11, dur:2780.41, max:2503.10, min:13.29
01-14 17:53:07.905: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:07.905: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:07.958: V/Provider/Settings(9545): invalidate [system]: current 6 != cached 0
01-14 17:53:07.963: V/Provider/Settings(9545): from db cache, name = sound_effects_enabled , value = 0
01-14 17:53:07.966: D/skia(9545): Flag is not 10
01-14 17:53:07.976: W/System.err(9545): java.security.InvalidKeyException: Key length not 128/192/256 bits.
01-14 17:53:07.983: W/System.err(9545):     at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineInit(BaseBlockCipher.java:578)
01-14 17:53:07.983: W/System.err(9545):     at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineInit(BaseBlockCipher.java:625)
01-14 17:53:07.983: W/System.err(9545):     at javax.crypto.Cipher.init(Cipher.java:519)
01-14 17:53:07.983: W/System.err(9545):     at javax.crypto.Cipher.init(Cipher.java:479)
01-14 17:53:07.983: W/System.err(9545):     at com.idg.voiscphone.FileChooser.encrypt(FileChooser.java:276)
01-14 17:53:07.984: W/System.err(9545):     at com.idg.voiscphone.FileChooser.function4(FileChooser.java:209)
01-14 17:53:07.984: W/System.err(9545):     at com.idg.voiscphone.FileChooser.onContextItemSelected(FileChooser.java:169)
01-14 17:53:07.984: W/System.err(9545):     at android.app.Activity.onMenuItemSelected(Activity.java:2597)
01-14 17:53:07.984: W/System.err(9545):     at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:3663)
01-14 17:53:07.984: W/System.err(9545):     at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
01-14 17:53:07.985: W/System.err(9545):     at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
01-14 17:53:07.985: W/System.err(9545):     at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
01-14 17:53:07.985: W/System.err(9545):     at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:167)
01-14 17:53:07.985: W/System.err(9545):     at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:963)
01-14 17:53:07.985: W/System.err(9545):     at android.widget.AdapterView.performItemClick(AdapterView.java:298)
01-14 17:53:07.985: W/System.err(9545):     at android.widget.AbsListView.performItemClick(AbsListView.java:1128)
01-14 17:53:07.986: W/System.err(9545):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:2812)
01-14 17:53:07.986: W/System.err(9545):     at android.widget.AbsListView$1.run(AbsListView.java:3571)
01-14 17:53:07.986: W/System.err(9545):     at android.os.Handler.handleCallback(Handler.java:725)
01-14 17:53:07.986: W/System.err(9545):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-14 17:53:07.986: W/System.err(9545):     at android.os.Looper.loop(Looper.java:153)
01-14 17:53:07.987: W/System.err(9545):     at android.app.ActivityThread.main(ActivityThread.java:5297)
01-14 17:53:07.987: W/System.err(9545):     at java.lang.reflect.Method.invokeNative(Native Method)
01-14 17:53:07.987: W/System.err(9545):     at java.lang.reflect.Method.invoke(Method.java:511)
01-14 17:53:07.987: W/System.err(9545):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
01-14 17:53:07.988: W/System.err(9545):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
01-14 17:53:07.988: W/System.err(9545):     at dalvik.system.NativeStart.main(Native Method)
01-14 17:53:07.989: D/OpenGLRenderer(9545): Flushing caches (mode 0)
01-14 17:53:08.013: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.013: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.028: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.028: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.052: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.053: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.054: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.076: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.076: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.076: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.078: V/InputMethodManager(9545): onWindowFocus: android.widget.ListView{4206e2c0 VFED.VCL .F...... 0,0-720,1126 #102000a android:id/list} softInputMode=16 first=false flags=#1810100
01-14 17:53:08.091: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.091: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.091: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.092: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.092: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.092: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.097: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.102: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0

您的代码的一个问题是您指定的Cipher算法和SecretKeySpec实例不一样。 你正在混合2种不同的算法。

与参考示例中一样,对两个实例保持相同:

线条不正确:

SecretKeySpec KS = new SecretKeySpec(KeyData, "Blowfish");
Cipher cipher = Cipher.getInstance("AES");

你可以考虑在这里阅读AES vs Blowfish。

编辑:

如上所述,严格的AES将在整个解决方案中使用。 因此,您设置的密钥不是有效的AES密钥 - AES密钥是128,192或256位(从您的例外中可以看出)。 这意味着您当前的密钥应该是testkey或32字节(尽管testkey是7)。

考虑以下:

  1. 按照参考并将算法更改为Blowfish,它将接受您的密钥
  2. 尝试将密钥更改为16字节(例如: ThisSecurityKey1 )。 您可以考虑使用字符编码(UTF-8,UTF-16),但由于您使用的是纯文本,因此它应该可以使用。
  3. Lookup KeyGenerator类,用于生成对称密钥。

此类提供秘密(对称)密钥生成器的功能。

另外,请尝试参考AES的更好的加密示例 - 您选择的引用充满了不符合的Java编码标准。

您的代码的另一个问题是:

while ((len1 = attachment.read(buffer)) > 0) {
    f.write(buffer);
}

这将在目标的末尾写入垃圾,除非大小是缓冲区大小的倍数。 它应该是:

while ((len1 = attachment.read(buffer)) > 0) {
    f.write(buffer, 0, len1);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM