Hiding strings in Obfuscated code

JavaAndroidProguard

Java Problem Overview


I just Obfuscated my Android code using proguard and then decompiled it. There are a number of strings I would really like to hide from prying eyes. When I decompiled my code the strings were there for everyone to see...and change. One of the strings is a URL to my licensing server and they could in effect change the url to point to a fake server (as I will be releasing the server code to the public). What is the best way of hiding this sort of information?

Also, I noticed that the R class strings are all random numbers but I can't find the R class in the decompiled code. Where is it?

Foe example I see: new SimpleCursorAdapter(localActivity, 2130903058, localCursor, arrayOfString, arrayOfInt);

2130903058 is a layout file but what is it referencing? The number means nothing unless it is pointing to some sort of address.

Java Solutions


Solution 1 - Java

Assuming you are happy with obscure rather than secure, there a number of mechanisms you could use, but obfuscaters like proguard are not going to be able to help you.

To achieve this you will need to do encoding or encryption of the string yourself, the approach you use depends on what you are trying to defend against, if it you are just trying to hide from obvious inspection, than encoding may be sufficient (see android.util.Base64, http://developer.android.com/reference/android/util/Base64.html). Note that encoding is in NO WAY SECURE and all it will to is remove the obvious reference to your site.

If you are trying to defend against something more, then you could move to actually encrypting the string, to do this you would use a symmetric cipher like AES via javax.crypto.Cipher, http://www.androidsnippets.org/snippets/39/index.html provides a decent usage example. Again this is more annoying then secure to would be hackers, as you will need to store the key somewhere in your jar thus negating any cryptographic security.

To make this clearer, the basic steps would be:

  1. Manually create an encrypt your string using a known key.
  2. Convert your code to use a decrypted version of this string, example:

Before:

public class Foo {
    private String mySecret = "http://example.com";
  
    ...
}

Becomes:

public class Foo {
    private String encrypted = "<manually created encrypted string>";
    private String key = "<key used for encryption";
    private String mySecret = MyDecryptUtil.decrypt(encrypted, key);

    ...
}

A (good) alternative to all of this is considering using a third party drm solution such as the licensing server google provides http://android-developers.blogspot.com/2010/07/licensing-service-for-android.html. This may be more secure than something you roll your self, but is subject to very similar limitations to what I described above.

Solution 2 - Java

Hi all.

  1. Let secret be the text you want to hide

  2. Find the keyhash of your debug/release.keystore. Let k1 be this key.

(use tools keytool+openssl: keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64 )

  1. Use a tool (external to the android code) to encrypt secret with k1

    encrypted = encode (secret, k1)

(For instance: https://jwt.io, for java: https://github.com/jwtk/jjwt).

  1. In your android java code write down encrypted. When you need the decoded version of encrypted (this is, the original secret) write

original = decode(encrypted, get_my_keyhash_programmatically() )

That's all. This works because the original secret is not shown on java source code, neither the k1 to decode it. And, if a hacker wants to print your decoded secret, he must change code and recompile, signing his .apk with his own keystore not yours, and thus not getting the right original secret. (The "only" point is whether k1 can be figured out from your original .apk).

Note: get_my_keyhash_programmatically():

try {
    PackageInfo info = getPackageManager().getPackageInfo(
            "el nombre de su paquete por ejemplo com.tarea.u8",
            PackageManager.GET_SIGNATURES);
    for (Signature signature : info.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
    }
} catch (PackageManager.NameNotFoundException e) {

} catch (NoSuchAlgorithmException e) {

}

Solution 3 - Java

what I did was create a long list of static strings in my global utility class. Someplace within the long list of strings I put my passkey in multiple chunks.

with my code it's easy to see what the real passkeys are - but once the obfuscator gets to work all the statics will have name like A, B, C, etc. and it won't be easy to spot any more.

Solution 4 - Java

I used ROT47. It's not very secure, but easy to use and implement, because it's a symetric encoder/decoder

Solution 5 - Java

You should google for "Just another Perl hacker". These are programms that print out a string with obfuscated code. There are also lots of examples in other languages then Perl on the net.

Wikipedia entry

Solution 6 - Java

Here is what I currently use it has hacks to support sprintf functions which spilled plain-text in compiled binary file. You could now use w_sprintf_s instead of sprintf, like so

char test[256] = { 0 };
w_sprintf_s(test, 256, XorStr("test test :D %d %+d\n"), 1, 1337);

or use it like this to print stuff on screen for example

w_printf(XorStr("test I print this and can't see me inside .dll or .exe"));

works on variables, if you have a custom printf() you could use that as well..

char szGuid[255] = { 0 };
//generate serial code removed.
char finalSerial[512] = { 0 };
XorCompileTime::w_sprintf(finalSerial, XorStr("serial information=%s"), szGuid);
myprintf(XorStr("Your Hardware ID: %s\n"), szGuid);


May add support for wchar_t wide strings like arkan did.. but I have no use for them right now as I don't write anything in symbols / unicode.

Here is a file just rename the code below to a XorString.h file and include it in your project simple as that

#pragma once
#include <string>
#include <array>
#include <cstdarg>

#define BEGIN_NAMESPACE( x ) namespace x {
#define END_NAMESPACE }

BEGIN_NAMESPACE(XorCompileTime)

constexpr auto time = __TIME__;
constexpr auto seed = static_cast< int >(time[7]) + static_cast< int >(time[6]) * 10 + static_cast< int >(time[4]) * 60 + static_cast< int >(time[3]) * 600 + static_cast< int >(time[1]) * 3600 + static_cast< int >(time[0]) * 36000;

// 1988, Stephen Park and Keith Miller
// "Random Number Generators: Good Ones Are Hard To Find", considered as "minimal standard"
// Park-Miller 31 bit pseudo-random number generator, implemented with G. Carta's optimisation:
// with 32-bit math and without division

template < int N >
struct RandomGenerator
{
private:
	static constexpr unsigned a = 16807; // 7^5
	static constexpr unsigned m = 2147483647; // 2^31 - 1

	static constexpr unsigned s = RandomGenerator< N - 1 >::value;
	static constexpr unsigned lo = a * (s & 0xFFFF); // Multiply lower 16 bits by 16807
	static constexpr unsigned hi = a * (s >> 16); // Multiply higher 16 bits by 16807
	static constexpr unsigned lo2 = lo + ((hi & 0x7FFF) << 16); // Combine lower 15 bits of hi with lo's upper bits
	static constexpr unsigned hi2 = hi >> 15; // Discard lower 15 bits of hi
	static constexpr unsigned lo3 = lo2 + hi;

public:
	static constexpr unsigned max = m;
	static constexpr unsigned value = lo3 > m ? lo3 - m : lo3;
};

template <>
struct RandomGenerator< 0 >
{
	static constexpr unsigned value = seed;
};

template < int N, int M >
struct RandomInt
{
	static constexpr auto value = RandomGenerator< N + 1 >::value % M;
};

template < int N >
struct RandomChar
{
	static const char value = static_cast< char >(1 + RandomInt< N, 0x7F - 1 >::value);
};

template < size_t N, int K >
struct XorString
{
private:
	const char _key;
	std::array< char, N + 1 > _encrypted;

	constexpr char enc(char c) const
	{
		return c ^ _key;
	}

	char dec(char c) const
	{
		return c ^ _key;
	}

public:
	template < size_t... Is >
	constexpr __forceinline XorString(const char* str, std::index_sequence< Is... >) : _key(RandomChar< K >::value), _encrypted{ enc(str[Is])... }
	{
	}

	__forceinline decltype(auto) decrypt(void)
	{
		for (size_t i = 0; i < N; ++i) {
			_encrypted[i] = dec(_encrypted[i]);
		}
		_encrypted[N] = '\0';
		return _encrypted.data();
	}
};

//--------------------------------------------------------------------------------
//-- Note: XorStr will __NOT__ work directly with functions like printf.
//         To work with them you need a wrapper function that takes a const char*
//         as parameter and passes it to printf and alike.
//
//         The Microsoft Compiler/Linker is not working correctly with variadic 
//         templates!
//  
//         Use the functions below or use std::cout (and similar)!
//--------------------------------------------------------------------------------

static auto w_printf = [](const char* fmt, ...) {
	va_list args;
	va_start(args, fmt);
	vprintf_s(fmt, args);
	va_end(args);
};

static auto w_printf_s = [](const char* fmt, ...) {
	va_list args;
	va_start(args, fmt);
	vprintf_s(fmt, args);
	va_end(args);
};

static auto w_sprintf = [](char* buf, const char* fmt, ...) {
	va_list args;
	va_start(args, fmt);
	vsprintf(buf, fmt, args);
	va_end(args);
};

static auto w_sprintf_s = [](char* buf, size_t buf_size, const char* fmt, ...) {
	va_list args;
	va_start(args, fmt);
	vsprintf_s(buf, buf_size, fmt, args);
	va_end(args);
};

#define XorStr( s ) ( XorCompileTime::XorString< sizeof( s ) - 1, __COUNTER__ >( s, std::make_index_sequence< sizeof( s ) - 1>() ).decrypt() )

END_NAMESPACE

Solution 7 - Java

You can use DexGuard to encrypt strings, probably more effectively than you could achieve manually, and without burdening the source code.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjaxView Question on Stackoverflow
Solution 1 - JavaMark HibberdView Answer on Stackoverflow
Solution 2 - Javacibercitizen1View Answer on Stackoverflow
Solution 3 - JavaSomeone SomewhereView Answer on Stackoverflow
Solution 4 - Javaw_gView Answer on Stackoverflow
Solution 5 - JavaiuizView Answer on Stackoverflow
Solution 6 - JavaSSpokeView Answer on Stackoverflow
Solution 7 - JavaAhmad RonaghView Answer on Stackoverflow