【问题标题】:Cipher Output and Input Streams密码输出和输入流
【发布时间】:2013-05-04 14:01:21
【问题描述】:

我正在尝试在 Android 文件系统中存储一些加密数据。我收到了我不理解的错误和空文件。请帮忙。

代码:

private Cipher cipher;
private ArrayList<ConnectionProfile> connectionProfiles;

public void createCipher() throws Exception{
    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
}

public void saveProfiles() {
    try {
        if (cipher == null) {createCipher();}
        FileOutputStream fos = openFileOutput("connProfiles.bin", Context.MODE_PRIVATE);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        CipherOutputStream cos = new CipherOutputStream(bos, cipher);
        ObjectOutputStream oos = new ObjectOutputStream(cos);
        oos.writeObject(connectionProfiles);
        oos.flush();
        oos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void readProfiles() {
    try {
        if (cipher == null) {createCipher();}
        FileInputStream fis = openFileInput("connProfiles.bin");
        BufferedInputStream bis = new BufferedInputStream(fis);
        CipherInputStream cis = new CipherInputStream(bis, cipher);
        ObjectInputStream ois = new ObjectInputStream(cis);
        connectionProfiles = (ArrayList<ConnectionProfile>) ois.readObject();
        ois.close();
    } catch (Exception e) {
        e.printStackTrace();
        ;
    }
}

追溯:

05-09 23:24:39.628: W/System.err(837): java.lang.IllegalStateException
05-09 23:24:39.639: W/System.err(837):  at javax.crypto.Cipher.update(Cipher.java:884)
05-09 23:24:39.639: W/System.err(837):  at javax.crypto.CipherOutputStream.write(CipherOutputStream.java:95)
05-09 23:24:39.639: W/System.err(837):  at java.io.DataOutputStream.writeShort(DataOutputStream.java:192)
05-09 23:24:39.648: W/System.err(837):  at java.io.ObjectOutputStream.writeStreamHeader(ObjectOutputStream.java:1815)
05-09 23:24:39.648: W/System.err(837):  at java.io.ObjectOutputStream.<init>(ObjectOutputStream.java:279)
05-09 23:24:39.648: W/System.err(837):  at com.sajnasoft.down2home.MainActivity.saveProfiles(MainActivity.java:39)
05-09 23:24:39.648: W/System.err(837):  at com.sajnasoft.down2home.MainActivity$2.onClick(MainActivity.java:92)
05-09 23:24:39.658: W/System.err(837):  at android.view.View.performClick(View.java:4204)
05-09 23:24:39.658: W/System.err(837):  at android.view.View$PerformClick.run(View.java:17355)
05-09 23:24:39.658: W/System.err(837):  at android.os.Handler.handleCallback(Handler.java:725)
05-09 23:24:39.658: W/System.err(837):  at android.os.Handler.dispatchMessage(Handler.java:92)
05-09 23:24:39.658: W/System.err(837):  at android.os.Looper.loop(Looper.java:137)
05-09 23:24:39.668: W/System.err(837):  at android.app.ActivityThread.main(ActivityThread.java:5041)
05-09 23:24:39.668: W/System.err(837):  at java.lang.reflect.Method.invokeNative(Native Method)
05-09 23:24:39.668: W/System.err(837):  at java.lang.reflect.Method.invoke(Method.java:511)
05-09 23:24:39.678: W/System.err(837):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-09 23:24:39.678: W/System.err(837):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-09 23:24:39.678: W/System.err(837):  at dalvik.system.NativeStart.main(Native Method)
05-09 23:26:33.878: W/IInputConnectionWrapper(837): showStatusIcon on inactive InputConnection

更新:

所以现在我有

private Spinner spinner;
private SpinAdapter adapter;
private Cipher cipher;
private ArrayList<ConnectionProfile> connectionProfiles;
private KeyGenerator keygen;
private SecretKey key;

public void createCipher() throws Exception{
    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    keygen = KeyGenerator.getInstance("AES");
    key = keygen.generateKey();
}

public void saveProfiles() {
    try {
        if (cipher == null) {createCipher();}
        cipher.init(Cipher.ENCRYPT_MODE, key);
        FileOutputStream fos = openFileOutput("connProfiles.bin", Context.MODE_PRIVATE);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        CipherOutputStream cos = new CipherOutputStream(bos, cipher);
        ObjectOutputStream oos = new ObjectOutputStream(cos);
        oos.writeObject(connectionProfiles);
        oos.flush();
        oos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void readProfiles() {
    try {
        if (cipher == null) {createCipher();}
        cipher.init(Cipher.ENCRYPT_MODE, key);
        FileInputStream fis = openFileInput("connProfiles.bin");
        BufferedInputStream bis = new BufferedInputStream(fis);
        CipherInputStream cis = new CipherInputStream(bis, cipher);
        ObjectInputStream ois = new ObjectInputStream(cis);
        connectionProfiles = (ArrayList<ConnectionProfile>) ois.readObject();
        ois.close();
    } catch (Exception e) {
        e.printStackTrace();
        ;
    }
}

和:

05-11 22:20:40.658: W/System.err(1019): java.io.StreamCorruptedException
05-11 22:20:40.658: W/System.err(1019):     at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:2109)
05-11 22:20:40.658: W/System.err(1019):     at java.io.ObjectInputStream.<init>(ObjectInputStream.java:372)
05-11 22:20:40.658: W/System.err(1019):     at com.sajnasoft.down2home.MainActivity.readProfiles(MainActivity.java:59)
05-11 22:20:40.658: W/System.err(1019):     at com.sajnasoft.down2home.MainActivity.onCreate(MainActivity.java:83)
05-11 22:20:40.658: W/System.err(1019):     at android.app.Activity.performCreate(Activity.java:5104)
05-11 22:20:40.658: W/System.err(1019):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
05-11 22:20:40.668: W/System.err(1019):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
05-11 22:20:40.668: W/System.err(1019):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-11 22:20:40.668: W/System.err(1019):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-11 22:20:40.668: W/System.err(1019):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-11 22:20:40.668: W/System.err(1019):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-11 22:20:40.668: W/System.err(1019):     at android.os.Looper.loop(Looper.java:137)
05-11 22:20:40.668: W/System.err(1019):     at android.app.ActivityThread.main(ActivityThread.java:5041)
05-11 22:20:40.678: W/System.err(1019):     at java.lang.reflect.Method.invokeNative(Native Method)
05-11 22:20:40.678: W/System.err(1019):     at java.lang.reflect.Method.invoke(Method.java:511)
05-11 22:20:40.678: W/System.err(1019):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-11 22:20:40.678: W/System.err(1019):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-11 22:20:40.678: W/System.err(1019):     at dalvik.system.NativeStart.main(Native Method)

好的,现在我在 onCreate 中初始化密码和盐,我的方法变得更加复杂,如下所示。最终结果是尝试读取时流损坏。

private Spinner spinner;
private SpinAdapter adapter;
private Cipher cipher;
private ArrayList<ConnectionProfile> connectionProfiles;
private KeyGenerator keygen;
private SecretKey key;
private String salt;
private SecretKey saltedKey;
private static final String RANDOM_ALGORITHM = "SHA1PRNG";
private IvParameterSpec ivSpec;

public void createKey() throws Exception {
    keygen = KeyGenerator.getInstance("AES");
    key = keygen.generateKey();
    byte[] saltedKeyBytes = new byte[key.getEncoded().length+salt.getBytes().length];
    System.arraycopy(key.getEncoded(), 0, saltedKeyBytes, 0, key.getEncoded().length);
    System.arraycopy(salt.getBytes(), 0, saltedKeyBytes, key.getEncoded().length, salt.getBytes().length);
    saltedKey = new SecretKeySpec(saltedKeyBytes, 0, saltedKeyBytes.length, "AES");
}

 private byte[] generateIv() throws NoSuchAlgorithmException {
      SecureRandom random = SecureRandom.getInstance(RANDOM_ALGORITHM);
      byte[] iv = new byte[16];
      random.nextBytes(iv);
      return iv;
}

public void saveProfiles() {
    try {
        if (key == null) {createKey();}
        cipher.init(Cipher.ENCRYPT_MODE, saltedKey, ivSpec);
        FileOutputStream fos = openFileOutput("connProfiles.bin", Context.MODE_PRIVATE);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        CipherOutputStream cos = new CipherOutputStream(bos, cipher);
        ObjectOutputStream oos = new ObjectOutputStream(cos);
        oos.writeObject(connectionProfiles);
        oos.flush();
        oos.close();
        FileOutputStream keyOutputStream = openFileOutput("key.bin", Context.MODE_PRIVATE);
        keyOutputStream.write(key.getEncoded());
        keyOutputStream.flush();
        keyOutputStream.close();
        byte[] iv = generateIv();
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        FileOutputStream ivOutputStream = openFileOutput("iv.bin", Context.MODE_PRIVATE);
        ivOutputStream.write(iv);
        ivOutputStream.flush();
        ivOutputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void readProfiles() {
    try {
        File file = new File(this.getFilesDir(), "key.bin");
        byte[] keyBytes = new byte[(int) file.length()];
        FileInputStream keyInputStream = new FileInputStream(file);
        keyInputStream.read(keyBytes);
        keyInputStream.close();
        File file2 = new File(this.getFilesDir(), "iv.bin");
        byte[] iv = new byte[(int) file2.length()];
        FileInputStream ivInputStream = new FileInputStream(file2);
        ivInputStream.read(iv);
        ivInputStream.close();
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        byte[] saltedKeyBytes = new byte[keyBytes.length+salt.getBytes().length];
        System.arraycopy(keyBytes, 0, saltedKeyBytes, 0, keyBytes.length);
        System.arraycopy(salt.getBytes(), 0, saltedKeyBytes, keyBytes.length, salt.getBytes().length);
        saltedKey = new SecretKeySpec(saltedKeyBytes, 0, saltedKeyBytes.length, "AES");
        cipher.init(Cipher.DECRYPT_MODE, saltedKey, ivSpec);
        FileInputStream fis = openFileInput("connProfiles.bin");
        BufferedInputStream bis = new BufferedInputStream(fis);
        CipherInputStream cis = new CipherInputStream(bis, cipher);
        ObjectInputStream ois = new ObjectInputStream(cis);
        connectionProfiles = (ArrayList<ConnectionProfile>) ois.readObject();
        ois.close();
    } catch (Exception e) {
        e.printStackTrace();
        ;
    }
}

追溯:

05-19 01:08:17.325: W/System.err(843): java.io.StreamCorruptedException
05-19 01:08:17.325: W/System.err(843):  at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:2109)
05-19 01:08:17.325: W/System.err(843):  at java.io.ObjectInputStream.<init>(ObjectInputStream.java:372)
05-19 01:08:17.335: W/System.err(843):  at com.sajnasoft.down2home.MainActivity.readProfiles(MainActivity.java:102)
05-19 01:08:17.335: W/System.err(843):  at com.sajnasoft.down2home.MainActivity.onCreate(MainActivity.java:132)
05-19 01:08:17.335: W/System.err(843):  at android.app.Activity.performCreate(Activity.java:5104)
05-19 01:08:17.335: W/System.err(843):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
05-19 01:08:17.335: W/System.err(843):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
05-19 01:08:17.335: W/System.err(843):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-19 01:08:17.335: W/System.err(843):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-19 01:08:17.335: W/System.err(843):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-19 01:08:17.345: W/System.err(843):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-19 01:08:17.345: W/System.err(843):  at android.os.Looper.loop(Looper.java:137)
05-19 01:08:17.345: W/System.err(843):  at android.app.ActivityThread.main(ActivityThread.java:5041)
05-19 01:08:17.345: W/System.err(843):  at java.lang.reflect.Method.invokeNative(Native Method)
05-19 01:08:17.345: W/System.err(843):  at java.lang.reflect.Method.invoke(Method.java:511)
05-19 01:08:17.345: W/System.err(843):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-19 01:08:17.345: W/System.err(843):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-19 01:08:17.355: W/System.err(843):  at dalvik.system.NativeStart.main(Native Method)

【问题讨论】:

    标签: android io inputstream outputstream encryption


    【解决方案1】:

    好的,我得到它的工作。您没有使用正确的 ivSpec 进行密码初始化。试试这个(iv 现在是一个字段):

    public void saveProfiles() {
        try {
            if (key == null) {
                createKey();
                iv = generateIv();
                ivSpec = new IvParameterSpec(iv);
            }
            cipher.init(Cipher.ENCRYPT_MODE, saltedKey, ivSpec);
            FileOutputStream fos = openFileOutput("connProfiles.bin", Context.MODE_PRIVATE);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            CipherOutputStream cos = new CipherOutputStream(bos, cipher);
            ObjectOutputStream oos = new ObjectOutputStream(cos);
            oos.writeObject(connectionProfiles);
            oos.flush();
            oos.close();
            FileOutputStream keyOutputStream = openFileOutput("key.bin", Context.MODE_PRIVATE);
            keyOutputStream.write(key.getEncoded());
            keyOutputStream.flush();
            keyOutputStream.close();
            FileOutputStream ivOutputStream = openFileOutput("iv.bin", Context.MODE_PRIVATE);
            ivOutputStream.write(iv);
            ivOutputStream.flush();
            ivOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    在我的测试中,我没有使用盐。如果密钥太长,这也可能会导致问题。

    【讨论】:

    • 不,我确定 key+salt 是 256 位
    • java.security.InvalidAlgorithmParameterException:IV 必须为 16 字节长。等等,这可能是我的错。
    • 我把 byte[] iv = null 放在了你函数的顶部,而我可能应该把 byte[] iv = new byte[16]; 放在上面
    • 您应该将其声明为字段,因为您将密钥保存在字段中。如果键不为空,否则您不会生成 iv。
    • 现在有一个奇怪的问题。 connectionProfiles 是一个显示在微调器中的数组。保存时微调器没有更新。不涉及回溯。保存后打开时,也不会在微调器中显示保存的结果。在模拟器中有这个问题,而不是在我的设备上。在我的设备上,我看到微调器更新,但不记得保存的值。
    【解决方案2】:

    我认为问题在于您忘记了初始化密码: 您必须告诉加密或解密的密码: cipher.init(Cipher.DECRYPT_MODE, secKey); cipher.init(Cipher.ENCRYPT_MODE, secKey);

    我认为 AES 需要一个密钥来加密和解密。

    希望这个链接能帮到你:

    http://www.flexiprovider.de/examples/ExampleCrypt.html

    【讨论】:

    • 所以现在我保存了它,但阅读有困难。当我去阅读时,它可能正在创建一个不同的密钥/密码。我会更新我的 OP。
    • 如果我将密钥保存在与加密文件相同的位置,是否会危及我的安全?
    • 第一。据我所知,您必须使用相同的密钥来加密和解密。将您的密钥写在文件上,我认为没关系。但我认为你应该在从文件中读取后添加一些字符。例如,您的密钥是:“ThisIsKey_:D”。您可以保存密钥值为:“ThisIsKey”,从文件中读取它后,您可以附加“_:D”来制作您的密钥。希望对您有所帮助
    • 我还没有时间尝试您的解决方案。
    • 反编译应用程序并检索盐不是很简单吗?
    猜你喜欢
    • 1970-01-01
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多