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 */
016
017package com.revetsec;
018
019import com.revetsec.internal.crypto.EcCurve;
020import com.revetsec.internal.crypto.EcPublicKeys;
021import com.revetsec.internal.crypto.EcdsaSignatures;
022import com.revetsec.internal.crypto.Ed25519PublicKeys;
023import com.revetsec.internal.crypto.HashAlgorithm;
024import com.revetsec.internal.crypto.KeyRejectedException;
025import com.revetsec.internal.crypto.RsaPublicKeys;
026import com.revetsec.internal.crypto.SignatureVerifier;
027import com.revetsec.internal.crypto.VerifyResult;
028import com.revetsec.internal.pem.Pem;
029import com.revetsec.internal.pem.PemException;
030import org.jspecify.annotations.NonNull;
031import org.jspecify.annotations.Nullable;
032import com.google.errorprone.annotations.CheckReturnValue;
033import javax.annotation.concurrent.ThreadSafe;
034import java.security.GeneralSecurityException;
035import java.security.KeyFactory;
036import java.security.PrivateKey;
037import java.security.PublicKey;
038import java.security.SecureRandom;
039import java.security.Signature;
040import java.security.cert.X509Certificate;
041import java.security.interfaces.ECPrivateKey;
042import java.security.interfaces.ECPublicKey;
043import java.security.interfaces.EdECPrivateKey;
044import java.security.interfaces.EdECPublicKey;
045import java.security.interfaces.RSAPrivateCrtKey;
046import java.security.interfaces.RSAPublicKey;
047import java.security.spec.NamedParameterSpec;
048import java.security.spec.RSAPublicKeySpec;
049import java.time.Duration;
050import java.util.Arrays;
051import static java.util.Objects.requireNonNull;
052
053/**
054 * Bounded imports of ordinary JCA key material: RSA (2048 through 16384 bits, the existing exponent/ROCA policy),
055 * EC P-256/P-384 and canonical, non-small-order Ed25519 public points. DER is at most 65536 bytes and PEM at most
056 * 98304 characters, checked before copying/decoding; PEM's decoded DER is also bounded before allocation.
057 * <p>
058 * One exact PEM block is accepted, with canonical padded Base64 and matching labels. Public DER is SPKI.
059 * Private material is unencrypted PKCS#8 version 0 without attributes/outer public fields, or two-prime RSA
060 * PKCS#1 version 0. SEC1 armor, encrypted keys, RFC5958 version 1/attributes, P-521, Ed448, XDH and RSA-PSS
061 * containers are outside this profile. EC's inner named parameters must agree with its outer parameters; an
062 * embedded public hint must be a well-formed on-curve point but remains untrusted metadata. Import does not
063 * establish scalar-to-hint or key-pair agreement; use the separate explicit pair check.
064 * <p>
065 * Certificate parsing checks the embedded key profile, not certificate signatures, trust, chains, hostname,
066 * time, revocation or complete inner DER canonicality. Caller input remains unchanged. Owned private DER and
067 * pair-check challenge/signature buffers are erased; provider-owned keys, copies and immutable values remain
068 * under JCA/provider ownership. No method exports private key material or implicitly signs during import.
069 * @author <a href="https://www.revetkn.com">Mark Allen</a>
070 * @since 1.0.0
071 */
072@ThreadSafe
073public final class KeyImports {
074        private static final int MAXIMUM_DER_BYTES = 65_536;
075        private static final int MAXIMUM_PEM_CHARACTERS = 98_304;
076        private KeyImports() { }
077
078        /**
079         * Imports one CERTIFICATE PEM block and checks its embedded key profile, without establishing certificate trust.
080         * @param pem at most 98304 characters
081         * @return the caller-owned parsed certificate
082         * @throws NullPointerException if pem is null
083         * @throws KeyImportException if parsing, size or the selected key profile fails
084         * @since 1.0.0
085         */
086        @CheckReturnValue
087        public static @NonNull X509Certificate certificateFromPem(@NonNull String pem) {
088                checkPem(pem);
089                return load(() -> checkedCertificate(Pem.parseCertificate(pem, MAXIMUM_DER_BYTES)));
090        }
091
092        /**
093         * Imports one DER certificate and checks its embedded key profile, without establishing certificate trust.
094         * @param der at most 65536 bytes; not modified
095         * @return the caller-owned parsed certificate
096         * @throws NullPointerException if der is null
097         * @throws KeyImportException if parsing, size or the selected key profile fails
098         * @since 1.0.0
099         */
100        @CheckReturnValue
101        public static @NonNull X509Certificate certificateFromDer(byte @NonNull [] der) {
102                byte[] owned = snapshot(der);
103                try { return load(() -> checkedCertificate(Pem.parseCertificateDer(owned))); }
104                finally { clear(owned); }
105        }
106
107        /**
108         * Imports one PUBLIC KEY PEM block under the selected public-key profile.
109         * @param pem at most 98304 characters
110         * @return the caller-owned checked JCA key
111         * @throws NullPointerException if pem is null
112         * @throws KeyImportException if parsing, size or the selected key profile fails
113         * @since 1.0.0
114         */
115        @CheckReturnValue
116        public static @NonNull PublicKey publicKeyFromPem(@NonNull String pem) {
117                checkPem(pem); return load(() -> checkedPublic(Pem.parsePublicKey(pem, MAXIMUM_DER_BYTES)));
118        }
119
120        /**
121         * Imports one canonical SubjectPublicKeyInfo DER value under the selected public-key profile.
122         * @param der at most 65536 bytes; not modified
123         * @return the caller-owned checked JCA key
124         * @throws NullPointerException if der is null
125         * @throws KeyImportException if parsing, size or the selected key profile fails
126         * @since 1.0.0
127         */
128        @CheckReturnValue
129        public static @NonNull PublicKey publicKeyFromSpkiDer(byte @NonNull [] der) {
130                byte[] owned = snapshot(der);
131                try { return load(() -> checkedPublic(Pem.parsePublicKeyDer(owned))); }
132                finally { clear(owned); }
133        }
134
135        /**
136         * Imports one PRIVATE KEY or RSA PRIVATE KEY PEM block in the selected unencrypted private-container profile.
137         * @param pem at most 98304 characters
138         * @return the caller-owned decoded JCA key; pair agreement is not established
139         * @throws NullPointerException if pem is null
140         * @throws KeyImportException if parsing, size or the selected key profile fails
141         * @since 1.0.0
142         */
143        @CheckReturnValue
144        public static @NonNull PrivateKey privateKeyFromPem(@NonNull String pem) {
145                checkPem(pem); return load(() -> checkedPrivate(Pem.parsePrivateKey(pem, MAXIMUM_DER_BYTES)));
146        }
147
148        /**
149         * Imports one unencrypted PKCS#8 version 0 key without attributes or an outer public-key field.
150         * @param der at most 65536 bytes; not modified
151         * @return the caller-owned decoded JCA key; pair agreement is not established
152         * @throws NullPointerException if der is null
153         * @throws KeyImportException if parsing, size or the selected key profile fails
154         * @since 1.0.0
155         */
156        @CheckReturnValue
157        public static @NonNull PrivateKey privateKeyFromPkcs8Der(byte @NonNull [] der) {
158                return privateDer(der, false);
159        }
160
161        /**
162         * Imports one two-prime RSA PKCS#1 version 0 private key.
163         * @param der at most 65536 bytes; not modified
164         * @return the caller-owned decoded RSA key; pair agreement is not established
165         * @throws NullPointerException if der is null
166         * @throws KeyImportException if parsing, size or the selected key profile fails
167         * @since 1.0.0
168         */
169        @CheckReturnValue
170        public static @NonNull PrivateKey rsaPrivateKeyFromPkcs1Der(byte @NonNull [] der) {
171                return privateDer(der, true);
172        }
173
174        private static @NonNull PrivateKey privateDer(byte @NonNull [] der, boolean pkcs1) {
175                byte[] owned = snapshot(der);
176                try { return load(() -> checkedPrivate(pkcs1 ? Pem.parseRsaPrivateKeyDer(owned) : Pem.parsePrivateKeyDer(owned))); }
177                finally { clear(owned); }
178        }
179
180        /**
181         * Checks agreement with a fresh 32-byte noncredential challenge, a fresh JCA signer and the independent verifier.
182         * The public key must provide a bounded canonical SPKI encoding; it is reparsed to a checked stable projection.
183         * The private key may remain opaque; its encoding is never requested. No signature or challenge is returned.
184         * One original monotonic budget covers public snapshot, provider/random initialization, signing and verification.
185         * Trusted synchronous providers must cooperate; these checks cannot preempt a blocked provider. No retry occurs.
186         * @param privateKey the caller-owned private key
187         * @param publicKey the caller-owned encodable public key
188         * @param remainingBudget the original remaining budget; nonpositive values are exhausted
189         * @throws NullPointerException if a required argument is null
190         * @throws KeyImportException if the profile, pair, provider, interruption or budget check fails
191         * @since 1.0.0
192         */
193        public static void checkKeyPair(@NonNull PrivateKey privateKey, @NonNull PublicKey publicKey, @NonNull Duration remainingBudget) {
194                requireNonNull(privateKey); requireNonNull(publicKey); requireNonNull(remainingBudget);
195                if (Thread.currentThread().isInterrupted()) throw failure(KeyImportException.Reason.CANCELLED);
196                if (remainingBudget.isNegative() || remainingBudget.isZero()) throw failure(KeyImportException.Reason.BUDGET_EXHAUSTED);
197                Budget deadline = new Budget(remainingBudget);
198                byte[] challenge = new byte[32]; byte @Nullable [] signature = null; byte @Nullable [] jose = null;
199                try {
200                        active(deadline);
201                        PublicKey stable = publicKeyFromSpkiDer(requireNonNull(publicKey.getEncoded()));
202                        active(deadline);
203                        String privateAlgorithm = requireNonNull(privateKey.getAlgorithm());
204                        @Nullable EcCurve curve = stable instanceof ECPublicKey ec ? selectedCurve(ec.getParams()) : null;
205                        if (privateKey instanceof RSAPrivateCrtKey || privateKey instanceof ECPrivateKey || privateKey instanceof EdECPrivateKey)
206                                checkedPrivate(privateKey);
207                        active(deadline);
208                        if (privateKey instanceof ECPrivateKey ec && curve != null && selectedCurve(ec.getParams()) != curve)
209                                throw failure(KeyImportException.Reason.KEY_PAIR_MISMATCH);
210                        if (privateKey instanceof RSAPrivateCrtKey rsa && stable instanceof RSAPublicKey publicRsa
211                                        && (!rsa.getModulus().equals(publicRsa.getModulus())
212                                                        || !rsa.getPublicExponent().equals(publicRsa.getPublicExponent())))
213                                throw failure(KeyImportException.Reason.KEY_PAIR_MISMATCH);
214                        if (!(privateAlgorithm.equals("RSA") || privateAlgorithm.equals("EC") || privateAlgorithm.equals("Ed25519") || privateAlgorithm.equals("EdDSA")))
215                                throw failure(KeyImportException.Reason.UNSUPPORTED_KEY);
216                        String algorithm = stable instanceof RSAPublicKey ? "SHA256withRSA" : curve != null
217                                        ? (curve == EcCurve.P_256 ? "SHA256withECDSA" : "SHA384withECDSA") : "Ed25519";
218                        if (!(stable instanceof RSAPublicKey ? privateAlgorithm.equals("RSA") : curve != null
219                                        ? privateAlgorithm.equals("EC") : privateAlgorithm.equals("Ed25519") || privateAlgorithm.equals("EdDSA")))
220                                throw failure(KeyImportException.Reason.KEY_PAIR_MISMATCH);
221                        active(deadline);
222                        SecureRandom random = pairRandom();
223                        active(deadline); random.nextBytes(challenge); active(deadline);
224                        Signature signer = Signature.getInstance(algorithm);
225                        active(deadline); signer.initSign(privateKey, random); active(deadline);
226                        signer.update(challenge); active(deadline);
227                        signature = requireNonNull(signer.sign()); active(deadline);
228                        if (signature.length > RsaPublicKeys.MAXIMUM_SIGNATURE_LENGTH) throw failure(KeyImportException.Reason.OPERATION_UNAVAILABLE);
229                        VerifyResult result;
230                        if (curve != null) {
231                                try { jose = EcdsaSignatures.toJose(curve, signature); }
232                                catch (IllegalArgumentException mismatch) { throw failure(KeyImportException.Reason.KEY_PAIR_MISMATCH); }
233                                active(deadline);
234                                result = SignatureVerifier.verifyEcdsa(curve, curve == EcCurve.P_256 ? HashAlgorithm.SHA_256 : HashAlgorithm.SHA_384, stable, challenge, jose);
235                        } else if (stable instanceof RSAPublicKey) result = SignatureVerifier.verifyRsaPkcs1(HashAlgorithm.SHA_256, stable, challenge, signature);
236                        else result = SignatureVerifier.verifyEd25519(stable, challenge, signature);
237                        active(deadline);
238                        // The signature is produced locally from a normalized private-key algorithm. Shape,
239                        // range and verification failures therefore establish a mismatch; only a JCA/provider
240                        // failure remains an operational outage.
241                        if (result != VerifyResult.VALID) throw failure(result == VerifyResult.PROVIDER_FAILURE
242                                        ? KeyImportException.Reason.OPERATION_UNAVAILABLE : KeyImportException.Reason.KEY_PAIR_MISMATCH);
243                } catch (KeyImportException failure) { active(deadline); throw failure; }
244                catch (KeyRejectedException rejected) { active(deadline); throw failure(KeyImportException.Reason.KEY_REJECTED); }
245                catch (GeneralSecurityException | RuntimeException providerFailure) {
246                        active(deadline); throw failure(KeyImportException.Reason.OPERATION_UNAVAILABLE);
247                } finally { clear(challenge); clear(signature); clear(jose); }
248        }
249
250        private static @NonNull X509Certificate checkedCertificate(@NonNull X509Certificate certificate) throws KeyRejectedException, GeneralSecurityException {
251                checkedPublic(certificate.getPublicKey()); return certificate;
252        }
253
254        private static @NonNull PublicKey checkedPublic(@NonNull PublicKey key) throws KeyRejectedException {
255                if (key instanceof RSAPublicKey rsa) {
256                        if (!"RSA".equals(rsa.getAlgorithm()) || rsa.getParams() != null)
257                                throw failure(KeyImportException.Reason.UNSUPPORTED_KEY);
258                        RsaPublicKeys.checkPublicKey(rsa);
259                } else if (key instanceof ECPublicKey ec) EcPublicKeys.checkPublicKey(selectedCurve(ec.getParams()), ec);
260                else if (key instanceof EdECPublicKey ed) {
261                        if (!NamedParameterSpec.ED25519.getName().equals(ed.getParams().getName())) throw failure(KeyImportException.Reason.UNSUPPORTED_KEY);
262                        Ed25519PublicKeys.checkPublicKey(ed);
263                } else throw failure(KeyImportException.Reason.UNSUPPORTED_KEY);
264                return key;
265        }
266
267        private static @NonNull PrivateKey checkedPrivate(@NonNull PrivateKey key) throws GeneralSecurityException, KeyRejectedException {
268                if (key instanceof RSAPrivateCrtKey rsa) {
269                        if (rsa.getParams() != null) throw failure(KeyImportException.Reason.UNSUPPORTED_KEY);
270                        checkedPublic(KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(rsa.getModulus(), rsa.getPublicExponent())));
271                } else if (key instanceof ECPrivateKey ec) selectedCurve(ec.getParams());
272                else if (!(key instanceof EdECPrivateKey ed) || !NamedParameterSpec.ED25519.getName().equals(ed.getParams().getName()))
273                        throw failure(KeyImportException.Reason.UNSUPPORTED_KEY);
274                return key;
275        }
276
277        private static @NonNull EcCurve selectedCurve(java.security.spec.@NonNull ECParameterSpec parameters) {
278                EcCurve curve = EcCurve.findByParameterSpec(parameters).orElseThrow(() -> failure(KeyImportException.Reason.UNSUPPORTED_KEY));
279                if (curve == EcCurve.P_521) throw failure(KeyImportException.Reason.UNSUPPORTED_KEY);
280                return curve;
281        }
282
283        private static byte @NonNull [] snapshot(byte @NonNull [] der) {
284                requireNonNull(der);
285                if (der.length > MAXIMUM_DER_BYTES) throw failure(KeyImportException.Reason.INPUT_TOO_LARGE);
286                return der.clone();
287        }
288
289        private static void checkPem(@NonNull String pem) {
290                requireNonNull(pem);
291                if (pem.length() > MAXIMUM_PEM_CHARACTERS) throw failure(KeyImportException.Reason.INPUT_TOO_LARGE);
292        }
293
294        @FunctionalInterface private interface Loader<T> { @NonNull T load() throws PemException, GeneralSecurityException, KeyRejectedException; }
295        private static <T> @NonNull T load(@NonNull Loader<@NonNull T> loader) {
296                try { return loader.load(); }
297                catch (KeyImportException failure) { throw failure; }
298                catch (PemException failure) {
299                        throw failure(switch (failure.getKind()) {
300                                case UNSUPPORTED_ALGORITHM, UNSUPPORTED_LABEL, ENCRYPTED_PRIVATE_KEY, SEC1_PRIVATE_KEY -> KeyImportException.Reason.UNSUPPORTED_KEY;
301                                case INVALID_KEY -> KeyImportException.Reason.KEY_REJECTED;
302                                default -> KeyImportException.Reason.MALFORMED_INPUT;
303                        });
304                } catch (KeyRejectedException failure) { throw failure(KeyImportException.Reason.KEY_REJECTED); }
305                catch (IllegalArgumentException tooLarge) { throw failure(KeyImportException.Reason.INPUT_TOO_LARGE); }
306                catch (GeneralSecurityException | RuntimeException providerFailure) { throw failure(KeyImportException.Reason.OPERATION_UNAVAILABLE); }
307        }
308
309        /** Pure monotonic budget: no dependency on the protocol-restricted HTTP package. */
310        private static final class Budget {
311                private final long start = System.nanoTime();
312                private final long total;
313                private Budget(@NonNull Duration duration) {
314                        long nanos;
315                        try { nanos = duration.toNanos(); } catch (ArithmeticException excessive) { nanos = Long.MAX_VALUE; }
316                        this.total = nanos;
317                }
318                private boolean isExpired() { return System.nanoTime() - this.start >= this.total; }
319        }
320
321        private static void active(@NonNull Budget deadline) {
322                if (Thread.currentThread().isInterrupted()) throw failure(KeyImportException.Reason.CANCELLED);
323                if (deadline.isExpired()) throw failure(KeyImportException.Reason.BUDGET_EXHAUSTED);
324        }
325        /** One trusted provider initialization boundary, entered and exited under the original budget. */
326        private static @NonNull SecureRandom pairRandom() { return new SecureRandom(); }
327        private static void clear(byte @Nullable [] bytes) { if (bytes != null) Arrays.fill(bytes, (byte) 0); }
328        private static @NonNull KeyImportException failure(KeyImportException.@NonNull Reason reason) { return KeyImportException.fromReason(reason); }
329}