Android 异步任务加密

Android 异步任务加密,android,encryption,android-asynctask,Android,Encryption,Android Asynctask,我使用此代码对字符串进行加密,效果非常好: public class Encryption { public String encrypt(String seed, String cleartext) throws Exception { byte[] rawKey = getRawKey(seed.getBytes()); byte[] result = encrypt(rawKey, cleartext.getBytes()); re

我使用此代码对字符串进行加密,效果非常好:

public class Encryption {

    public String encrypt(String seed, String cleartext) throws Exception {
        byte[] rawKey = getRawKey(seed.getBytes());
        byte[] result = encrypt(rawKey, cleartext.getBytes());
        return toHex(result);
    }

    public String decrypt(String seed, String encrypted) throws Exception {
        byte[] rawKey = getRawKey(seed.getBytes());
        byte[] enc = toByte(encrypted);
        byte[] result = decrypt(rawKey, enc);
        return new String(result);
    }

    private byte[] getRawKey(byte[] seed) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(seed);
        kgen.init(128, sr); // 192 and 256 bits may not be available
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();
        return raw;
    }

    private byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(clear);
        return encrypted;
    }

    private byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }

    public String toHex(String txt) {
        return toHex(txt.getBytes());
    }

    public String fromHex(String hex) {
        return new String(toByte(hex));
    }

    public byte[] toByte(String hexString) {
        int len = hexString.length() / 2;
        byte[] result = new byte[len];
        for (int i = 0; i < len; i++)
            result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
                    16).byteValue();
        return result;
    }

    public String toHex(byte[] buf) {
        if (buf == null)
            return "";
        StringBuffer result = new StringBuffer(2 * buf.length);
        for (int i = 0; i < buf.length; i++) {
            appendHex(result, buf[i]);
        }
        return result.toString();
    }

    private final static String HEX = "0123456789ABCDEF";

    private void appendHex(StringBuffer sb, byte b) {
        sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
    }

}

你应该能够。您在线程部分完成了繁重的工作,ASyncTask有一些机制可以帮助您使用UI线程更新控件。您在线程部分完成了繁重的提升,而ASyncTask有一些机制可以帮助您使用UI线程更新控件。您查看了吗?它是内置的

异步任务是由运行在服务器上的计算定义的 后台线程,其结果发布在UI线程上。一 异步任务由3种泛型类型定义,称为Params, 进度和结果,以及4个步骤,称为onPreExecute,doInBackground, onProgressUpdate和onPostExecute

你有没有看报纸?它是内置的

异步任务是由运行在服务器上的计算定义的 后台线程,其结果发布在UI线程上。一 异步任务由3种泛型类型定义,称为Params, 进度和结果,以及4个步骤,称为onPreExecute,doInBackground, onProgressUpdate和onPostExecute

您可以调用doFinal(字节[])。这样您就无法从密码中获取进度信息。当您更改为更新(字节[]、偏移量等)时,您可以将数据分块并在循环中显示进度。最后完成做最后的btw

你最终可能会得到类似(从头部)的东西

private byte[]encrypt(byte[]原始,byte[]清除)引发异常{
SecretKeySpec skeySpec=新SecretKeySpec(原始,“AES”);
Cipher Cipher=Cipher.getInstance(“AES”);
cipher.init(cipher.ENCRYPT_模式,skeySpec);
整数偏移=0;
字节[]加密;
while(偏移量
调用doFinal(字节[])。这样您就无法从密码中获取进度信息。当您更改为更新(字节[]、偏移量等)时,您可以将数据分块并在循环中显示进度。最后完成做最后的btw

你最终可能会得到类似(从头部)的东西

private byte[]encrypt(byte[]原始,byte[]清除)引发异常{
SecretKeySpec skeySpec=新SecretKeySpec(原始,“AES”);
Cipher Cipher=Cipher.getInstance(“AES”);
cipher.init(cipher.ENCRYPT_模式,skeySpec);
整数偏移=0;
字节[]加密;
while(偏移量
您是在大量数据或其他数据上运行此操作吗?是的,当我插入几MB数据时,我的应用程序冻结了近一分钟。您是在大量数据或其他数据上运行此操作吗?是的,当我插入几MB数据时,我的应用程序冻结了近一分钟。谢谢,您是否有来源,以便我可以尝试修复代码?对不起,我没有。publishProgress和onProgressUpdate(Progress…)可以工作吗谢谢,你有没有源代码让我可以尝试修复代码?对不起,我没有。publishProgress和onProgressUpdate(Progress…)虽然可以工作,但我知道,但是我如何从密码中获取数据以便可以调用onProgressUpdate?是的,我知道,但是如何从密码中获取数据以便可以调用onProgressUpdate?“运算符+=对于参数类型byte[],byte[]未定义。”我还在问题中添加了一些代码抱歉,我现在不使用java代码,所以我必须切换上下文。。。我对代码做了一些修改,现在应该更好了。请作为示例使用,而不是作为产品使用。如果您有一个大文件等需要加密,则使用
update()
是一种方法。否则就一次完成@ObAt您的密钥派生方法不安全,将在4.2中中断,请使用真正的密钥派生函数,如PBKDF2。详细信息:“未定义参数类型byte[],byte[]的运算符+=”。我还在问题中添加了一些代码抱歉,我现在不使用java代码,所以我必须切换上下文。。。我对代码做了一些修改,现在应该更好了。请作为示例使用,而不是作为产品使用。如果您有一个大文件等需要加密,则使用
update()
是一种方法。否则就一次完成@ObAt您的密钥派生方法不安全,将在4.2中中断,请使用真正的密钥派生函数,如PBKDF2。细节:
private class EncryptData extends AsyncTask<String, Integer, String> {
        ProgressDialog pd;

        @Override
        protected void onPreExecute() {
            pd = new ProgressDialog(MainActivity.this);
            pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pd.setMessage("Processing Data...");
            pd.setCancelable(false);
            pd.show();
        }

        @Override
        protected String doInBackground(String... arg0) {

            Encryption encryptText = new Encryption();
            String result = "";

            try {
                result = encryptText.encrypt("123", arg0[0]);
            } catch (Exception e) {

            }
            return result;
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            pd.setProgress((int) (progress[0]));
            pd.setMessage("Processing Data... (" + progress[0] + "%)");
        }

        @Override
        protected void onPostExecute(String ui) {
            setEncryptedData(ui);
            pd.dismiss();
        }
    }
    public int getProcess() {
        return ((int) (offset / totalSize) * 100);
    }

    public void setProgress(int totalSize, int offset) {
        this.totalSize = totalSize;
        this.offset = offset;
    }
private byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

    int offset = 0;
    byte[] encrypted;

    while(offset < clear.length()) {
        final byte[] answer = cipher.update(clear, offset, 1024);
        encrypted = Arrays.copyOf( encrypted, encrypted.length + 1024);
        System.arrayCopy(answer, 0, encrypted, offset, 1024);
        offset += 1024;
    }
    encrypted += cipher.doFinal(clear, offset, clear.length() - offset);
    return encrypted;
}