0

Currently I'm using com.google.common.io.BaseEncoding class and running following command on Scala REPL to encode the array of bytes like this:

scala> com.google.common.io.BaseEncoding.base64().encode(Array.fill(16)((scala.util.Random.nextInt(256) - 128).toByte))
res5: String = zb6fgtoW404V259DLCg5sQ==

So far I've created some shell script for it:

#!/bin/bash
max_count=16
count=1
while [ "$count" -le $max_count ];
do
  vector[$count]=$((RANDOM%256-128))
  count=$((count+1))
done

echo $(IFS=' '; (echo "${vector[*]}") | base64) | tr -d ' '

But I want to create same logic as BaseEncoding.base64().encode() method. Is it possible to convert array of bytes to encoded base64 string on Bash?

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
Azik
  • 169
  • 1
  • 1
  • 10
  • Using Bash for this is unusually ill-advised but piping to `base64` obviously trivially accomplishes this. Putting the bytes in an array is wacky but `printf '%s' "${array[@]}"` trivially prints the bytes back out. – tripleee May 23 '18 at 12:46
  • What is not working with the code you posted? – Micha Wiedenmann May 23 '18 at 12:48
  • The problem is my code converts string not array of bytes, so when I run First code above with `Array(-62, 20, -56, -91, -122, 74, 77, -38, 83, -110, -77, -53, -110, -114, -72, -57)` the result is `whTIpYZKTdpTkrPLko64xw==`, but my scripts result is `LTYyLDIwLC01NiwtOTEsLTEyMiw3NCw3NywtMzgsODMsLTExMCwtNzcsLTUzLC0xMTAsLTExNCwtNzIsLTU3Cg=="` . So they are not same. – Azik May 23 '18 at 12:58

0 Answers0