0

I want to encrypt data in android to save them in shared preferences or send them to the server.

This is a class which I wrote for this, but I don't know any other ways to make it more perfect and secure.

Please tell me your ideas!

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

Full project source here.

Hossein Yousefpour
  • 3,827
  • 3
  • 23
  • 35
  • Where do you store the secret key? This may undermine the security you seem to believe to have. – Henry Jan 23 '19 at 13:06
  • @Henry I'm working to add it on AndroidKeyStore. for now its combine of something like "username+password+a number". – Hossein Yousefpour Jan 23 '19 at 13:13
  • there is no best way. Does your class work? What is the problem? – Vladyslav Matviienko Jan 23 '19 at 13:26
  • 1
    this may help: [Best practice for storing and protecting private API keys in applications](https://stackoverflow.com/questions/14570989/best-practice-for-storing-and-protecting-private-api-keys-in-applications) – Dhamik jagodana Jan 23 '19 at 17:57
  • @VladyslavMatviienko yes. It works so well! I just want to be serious about having the best and secure way. – Hossein Yousefpour Jan 23 '19 at 17:58
  • It doesn't handle IVs. So if you encrypt something and then want to decrypt it later, you won't be able to. – Luke Joshua Park Jan 23 '19 at 18:02
  • 1
    @LukeJoshuaPark seems it stores IV as an object property (not correctly indeed). So Gabriel - iv is to be unique for each encryption, so you could consider it as part of the ciphertext (not an object property). You can use padding, `NoPadding` works only for for block-size input. Encryption itself seems ok otherwise, but security is much broader term, still you may consider how you generate or store the encryption key – gusto2 Jan 25 '19 at 10:04

0 Answers0