3

En Android Developer, cuando queremos integrar la librería In-app Billing Version 3, encontramos la recomendación de que las claves base64 de la aplicación no deben ser guardadas de forma plana en el código:

/* base64EncodedPublicKey should be YOUR APPLICATION'S PUBLIC KEY (that you got from the Google Play developer console). This is not your developer public key, it's the app-specific public key.

Instead of just storing the entire literal string here embedded in the program, construct the key at runtime from pieces or use bit manipulation (for com.probarnocuestanada, XOR with some other string) to hide the actual key. The key itself is not secret information, but we don't want to make it easy for an attacker to replace the public key with one of their own and then fake messages from the server. */

String base64EncodedPublicKey = "CONSTRUCT_YOUR_KEY_AND_PLACE_IT_HERE";

Segun la recomendación de Android, deberían ser "ofuscadas" de alguna manera para ser un poco mas seguras.

Alguien podría recomendar alguna forma sobre ¿Como almacenar de forma segura la clave base64EncodedPublicKey de una app en Android?

2
  • Buena pregunta, me interesa también saber como se puede ofuscar eso.
    – Codelaby
    el 5 jul. 2016 a las 6:45
  • 1
    En al Doc de Google repite lo mismo, pero no explica como: "Security Recommendation: It is highly recommended that you do not hard-code the exact public license key string value as provided by Google Play. Instead, you can construct the whole public license key string at runtime from substrings, or retrieve it from an encrypted store, before passing it to the constructor. This approach makes it more difficult for malicious third-parties to modify the public license key string in your APK file" el 5 jul. 2016 a las 16:54

3 respuestas 3

2

La huella digital de tu aplicación es un valor único que se puede obtener mediante programación. Este valor sólo existe en el propio PC del desarrollador (para firmar APKs) o en tiempo de ejecución en la app.

Se puede emplear ese valor como clave de encriptado; para obtenerlo:

public String getCertificateSHA1Fingerprint(Context context) {
    PackageManager pm = context.getPackageManager();
    String packageName = context.getPackageName();
    int flags = PackageManager.GET_SIGNATURES;
    PackageInfo packageInfo = null;
    try {
        packageInfo = pm.getPackageInfo(packageName, flags);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    Signature[] signatures = packageInfo.signatures;
    byte[] cert = signatures[0].toByteArray();
    InputStream input = new ByteArrayInputStream(cert);
    CertificateFactory cf = null;
    try {
        cf = CertificateFactory.getInstance("X509");
    } catch (CertificateException e) {
        e.printStackTrace();
    }
    X509Certificate c = null;
    try {
        c = (X509Certificate) cf.generateCertificate(input);
    } catch (CertificateException e) {
        e.printStackTrace();
    }
    String hexString = null;
    try {
        MessageDigest md = MessageDigest.getInstance("SHA1");
        byte[] publicKey = md.digest(c.getEncoded());
        hexString = byte2HexFormatted(publicKey);
    } catch (NoSuchAlgorithmException | CertificateEncodingException e1) {
        e1.printStackTrace();
    }
    return hexString;
}

private String byte2HexFormatted(byte[] arr) {
    StringBuilder str = new StringBuilder(arr.length * 2);
    for (int i = 0; i < arr.length; i++) {
        String h = Integer.toHexString(arr[i]);
        int l = h.length();
        if (l == 1) h = "0" + h;
        if (l > 2) h = h.substring(l - 2, l);
        str.append(h.toUpperCase());
        if (i < (arr.length - 1)) str.append(':');
    }
    return str.toString();
}

Con el fingerprint de tu app:

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

public class AES {

    public static SecretKey generateKey(String key) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-1");
        byte[] passphrase = null;
        try {
            passphrase = digest.digest(key.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        passphrase = Arrays.copyOf(passphrase, 16);
        return new SecretKeySpec(passphrase, "AES");
    }

    public static String encrypt(String message, String key) throws Exception {
        byte[] data = message.getBytes("UTF-8");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, generateKey(key));
        byte[] encryptData = cipher.doFinal(data);

        return byteArrayToHexString(encryptData);
    }

    public static String decrypt(String v, String key) throws Exception {
        byte[] tmp = hexStringToByteArray(v);
        SecretKeySpec spec = new SecretKeySpec(generateKey(key).getEncoded(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, spec);
        String result;
        try {
            result = new String(cipher.doFinal(tmp), StandardCharsets.UTF_8);
        } catch (IllegalBlockSizeException e) {
            result = v;
        }

        return result;

    }

    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len/2];

        for(int i = 0; i < len; i+=2){
            data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
        }

        return data;
    }

    final protected static char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    public static String byteArrayToHexString(byte[] bytes) {
        char[] hexChars = new char[bytes.length*2];
        int v;

        for(int j=0; j < bytes.length; j++) {
            v = bytes[j] & 0xFF;
            hexChars[j*2] = hexArray[v>>>4];
            hexChars[j*2 + 1] = hexArray[v & 0x0F];
        }

        return new String(hexChars);
    }
}

