如何使用密钥加密和解密android中的json字符串?

时间:2017-10-31 05:14:35

标签: android json encryption android-canvas

我目前正在开发一个基于绘图的项目,我已经将值存储为json格式并存储在文件中,但我想通过使用密钥加密json并使用相同的密钥解密json。

2 个答案:

答案 0 :(得分:5)

使用String resultString = JSON.stringify()对您的json进行字符串化,并使用以下方法加密您的resultString

public class EncryptUtils {
public static SecretKey generateKey(String mySecret) 
    throws NoSuchAlgorithmException, InvalidKeySpecException 
{ 
    return secret = new SecretKeySpec(mySecret.getBytes(), "AES"); 
}

public static byte[] encryptMsg(String message, SecretKey secret)
    throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException 
{ 
   /* Encrypt the message. */
   Cipher cipher = null; 
   cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
   cipher.init(Cipher.ENCRYPT_MODE, secret); 
   byte[] cipherText = cipher.doFinal(message.getBytes("UTF-8")); 
   return cipherText; 
}

public static String decryptMsg(byte[] cipherText, SecretKey secret) 
    throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidParameterSpecException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException 
{
    /* Decrypt the message, given derived encContentValues and initialization vector. */
    Cipher cipher = null;
    cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, secret); 
    String decryptString = new String(cipher.doFinal(cipherText), "UTF-8");
    return decryptString; 
}
}

String mySecret="mySecretKeyString";
String secretKey = EncryptUtils.generateKey(mySecret);
String encryptedStr = EncryptUtils.encryptMsg(jsonResultString, secretKey));

String decryptedStr = EncryptUtils.decryptMsg(encryptedStr.getBytes("UTF-8"), secretKey));

最后,您可以使用以下方法获取JSON数据

try {

    JSONObject obj = new JSONObject(decryptedString);

    Log.d("My App", obj.toString());

} catch (Throwable t) {
    Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}

答案 1 :(得分:-2)

请勿将其用作某种安全措施。

这篇文章中的加密机制是一次性填充,这意味着攻击者可以使用2个加密消息轻松恢复密钥。 XOR 2加密消息,你得到了密钥。那很简单!

public class EncryptUtils {
    public static final String DEFAULT_ENCODING = "UTF-8"; 
    static BASE64Encoder enc = new BASE64Encoder();
    static BASE64Decoder dec = new BASE64Decoder();

    public static String base64encode(String text) {
        try {
            return enc.encode(text.getBytes(DEFAULT_ENCODING));
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }//base64encode

    public static String base64decode(String text) {
        try {
            return new String(dec.decodeBuffer(text), DEFAULT_ENCODING);
        } catch (IOException e) {
            return null;
        }
    }//base64decode

    public static void main(String[] args) {
        String txt = "some text to be encrypted";
        String key = "key phrase used for XOR-ing";
        System.out.println(txt + " XOR-ed to: " + (txt = xorMessage(txt, key)));

        String encoded = base64encode(txt);       
        System.out.println(" is encoded to: " + encoded + " and that is decoding to: " + (txt = base64decode(encoded)));
        System.out.print("XOR-ing back to original: " + xorMessage(txt, key));
    }

    public static String xorMessage(String message, String key) {
        try {
            if (message == null || key == null) return null;

            char[] keys = key.toCharArray();
            char[] mesg = message.toCharArray();

            int ml = mesg.length;
            int kl = keys.length;
            char[] newmsg = new char[ml];

            for (int i = 0; i < ml; i++) {
                newmsg[i] = (char)(mesg[i] ^ keys[i % kl]);
            }//for i

            return new String(newmsg);
        } catch (Exception e) {
            return null;
        }
    }//xorMessage
}