]> WPIA git - gigi.git/blobdiff - src/org/cacert/gigi/util/PEM.java
fix: more leasurely decode pem (ignore whitespace)
[gigi.git] / src / org / cacert / gigi / util / PEM.java
index 0616270533ceac10fd0ec63249704842f2fed16f..3be46531dc93bf9d26740399c6e3aa311a47a2ce 100644 (file)
@@ -1,21 +1,29 @@
 package org.cacert.gigi.util;
 
 import java.util.Base64;
+import java.util.regex.Pattern;
 
 public class PEM {
 
+    public static final Pattern LINE = Pattern.compile("(.{64})(?=.)");
+
     public static String encode(String type, byte[] data) {
         return "-----BEGIN " + type + "-----\n" + //
-                Base64.getEncoder().encodeToString(data).replaceAll("(.{64})(?=.)", "$1\n") + //
+                formatBase64(data) + //
                 "\n-----END " + type + "-----";
     }
 
     public static byte[] decode(String type, String data) {
-        data = data.replaceAll("-----BEGIN " + type + "-----", "").replace("\n", "").replace("\r", "");
+        data = data.replaceAll("-----BEGIN " + type + "-----", "");
         // Remove the first and last lines
         data = data.replaceAll("-----END " + type + "-----", "");
+        data = data.replace("\n", "").replace("\r", "").replace(" ", "").replace("\t", "");
         // Base64 decode the data
         return Base64.getDecoder().decode(data);
 
     }
+
+    public static String formatBase64(byte[] bytes) {
+        return LINE.matcher(Base64.getEncoder().encodeToString(bytes)).replaceAll("$1\n");
+    }
 }