All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.payingcloud.umf.util.CertUtils Maven / Gradle / Ivy

There is a newer version: 1.0.8
Show newest version
package cn.payingcloud.umf.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

public class CertUtils {
    private CertUtils() {
    }

    public static PrivateKey loadRsaPrivateKey(InputStream stream) {
        return loadRsaPrivateKey(StreamUtils.copyToByteArray(stream));
    }

    public static PrivateKey loadRsaPrivateKey(byte[] bytes) {
        try {
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw new RuntimeException(e);
        }
    }

    public static X509Certificate loadX509Certificate(byte[] bytes) {
        try (InputStream stream = new ByteArrayInputStream(bytes)) {
            return loadX509Certificate(stream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static X509Certificate loadX509Certificate(InputStream stream) {
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            return (X509Certificate) certificateFactory.generateCertificate(stream);
        } catch (CertificateException e) {
            throw new RuntimeException(e);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy