001/*
002 * Copyright 2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package com.revetsec.saml;
017
018import com.revetsec.internal.pem.Pem;
019import com.revetsec.internal.pem.PemException;
020import org.jspecify.annotations.NonNull;
021import javax.annotation.concurrent.Immutable;
022import java.security.Key;
023import java.security.KeyStore;
024import java.security.KeyStoreException;
025import java.security.NoSuchAlgorithmException;
026import java.security.PrivateKey;
027import java.security.UnrecoverableKeyException;
028import java.security.cert.X509Certificate;
029import java.security.cert.CertificateEncodingException;
030import java.security.interfaces.RSAPrivateKey;
031import java.security.interfaces.RSAPublicKey;
032import java.util.Objects;
033
034/**
035 * An RSA private key paired with its public X.509 certificate for SAML signing or decryption.
036 * The application owns key storage and rotation; Revetsec retains no mutable key provider state.
037 *
038 * @since 1.0.0
039 */
040@Immutable
041public final class SamlCredential {
042    private final @NonNull PrivateKey key;
043    private final @NonNull X509Certificate certificate;
044
045    private SamlCredential(@NonNull PrivateKey key, @NonNull X509Certificate certificate) {
046        this.key = key;
047        this.certificate = certificate;
048    }
049
050    /**
051     * Pairs an RSA private key with a matching RSA certificate.
052     *
053     * @param key private key, at least 2048 bits
054     * @param certificate certificate with the matching RSA modulus
055     * @return immutable credential
056     * @since 1.0.0
057     */
058    public static @NonNull SamlCredential fromPrivateKeyAndCertificate(@NonNull PrivateKey key,
059            @NonNull X509Certificate certificate) {
060        Objects.requireNonNull(key);
061        Objects.requireNonNull(certificate);
062        if (!(key instanceof RSAPrivateKey privateRsa)
063                || !(certificate.getPublicKey() instanceof RSAPublicKey publicRsa)
064                || privateRsa.getModulus().bitLength() < 2048
065                || !privateRsa.getModulus().equals(publicRsa.getModulus()))
066            throw new IllegalArgumentException("Unsupported or mismatched SAML credential");
067        return new SamlCredential(key, copyCertificate(certificate));
068    }
069
070    /**
071     * Loads an RSA key pair from an application-owned KeyStore.
072     *
073     * @param store key store
074     * @param alias key entry alias
075     * @param password entry password
076     * @return matching credential
077     * @since 1.0.0
078     */
079    public static @NonNull SamlCredential fromKeyStore(@NonNull KeyStore store, @NonNull String alias,
080            char @NonNull [] password) {
081        Objects.requireNonNull(store);
082        Objects.requireNonNull(alias);
083        Objects.requireNonNull(password);
084        try {
085            Key key = store.getKey(alias, password);
086            java.security.cert.Certificate certificate = store.getCertificate(alias);
087            if (!(key instanceof PrivateKey privateKey) || !(certificate instanceof X509Certificate x509))
088                throw new IllegalArgumentException("SAML key entry unavailable");
089            return fromPrivateKeyAndCertificate(privateKey, x509);
090        } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException exception) {
091            throw new IllegalArgumentException("SAML key entry unavailable", exception);
092        }
093    }
094
095    /**
096     * Loads an unencrypted PKCS#8 or PKCS#1 RSA private key and one X.509 certificate from
097     * separate PEM blocks. Invalid armor, DER, key strength or key pairing fails closed.
098     *
099     * @param privateKeyPem one private key PEM block
100     * @param certificatePem one certificate PEM block
101     * @return matching credential
102     * @since 1.0.0
103     */
104    public static @NonNull SamlCredential fromPem(@NonNull String privateKeyPem,
105            @NonNull String certificatePem) {
106        Objects.requireNonNull(privateKeyPem);
107        Objects.requireNonNull(certificatePem);
108        try {
109            return fromPrivateKeyAndCertificate(Pem.parsePrivateKey(privateKeyPem),
110                    Pem.parseCertificate(certificatePem));
111        } catch (PemException exception) {
112            throw new IllegalArgumentException("Invalid SAML PEM credential");
113        }
114    }
115
116    /**
117     * Returns the certificate for SP metadata.
118     *
119     * @return X.509 certificate
120     * @since 1.0.0
121     */
122    public @NonNull X509Certificate getCertificate() { return copyCertificate(certificate); }
123    @NonNull PrivateKey privateKey() { return key; }
124
125    private static @NonNull X509Certificate copyCertificate(@NonNull X509Certificate certificate) {
126        try { return Pem.parseCertificateDer(certificate.getEncoded()); }
127        catch (CertificateEncodingException | PemException exception) {
128            throw new IllegalArgumentException("Invalid SAML certificate");
129        }
130    }
131    /**
132     * Redacts key material.
133     *
134     * @return redacted description
135     * @since 1.0.0
136     */
137    @Override public @NonNull String toString() { return "SamlCredential{<redacted>}"; }
138}