Skip to content

Instantly share code, notes, and snippets.

@bakawaii
Created October 11, 2017 15:53
Show Gist options
  • Save bakawaii/406e4b638dce6083dd2d9d7b66828823 to your computer and use it in GitHub Desktop.
Save bakawaii/406e4b638dce6083dd2d9d7b66828823 to your computer and use it in GitHub Desktop.
import android.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class CryptographyHelper {
private static final String ALGORITHM = "AES/ECB/ZeroBytePadding";
public static String encrypt(String plaintext, String key) throws Exception {
return Base64.encodeToString(encrypt(plaintext.getBytes("UTF-8"), key.getBytes("UTF-8"), ALGORITHM), Base64.NO_WRAP);
}
public static String decrypt(String ciphertext, String key) throws Exception {
return new String(decrypt(Base64.decode(ciphertext, Base64.NO_WRAP), key.getBytes("UTF-8"), ALGORITHM), "UTF-8");
}
private static byte[] encrypt(byte[] plaintext, byte[] key, String algorithm) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key, algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
return cipher.doFinal(plaintext);
}
private static byte[] decrypt(byte[] ciphertext, byte[] key, String algorithm) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key, algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
return cipher.doFinal(ciphertext);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment