arrayssmali

How to convert a byte array to hex string?


I have the following code:

sget-object v5, Lkotlin/text/Charsets;->UTF_8:Ljava/nio/charset/Charset;

invoke-static {v4, v2}, Ljava/util/Objects;->requireNonNull(Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/Object;

invoke-virtual {v4, v5}, Ljava/lang/String;->getBytes(Ljava/nio/charset/Charset;)[B

move-result-object v4

and now I need to convert v4 to a hex string in order to log it into Logcat in Android Studio, since i can't log bytes. How would I do that?


Solution

  • An easy way to convert byte[] to String is using BigInteger:

    String s = new BigInteger(1, data).toString(16);
    

    In smali you need two additional registers (or two registers that can be overwritten). In the following code v1 and v2 is used. The byte array has to be present in v4:

    new-instance v1, Ljava/math/BigInteger;
    
    const/4 v2, 0x1  # interpret the byte array as positive number
    
    invoke-direct {v1, v2, v4}, Ljava/math/BigInteger;-><init>(I[B)V
    
    const/16 v2, 0x10     # Output base 16 = hexadeximal
    
    invoke-virtual {v1, v2}, Ljava/math/BigInteger;->toString(I)Ljava/lang/String;
    
    move-result-object v1
    
    # The hex-string is now in v1
    
    # Let's log the value
    const-string v2, "TAG"
    
    invoke-static {v2, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I
    

    There is a very simple way to generate such smali code yourself:

    Take an any app you have the Android Studio source code of or create a new Android project using Android Studio. Add a method in the main activity and paste the java code you want the smali code of. Now compile the app to an APK and open it in Jadx. Seelct the activity class you have added the method to switch to the Smali view. Now you can simply copy the samli code, just some registers may have to be adapted (e.g. inthis case the v4 registers which has the byte[] input.