Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 25, 2024 10:20
Show Gist options
  • Save dacr/c57ad5fc9ca46690c8e1a5a8e8dd9695 to your computer and use it in GitHub Desktop.
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/20fa346ce60cf75b1520d28d23edac6a9feaff52
// summary : encode/decode base64 with charset management
// keywords : base64, encode, decode, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// 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