0

我使用这段代码来加密字符串,它工作得很好:

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 中运行此代码显示带有当前进程的 ProgressDialog。在 AsyncTask 类中运行代码是没有问题的,但我不知道如何获得当前进度。

编辑:我使用此代码在 AsyncTask 中运行代码:

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();
        }
    }

我想用这段代码加密几 MB 的数据。

编辑:我将此代码添加到加密:

    public int getProcess() {
        return ((int) (offset / totalSize) * 100);
    }

    public void setProgress(int totalSize, int offset) {
        this.totalSize = totalSize;
        this.offset = offset;
    }
4

3 回答 3

2

你调用 doFinal(byte[])。这样您就无法从 Cipher 中获取进度信息。当您更改为更新(字节 []、偏移等)时,您可以分块数据并在循环中显示您的进度。顺便说一句,完成最后。

你可能会得到类似的东西(从头开始)

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;
}
于 2012-12-13T17:57:51.090 回答
1

Did you look at the AsyncTask Reference? It is built-in.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

于 2012-12-13T17:54:58.177 回答
0

你应该能够。您在线程部分完成繁重的工作,并且 ASyncTask 具有帮助您使用 UI 线程更新控件的机制

于 2012-12-13T17:52:43.627 回答