]> WPIA git - gigi.git/blob - src/org/cacert/gigi/util/PEM.java
fix: ResultSet.getDate is often wrong as it fetches day-precision times
[gigi.git] / src / org / cacert / gigi / util / PEM.java
1 package org.cacert.gigi.util;
2
3 import java.util.Base64;
4 import java.util.regex.Pattern;
5
6 public class PEM {
7
8     public static final Pattern LINE = Pattern.compile("(.{64})(?=.)");
9
10     public static String encode(String type, byte[] data) {
11         return "-----BEGIN " + type + "-----\n" + //
12                 formatBase64(data) + //
13                 "\n-----END " + type + "-----";
14     }
15
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);
23
24     }
25
26     public static String formatBase64(byte[] bytes) {
27         return LINE.matcher(Base64.getEncoder().encodeToString(bytes)).replaceAll("$1\n");
28     }
29 }