在Android上加密和解密数据的最佳方法

时间:2019-01-23 12:57:50

标签: android security encryption server

我想在android中加密数据,以将其保存为共享首选项或将其发送到服务器。

这是我为此编写的类,但是我不知道有什么其他方法可以使它更加完善和安全。

请告诉我您的想法!

public class Cryptogram {

    private static byte[] iv;
    private static IvParameterSpec ivspec;

    public static byte[] Encrypt(String txt, SecretKey key) {
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] cipherText = cipher.doFinal(txt.getBytes("UTF-8"));
            iv = cipher.getIV();
            ivspec = new IvParameterSpec(iv);
            return cipherText;
        } catch (Exception e) {
            return e.toString().getBytes(Charset.forName("UTF-8"));
        }
    }

    public static String Decrypt(byte[] txt, SecretKey key) {
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", Security.getProvider("BC"));
            cipher.init(Cipher.DECRYPT_MODE, key, ivspec);
            String decryptString = new String(cipher.doFinal(txt), "UTF-8");
            return decryptString;
        } catch (Exception e) {
            return e.toString();
        }
    }
}

完整project source here

0 个答案:

没有答案