android加密存儲文件

       

隨着APP 數量的不斷擴大,手機個人信息也漸漸地成爲公開的祕密。加密APP中的信息是也漸漸地成爲必不可少的了。雖然有時加密很簡單,但對於普通的用戶(非技術發燒友)來說,已經很難破解了。JAVA提供了加解密支持--md5,DES,AES,PBE,RSA等很多加密算法。其中肯定會有適合的算法進行加解密。

以DES加密爲例寫的驗證程序

demo下載:http://download.csdn.net/detail/maokunlove/5134498

DESEncrypt 是對數據加解密的工具類

public class DESEncrypt {
    Key mKey;

    public DESEncrypt() {
        getKey("abcd");//"abcd"是加密的KEY,也可以爲其它的任意字符(包括數字或漢字),如果知道此KEY,並且知道是DES加密,那對方就可以解密了。最好不能公開
    }

    /**
     * According to the parameters generated KEY
     * @param strKey
     */
    public void getKey(String strKey) {
        try {
            KeyGenerator generator = KeyGenerator.getInstance("DES");
            generator.init(new SecureRandom(strKey.getBytes()));
            mKey = generator.generateKey();
            generator = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Encrypt the string
     * @param strMing
     * @return
     */
    public String getEncString(String strMing) {
        String strMi = "";
        try {
            return byte2hex(getEncCode(strMing.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strMi;
    }

    /**
     * decrypt the string
     * @param strMi
     * @return
     */
    public String getDesString(String strMi) {
        String strMing = "";
        try {
            return new String(getDesCode(hex2byte(strMi.getBytes())));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strMing;
    }

    /**
     * Encrypt the byte number string
     * @param byteS
     * @return
     */
    private byte[] getEncCode(byte[] byteS) {
        byte[] byteFina = null;
        Cipher cipher;
        try {
            cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, mKey);
            byteFina = cipher.doFinal(byteS);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cipher = null;
        }
        return byteFina;
    }

    /**
     * Decrypt the byte number string
     * @param byteD
     * @return
     */
    private byte[] getDesCode(byte[] byteD) {
        Cipher cipher;
        byte[] byteFina = null;
        try {
            cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, mKey);
            byteFina = cipher.doFinal(byteD);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cipher = null;
        }
        return byteFina;
    }

    /**
     * Convert one byte number to hexadecimal string
     * @param b
     * @return
     */
    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1)
                hs = hs + "0" + stmp;
            else
                hs = hs + stmp;
        }
        return hs.toUpperCase();
    }

    /**
     * Convert the hexadecimal string to one byte number
     *
     * @param b
     * @return
     */
    public static byte[] hex2byte(byte[] b) {
        if ((b.length % 2) != 0)
            throw new IllegalArgumentException();
        byte[] b2 = new byte[b.length / 2];
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        return b2;
    }
}

MainActivity驗證是否加解密

public class MainActivity extends Activity implements OnClickListener {

    private static final String TAG = "MainActivity";
    static final int READ_BLOCK_SIZE = 100;
    
    EditText mInput;
    TextView mFileText;
    Button mSave,mGetSave;
    String fileName = "file.dat";//文件名最好是那種特殊的後綴名的,即使導出來也沒有工具打開(對於一般用戶來說),也可以進行加密
    
    DESEncrypt mDESEncrypt;
    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mInput = (EditText) findViewById(R.id.input_view);
        mFileText = (TextView) findViewById(R.id.file_text);
        mSave = (Button) findViewById(R.id.save);
        mSave.setOnClickListener(this);
        mGetSave = (Button) findViewById(R.id.get_save);
        mGetSave.setOnClickListener(this);
        
        mDESEncrypt = new DESEncrypt();
    }
    @Override
    public void onClick(View view) {
        switch(view.getId()){
        case R.id.save:
            saveTofile(fileName,mInput.getText().toString());
            break;
        case R.id.get_save:
            getFileText();
            break;
        }
    }
    
    private void saveTofile(String fileName,String text) {
        try {
            FileOutputStream fOut;
            fOut = openFileOutput(fileName, MODE_WORLD_READABLE);

            OutputStreamWriter osw = new OutputStreamWriter(fOut);

            osw.write(mDESEncrypt.getEncString(text));
            osw.flush();
            osw.close();

            Toast.makeText(getBaseContext(), "File saved successfully!",Toast.LENGTH_SHORT).show();

            mInput.setText("");
        } catch (Exception ioe) {
            ioe.printStackTrace();
        }
    }
    
    private void getFileText() {
        try {
            FileInputStream fIn = openFileInput(fileName);
            InputStreamReader isr = new InputStreamReader(fIn);

            char[] inputBuffer = new char[READ_BLOCK_SIZE];
            String s = "";

            int charRead;
            while ((charRead = isr.read(inputBuffer)) > 0) {
                String readString = String.copyValueOf(inputBuffer, 0, charRead);
                s += readString;

                inputBuffer = new char[READ_BLOCK_SIZE];
            }

        } catch (Exception ioe) {
            ioe.printStackTrace();
        }
    }

範例下載:http://download.csdn.net/detail/maokunlove/5134498



發佈了22 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章