Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active February 3, 2026 20:18
Show Gist options
  • Select an option

  • Save dacr/c57ad5fc9ca46690c8e1a5a8e8dd9695 to your computer and use it in GitHub Desktop.

Select an option

Save dacr/c57ad5fc9ca46690c8e1a5a8e8dd9695 to your computer and use it in GitHub Desktop.
encode/decode base64 with charset management / published by https://github.com/dacr/code-examples-manager #502657a0-2da7-4c4f-b7ea-2e26c0e1b9bf/8de817429c1113282e5a9e5260d131a97a1f1f4f
// summary : encode/decode base64 with charset management
// keywords : base64, encode, decode, @testable
// publish : gist
// authors : David Crosson
// license : Apache License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
// id : 502657a0-2da7-4c4f-b7ea-2e26c0e1b9bf
// created-on : 2020-05-31T19:54:52Z
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.4.2"
//> using dep "org.scalatest::scalatest:3.2.10"
// ---------------------
import org.scalatest._
import flatspec._
import matchers._
import java.nio.ByteBuffer
import java.nio.charset.Charset
import java.util.Base64
def b64encode(input:String, charsetName:String="UTF-8"):String = {
Base64.getEncoder.encodeToString(input.getBytes(charsetName))
}
def b64decode(input:String, charsetName:String="UTF-8"):String = {
val bytes = Base64.getDecoder.decode(input.getBytes("US-ASCII"))
Charset.forName(charsetName).decode(ByteBuffer.wrap(bytes)).toString
}
object Base64EncodeDecodeTest extends AnyFlatSpec with should.Matchers {
override def suiteName="Base64EncodeDecodeTest"
"Base64" should "be able to encode and decode" in {
val text = "Lorem Ipsum."
val encoded = b64encode(text)
val textDecoded = b64decode(encoded)
textDecoded shouldBe text
}
}
Base64EncodeDecodeTest.execute()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment