Last active
April 2, 2023 10:10
-
-
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/3f85c74c966980fc7b4bfbb2878c78a52e2a2807
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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.1.1" | |
//> 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