-1

I use following script to decode a Base64 coded binary content and put it into a string then write to file.

byte[] decoded = slurper.signatureValue.decodeBase64();
String sigValue = new String(decoded)

def path = context.expand('${Properties#outDir}') + context.expand('${Properties#fileName}')
def myFile = new File(path)
myFile.write(sigValue)

When I use Notepad++ with MIME tools plugin to decode it and save it, output is different and not sure, what is difference caused by.

plaidshirt
  • 5,189
  • 19
  • 91
  • 181
  • If it's binary content, why do you put it in a string? And you only mention different results, but you neither show the base64 string nor the different results. – jps Mar 24 '23 at 11:10
  • @jps : I tired also this function: `myFile.bytes = decoded`, but result is not ok. I have just copied Base64 string manually and decoded in Notepad++ and when I compare two files(yes, which are not human readable), I see some extra characters. – plaidshirt Mar 24 '23 at 11:23
  • 1
    Do you have a simple example that reproduced the problem you're seeing? – tim_yates Mar 24 '23 at 11:50
  • @tim_yates : Using this tool: https://iamkate.com/code/binary-file-viewer/ difference is, that question marks are missing from file, which was saved by Groovy script. – plaidshirt Mar 24 '23 at 12:56
  • I'll take that as a no then – tim_yates Mar 24 '23 at 15:43
  • 1
    Normally `new String(decoded, encoding)` should solve your problem where encoding you have to find out. For example it could be `"UTF-8"` – daggett Mar 25 '23 at 06:49
  • 1
    Unfortunately without example value and expected result it's not possible to help. – daggett Mar 25 '23 at 06:50
  • 1
    BTW, when you are writing to file you also could specify encoding - file holds bytes... – daggett Mar 25 '23 at 06:53
  • 1
    As you already noticed your self the error is `new String(decoded)`. Since `decoded` is binary data, trying to handle it as a String will always cause problems. Your best bet is to never get `String` involved and write `decoded` directly to the file (as you did in your self-answer). – Joachim Sauer Mar 27 '23 at 08:54

1 Answers1

1

The following code produces valid(same as Notepad++ plugin) value:

byte[] decoded = Base64.getDecoder().decode(slurper.signatureValue);
myFile.bytes = decoded
plaidshirt
  • 5,189
  • 19
  • 91
  • 181