]> WPIA git - gigi.git/blob - src/org/cacert/gigi/util/PEM.java
Fix: hide shady regex and mark it as regex clearly.
[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 + "-----", "").replace("\n", "").replace("\r", "");
18         // Remove the first and last lines
19         data = data.replaceAll("-----END " + type + "-----", "");
20         // Base64 decode the data
21         return Base64.getDecoder().decode(data);
22
23     }
24
25     public static String formatBase64(byte[] bytes) {
26         return LINE.matcher(Base64.getEncoder().encodeToString(bytes)).replaceAll("$1\n");
27     }
28 }