1 package org.cacert.gigi.util;
3 import java.util.Base64;
4 import java.util.regex.Pattern;
8 public static final Pattern LINE = Pattern.compile("(.{64})(?=.)");
10 public static String encode(String type, byte[] data) {
11 return "-----BEGIN " + type + "-----\n" + //
12 formatBase64(data) + //
13 "\n-----END " + type + "-----";
16 public static byte[] decode(String type, String data) {
17 data = data.replaceAll("-----BEGIN " + type + "-----", "");
18 // Remove the first and last lines
19 data = data.replaceAll("-----END " + type + "-----", "");
20 data = data.replace("\n", "").replace("\r", "").replace(" ", "").replace("\t", "");
21 // Base64 decode the data
22 return Base64.getDecoder().decode(data);
26 public static String formatBase64(byte[] bytes) {
27 return LINE.matcher(Base64.getEncoder().encodeToString(bytes)).replaceAll("$1\n");