Using:
repositories {
mavenCentral()
}
Add dependency:
dependencies {
implementation 'io.github.novacrypto:Base58:2022.01.17@jar'
}
From simplest to most advanced:
String base58 = Base58.base58Encode(bytes);
byte[] bytes = Base58.base58Decode(base58String);
The static methods are threadsafe as they have a shared buffer per thread. They are named so they are still readable if you import static
.
String base58 = Base58.newInstance().encode(bytes);
byte[] bytes = Base58.newInstance().decode(base58CharSequence);
The instances are not threadsafe, never share an instance across threads.
Either:
final StringBuilder sb = new StringBuilder();
Base58.newSecureInstance().encode(bytes, sb::append);
return sb.toString();
Or let it get told the correct initial maximum size:
final StringBuilder sb = new StringBuilder();
Base58.newSecureInstance().encode(bytes, sb::ensureCapacity, sb::append);
return sb.toString();
Or supply an implementation of EncodeTargetFromCapacity
:
final StringBuilder sb = new StringBuilder();
Base58.newSecureInstance().encode(bytes, (charLength) -> {
// gives you a chance to allocate memory before passing the buffer as an EncodeTarget
sb.ensureCapacity(charLength);
return sb::append; // EncodeTarget
});
return sb.toString();
static class ByteArrayTarget implements DecodeTarget {
private int idx = 0;
byte[] bytes;
@Override
public DecodeWriter getWriterForLength(int len) {
bytes = new byte[len];
return b -> bytes[idx++] = b;
}
}
ByteArrayTarget target = new ByteArrayTarget();
Base58.newSecureInstance().decode(base58, target);
target.bytes;
These advanced usages avoid allocating memory and allow SecureByteBuffer usage.
- Update dependencies
- Add
EncodeTargetFromCapacity
andEncodeTargetCapacity
interfaces and relatedSecureEncoder#encode
method overloads
- uses static
SecureRandom
on the advice of Spotbugs, and while it was a false positive intended forRandom
use warning, it's not a bad thing to do anyway.