【问题标题】:How can I undo this Base64 encoding? (Scala)如何撤消此 Base64 编码? (斯卡拉)
【发布时间】:2022-01-12 21:38:19
【问题描述】:

我有一段代码可以像这样进行一些编码:

def byteBufferToString(b: ByteBuffer): String = java.util.Base64.getEncoder.encodeToString(bb.array)

我还想要另一种相反的方法。以下是我的一些尝试:

def stringToByteBuffer(str: String): ByteBuffer = ByteBuffer.wrap(Base64.getDecoder.decode(str))

def stringToByteBuffer(str: String): ByteBuffer = ByteBuffer.wrap(str.getBytes(Charset.forName("UTF-8"))

def stringToByteBuffer(str: String): ByteBuffer = ByteBuffer.wrap(Base64.getDecoder.decode(str.getBytes(Charset.forName("UTF-8")))

但这些似乎都不满足条件:

byteBufferToString(stringToByteBuffer(testString)) == testString

例如,当 testString 是 abc 时,我会得到类似 = abc= 的东西。有什么想法吗?

【问题讨论】:

标签: string scala encoding base64 bytebuffer


【解决方案1】:

通过将withoutPadding 添加到编码器中,我能够使您的初始测试通过。

import java.nio.ByteBuffer
import java.util.Base64

def byteBufferToString(bb: ByteBuffer): String =
  Base64.getEncoder.withoutPadding.encodeToString(bb.array)

def stringToByteBuffer(str: String): ByteBuffer =
  ByteBuffer.wrap(Base64.getDecoder.decode(str))
//or
//ByteBuffer.wrap(Base64.getDecoder.decode(str.getBytes(java.nio.charset.Charset.forName("UTF-8"))))

val testString = "abc"
byteBufferToString(stringToByteBuffer(testString)) == testString // true

但我认为这不是您真正想要的,因为它不会通过任何/所有测试字符串。

暂时放弃ByteBuffer这个业务,你的testString评价基本就是这个。

val x = Base64.getDecoder.decode("abc")
Base64.getEncoder.encodeToString(x) // abc= (padding)

您首先调用decode,这意味着测试字符串必须是String 表示Base64 编码。并非所有字符串都是。

val x = Base64.getDecoder.decode("abX")
Base64.getEncoder.encodeToString(x)  // abU=

val x = Base64.getDecoder.decode("ab#") //IllegalArgumentException

更有意义的是先encode,然后decode,并将结果转换为String

val y = Base64.getEncoder.encode("any STRING".toArray.map(_.toByte))
Base64.getDecoder.decode(y).map(_.toChar).mkString // any STRING

【讨论】:

    猜你喜欢
    • 2017-10-16
    • 2013-12-16
    • 2020-12-15
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 2011-09-16
    • 2016-01-31
    相关资源
    最近更新 更多