cert-signer.git

ref: 67d392d7d1d1d64c6ebfa60892d83f47a6d57c07

src/main/java/net/lulli/certsigner/util/Serde.java


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
/* 
 * This file is part of cert-signer
 * Copyright (c) 2024 Paolo Lulli.
 * 
 * This program is free software: you can redistribute it and/or modify  
 * it under the terms of the GNU General Public License as published by  
 * the Free Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package net.lulli.certsigner.util;

import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class Serde {
    private Serde() {
    }

    public static void toFile(PublicKey key, String fileName) {
        try {
            var pem = toPem(key);
            Files.write(Paths.get(fileName), pem.getBytes());
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage());
        }
    }

    public static void toFile(PrivateKey key, String fileName) {
        try {
            var pem = toPem(key);
            Files.write(Paths.get(fileName), pem.getBytes());
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage());
        }
    }

    public static X509Certificate certificateFromFile(String fileName) {
        try {
            var keyContent = Files.readString(Paths.get(fileName));
            return readX509Certificate(keyContent);
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage());
        }
    }

    public static PublicKey publicKeyFromFile(String fileName) {
        try {
            var keyContent = Files.readString(Paths.get(fileName));
            return readX509PublicKey(keyContent);
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage());
        }
    }

    public static PrivateKey privateKeyFromFile(String fileName) {
        try {
            var keyContent = Files.readString(Paths.get(fileName));
            return readPKCS8PrivateKey(keyContent);
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage());
        }
    }

    public static String toPem(PrivateKey privateKey) {
        try {
            Writer out = new StringWriter();
            out.write("-----BEGIN RSA PRIVATE KEY-----\n");
            writeBase64(out, privateKey);
            out.write("-----END RSA PRIVATE KEY-----\n");

            return out.toString();
        } catch (Exception e) {
            return null;
        }
    }

    public static String toPem(PublicKey publicKey) {
        try {
            Writer out = new StringWriter();
            out.write("-----BEGIN RSA PUBLIC KEY-----\n");
            writeBase64(out, publicKey);
            out.write("-----END RSA PUBLIC KEY-----\n");

            return out.toString();
        } catch (Exception e) {
            return null;
        }
    }

    static private void writeBase64(Writer out, Key key) throws java.io.IOException {
        byte[] buf = key.getEncoded();
        out.write(Base64.getEncoder().encodeToString(buf));
        out.write("\n");
    }


    public static X509Certificate readX509Certificate(String certificate) throws Exception {
        InputStream targetStream = new ByteArrayInputStream(certificate.getBytes());
        return (X509Certificate) CertificateFactory
                .getInstance("X509")
                .generateCertificate(targetStream);
    }

    public static RSAPublicKey readX509PublicKey(String key) throws Exception {
        String publicKeyPEM = key
                .replace("-----BEGIN PUBLIC KEY-----", "")
                .replaceAll(System.lineSeparator(), "")
                .replace("-----END PUBLIC KEY-----", "");

        byte[] encoded = Base64.getDecoder().decode(publicKeyPEM);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encoded);
        return (RSAPublicKey) keyFactory.generatePublic(keySpec);
    }

    public static RSAPrivateKey readPKCS8PrivateKey(String key) throws Exception {
        String privateKeyPEM = key
                .replace("-----BEGIN RSA PRIVATE KEY-----", "")
                .replaceAll(System.lineSeparator(), "")
                .replace("-----END RSA PRIVATE KEY-----", "");

        byte[] encoded = Base64.getDecoder().decode(privateKeyPEM);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
        return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    }

    public static PKCS10CertificationRequest pemToCsr(String pem) {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        PKCS10CertificationRequest csr = null;
        ByteArrayInputStream pemStream = null;
        try {
            pemStream = new ByteArrayInputStream(pem.getBytes("UTF-8"));
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }

        Reader pemReader = new BufferedReader(new InputStreamReader(pemStream));
        PEMParser pemParser = new PEMParser(pemReader);

        try {
            Object parsedObj = pemParser.readObject();
            if (parsedObj instanceof PKCS10CertificationRequest) {
                csr = (PKCS10CertificationRequest) parsedObj;
            }
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
        return csr;
    }
}