com.hejinonline.util.Base58.scala Maven / Gradle / Ivy
The newest version!
package com.hejinonline.util
import java.math.BigInteger
class InvalidBase58FormatException(reason: String) extends Exception(reason)
object Base58 {
val Digits = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
val Size = Digits.length
def encode(b: Array[Byte]): String = {
var intData = BigInteger.ZERO
for (i <- 0 until b.length) {
intData = intData.multiply(BigInteger.valueOf(256)).add(BigInteger.valueOf(b(i) & 0xFF))
}
var result = ""
while (intData.compareTo(BigInteger.ZERO) > 0) {
val r = intData.mod(BigInteger.valueOf(Size)).intValue()
intData = intData.divide(BigInteger.valueOf(Size))
result = Digits(r).toString + result
}
"1" * b.takeWhile(_ == 0).length + result
}
@throws(classOf[InvalidBase58FormatException])
def decode(s: String): Array[Byte] = {
var intData = BigInteger.ZERO
for (i <- 0 until s.length) {
val digit = Digits.indexOf(s(i))
if (digit < 0)
throw new InvalidBase58FormatException("Invalid character '" + digit + "'")
intData = intData.multiply(BigInteger.valueOf(Size)).add(BigInteger.valueOf(digit))
}
Array.fill[Byte](s.takeWhile(_ == '1').length)(0) ++ intData.toByteArray.dropWhile(_ == 0)
}
}