java中的解密问题

时间:2014-12-23 10:58:59

标签: java android encryption

我正在玩Android中保存/加载文本文件,工作正常。下一步是使用AES加密和解密。

我可以在writetofile方法中调用encrypt()方法,这个方法运行正常。如果我调用readfromfile方法,我可以看到检索到的密文很好。

但是解密对我来说不起作用 - 我在一些地方调用了simplecrypo--在stringBuffer.toString()和StringBuffer的append()方法中 - 但两者都使应用程序崩溃。

那么有人知道我应该在文件中解密字符串吗?

package com.example.filesdemo;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    private EditText etInput;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etInput = (EditText) findViewById(R.id.etInput);

    }

    public void writeToFile(View v) throws Exception {
        try {
            String inputStr = etInput.getText().toString();
            //encrypt the string - works!
            String encrypted = SimpleCrypto.encrypt("testkey", inputStr);


            FileOutputStream fos = openFileOutput("myfile.txt", MODE_PRIVATE);
            fos.write(encrypted.getBytes());
            fos.flush();
            fos.close();
            Toast.makeText(this, "File saved!", Toast.LENGTH_SHORT).show();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void readFromFile(View v) throws Exception{
        try {
            FileInputStream fis = openFileInput("myfile.txt");
            StringBuffer stringBuffer = new StringBuffer();
            BufferedReader bReader = new BufferedReader(new InputStreamReader(
                    fis));
            String strLine = null;

            while ((strLine = bReader.readLine()) != null) {
                stringBuffer.append(strLine + "\n");

            }
            bReader.close();
            fis.close();
            Toast.makeText(this, "File content: \n" +stringBuffer.toString(),
                    Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

此处公开提供加密类 - decrypt class,但我不认为这是问题。

谢谢!

1 个答案:

答案 0 :(得分:0)

从外观上看,您正在将加密的字节写入文件,然后尝试将它们作为文本读回到扫描仪中。正如你所发现的那样,它不会起作用。

如果您希望文件是文本,则需要将字节转换为Base64并写为文本。在读取Base64文本时,转换回字节和decypher。 Java 8有Base64类,我不确定Android。

如果您希望将文件作为原始字节,则需要将其作为字节读取,而不是文本。一旦读作字节,就可以直接解除。

相关问题