Para guardar el texto, puedes hacerlo como preferencia:

    public String getSecret() {
        SharedPreferences prefs = getSharedPreferences("com.example.test", Context.MODE_PRIVATE);
        String val = prefs.getString("secret", null);
        return val;
    }

    public void setSecret(String secret) {
        SharedPreferences.Editor editor = getSharedPreferences("com.example.test", Context.MODE_PRIVATE).edit();
        editor.putString("secret", secret).apply();
    }

Resumen:

String sha1 = getCertificateSHA1Fingerprint(this); // obtenemos huella digital
String message = "hello_world";
String encrypted = AES.encrypt(message, sha1); // encripta texto

setSecret(encrypted);
String secret = getSecret();
Log.e("TEST", secret);

String decrypted = AES.decrypt(secret, sha1);
Log.e("TEST", decrypted);

Este código se emplea en la librería AndroidStringObfuscator, que automatiza esta tarea.

1

Como regla ningún método es infalible, pero hay varias alternativas que hacen más difícil obtener esa clave.

La mejor alternativa: Tener la clave en el servidor. De esta manera no se puede obtener obtener la clave haciendo una decompilación de la app. La contra es que requiere conectividad para funcionar.

Calcular la clave: Esto es lo que menciona @Pablo Ezequiel utilizar strings y algoritmos para armar la clave en tiempo real. Siendo Base64 podría ser algo tan simple como guardar el valor decodificado, idealmente separado en distintos lugares.

Shared preferences/SQLite: Estas son las alternativas más básicas, la clave no está en el código pero una persona con voluntad puede recuperar estos valores.

String en el código: Esta es la peor opción ya que cualquier persona puede decompilar el APK puede encontrar este valor expuesto, por mas que se haya ofuscado la app usando proguard.

1

Recomendaciones de google en su guía Seguridad y diseño resalto lo interesante en este caso:

De ser posible, debes realizar la verificación de firma en un servidor remoto y no en un dispositivo. Implementar el proceso de verificación en un servidor hace que para los atacantes resulte difícil interrumpir el proceso de verificación mediante la aplicación de ingeniería inversa a tu archivo .apk. Si transfieres el procesamiento de seguridad a un servidor remoto, asegúrate de que el protocolo de enlace entre el dispositivo y el servidor sea seguro.

Oculta tu código

Debes ocultar tu código de facturación integrada a fin de que sea difícil para un atacante aplicar ingeniería inversa a los protocolos de seguridad y a otros componentes de la aplicación. Como mínimo, te recomendamos ejecutar una herramienta de ocultamiento como Proguard en tu código.

Nota: Si usas Proguard para ocultar tu código, debes agregar la siguiente línea a tu archivo de configuración de Proguard: -keep class com.android.vending.billing.**

Protege tu clave pública de Google Play

Para mantener tu clave pública protegida contra usuarios maliciosos y hackers, no la incorpores a ningún código como string literal. En cambio, construye la string en el tiempo de ejecución a partir de piezas o usa manipulación de bits (por ejemplo, XOR con alguna otra string) para ocultar la clave real. La clave en sí misma no representa información secreta, pero no será conveniente que un hacker o usuario malicioso puedan reemplazar fácilmente la clave pública por otra.

Buscando por SO In app billing security he encontrado cómo implementar un sistema de cifrado en XOR

public static String xorEncrypt(String input, String key) {
    byte[] inputBytes = input.getBytes();
    int inputSize = inputBytes.length;

    byte[] keyBytes = key.getBytes();
    int keySize = keyBytes.length - 1;

    byte[] outBytes = new byte[inputSize];
    for (int i=0; i<inputSize; i++) {
        outBytes[i] = (byte) (inputBytes[i] ^ keyBytes[i % keySize]);
    }

    return new String(Base64.encode(outBytes, Base64.DEFAULT));
}

public static String xorDecrypt(String input, String key) {
    byte[] inputBytes = Base64.decode(input, Base64.DEFAULT);
    int inputSize = inputBytes.length;

    byte[] keyBytes = key.getBytes();
    int keySize = keyBytes.length - 1;

    byte[] outBytes = new byte[inputSize];
    for (int i=0; i<inputSize; i++) {
        outBytes[i] = (byte) (inputBytes[i] ^ keyBytes[i % keySize]);
    }

    return new String(outBytes);
}

No les he probado aun

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.