Aşağıdaki örnekte bir String önce encode edilmiş, daha sonra da decode edilmiştir:
import java.io.UnsupportedEncodingException;
import java.util.Base64;
public class Base64Test {
public static void main(String[] args) throws UnsupportedEncodingException {
String text = "Fibiler";
String encoded = Base64.getEncoder().encodeToString(text.getBytes("utf-8"));
System.out.println(encoded); // RmliaWxlcg==
byte[] decoded = Base64.getDecoder().decode(encoded);
System.out.println(new String(decoded, "utf-8"));
}
}
Base64 sınıfı Java 8 ile birlikte gelen bir sınıftır.
Base64 gibi Base32 ile de encode ve decode yapılabilir. Standart Java'da Base32 sınıfı bulunmaz. Bu örneği Apache'in Common Codec projesi ile de yapabiliriz :
import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.binary.Base32;
public class CommonCodecBase32Test {
public static void main(String[] args) throws UnsupportedEncodingException {
String text = "Fibiler";
Base32 base32 = new Base32();
String encoded = base32.encodeToString(text.getBytes("utf-8"));
System.out.println(encoded); // IZUWE2LMMVZA====
byte[] decoded = base32.decode(encoded);
System.out.println(new String(decoded, "utf-8"));
}
}
Apache Common Codec projesi için Maven için aşağıdaki bağımlılık eklenmelidir:
<!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
Apache Codec yerine Guava kütüphanesi de kullanılabilir:
import java.io.UnsupportedEncodingException;
import com.google.common.io.BaseEncoding;
public class GuavaBase32Test {
public static void main(String[] args) throws UnsupportedEncodingException {
String text = "Fibiler";
BaseEncoding base32 = BaseEncoding.base32();
String encoded = base32.encode(text.getBytes("utf-8"));
System.out.println(encoded); // IZUWE2LMMVZA====
byte[] decoded = base32.decode(encoded);
System.out.println(new String(decoded, "utf-8"));
}
}
Guava için Maven'e aşağıdaki bağımlılığı ekleyebilirsiniz :
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>