Android加密/解密ArrayList <linkedhashmap>到String </linkedhashmap>

时间:2014-02-26 16:38:52

标签: android encryption arraylist

所以我使用下面的代码来加密/解密可以存储在设备首选项中的字符串值,但我知道需要添加一个加密/解密ArrayList的方法,该方法也可以存储在首选项中(所以我猜测加密需要将arraylist转换为字符串,然后解密需要将该字符串转换回arraylist)。由于我对Android / Java很陌生,所以我很难弄清楚如何做到这一点,所以任何帮助都会受到赞赏。

public String encrypt(String key, String data) {
    if (key == null || data == null)
        return null;
    try {
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(charsetName));
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
        SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);
        byte[] dataBytes = data.getBytes(charsetName);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return Base64.encodeToString(cipher.doFinal(dataBytes), base64Mode);
    } catch (Exception e) {
        return null;
    }
}

public String decrypt(String key, String data) {
    if (key == null || data == null)
        return null;
    try {
        byte[] dataBytes = Base64.decode(data, base64Mode);
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(charsetName));
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
        SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] dataBytesDecrypted = (cipher.doFinal(dataBytes));
        return new String(dataBytesDecrypted);
    } catch (Exception e) {
        return null;
    }
}

1 个答案:

答案 0 :(得分:0)

在将输入发送到ArrayList<LinkedHashMap>

之前,将encrypt()序列化为Json
public static String ArrayListToString(ArrayList<LinkedHashMap> list) {
    Gson serializer = new Gson();
    return serializer.toJson(list);
}

然后在解密后进行反序列化。

您需要在项目中引用Google-Gson