tomaswolf commented on code in PR #944:
URL: https://github.com/apache/mina-sshd/pull/944#discussion_r4705198322


##########
sshd-common/src/main/java/org/apache/sshd/common/util/security/mldsa/MLDSAUtils.java:
##########
@@ -0,0 +1,219 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.common.util.security.mldsa;
+
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.security.Key;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.Arrays;
+import java.util.Objects;
+
+import org.apache.sshd.common.util.ValidateUtils;
+import org.apache.sshd.common.util.io.der.ASN1Object;
+import org.apache.sshd.common.util.io.der.DERParser;
+import org.apache.sshd.common.util.io.der.DERWriter;
+import org.apache.sshd.common.util.security.MLDSAParameterSets;
+import org.apache.sshd.common.util.security.SecurityUtils;
+
+/**
+ * Utilities to extract ML-DSA key bytes and construct keys using RFC 9881 
encodings.
+ *
+ * @see    <a href="https://www.rfc-editor.org/rfc/rfc9881";>RFC 9881</a>
+ * @author <a href="mailto:[email protected]";>Apache MINA SSHD Project</a>
+ */
+public final class MLDSAUtils {
+    private static final byte[] OID_PREFIX = { 0x60, (byte) 0x86, 0x48, 0x01, 
0x65, 0x03, 0x04, 0x03 };
+
+    private MLDSAUtils() {
+        throw new UnsupportedOperationException("No instance allowed");
+    }
+
+    /**
+     * Retrieves the parameter set of an ML-DSA key.
+     *
+     * @param  key                     the key
+     * @return                         the parameter set
+     * @throws InvalidKeySpecException if the key is not an ML-DSA key or its 
encoding is invalid
+     */
+    public static MLDSAParameterSets getParameters(Key key) throws 
InvalidKeySpecException {
+        Objects.requireNonNull(key, "No key provided");
+        String algorithm = key.getAlgorithm();
+        MLDSAParameterSets named = MLDSAParameterSets.fromJceName(algorithm);
+        if (named == null
+                && !SecurityUtils.ML_DSA.equalsIgnoreCase(algorithm)
+                && !"MLDSA".equalsIgnoreCase(algorithm)) {
+            throw new InvalidKeySpecException("Not an ML-DSA key: " + 
algorithm);
+        }
+        if (named != null && key.getEncoded() == null) {
+            return named;
+        }
+        try (KeyDERParser encoded = sequence(key.getEncoded())) {
+            if (key instanceof PrivateKey) {
+                encoded.readObject(0x02);
+            }
+            MLDSAParameterSets params = readAlgorithm(encoded);
+            if (named != null && named != params) {
+                throw new InvalidKeySpecException("ML-DSA algorithm and OID 
disagree");
+            }
+            return params;
+        } catch (IOException e) {
+            throw new InvalidKeySpecException("Invalid ML-DSA key encoding", 
e);
+        }
+    }
+
+    /**
+     * Retrieves the raw bytes from an ML-DSA public key.
+     *
+     * @param  key                     the public key
+     * @return                         the raw public key bytes
+     * @throws InvalidKeySpecException if the public key encoding is invalid
+     */
+    public static byte[] getRawBytes(PublicKey key) throws 
InvalidKeySpecException {
+        Objects.requireNonNull(key, "No public key provided");
+        try (KeyDERParser encoded = sequence(key.getEncoded())) {
+            MLDSAParameterSets params = readAlgorithm(encoded);
+            byte[] bits = encoded.readObject(0x03).getValue();
+            encoded.requireEnd();
+            if (bits.length != params.getPublicKeySize() + 1 || bits[0] != 0) {
+                throw new InvalidKeySpecException("Invalid ML-DSA public key 
BIT STRING");
+            }
+            MLDSAParameterSets named = 
MLDSAParameterSets.fromJceName(key.getAlgorithm());
+            if (named != null && named != params) {
+                throw new InvalidKeySpecException("ML-DSA algorithm and OID 
disagree");
+            }
+            return Arrays.copyOfRange(bits, 1, bits.length);
+        } catch (IOException e) {
+            throw new InvalidKeySpecException("Invalid ML-DSA public key 
encoding", e);
+        }
+    }
+
+    /**
+     * Constructs an ML-DSA public key from raw bytes.
+     *
+     * @param  params                   the parameter set
+     * @param  raw                      the raw public key bytes
+     * @return                          the public key
+     * @throws GeneralSecurityException if the bytes have the wrong length or 
the key cannot be constructed
+     */
+    public static PublicKey getPublicKey(MLDSAParameterSets params, byte[] 
raw) throws GeneralSecurityException {
+        Objects.requireNonNull(params, "No ML-DSA parameters provided");
+        requireLength(raw, params.getPublicKeySize(), "public key");
+        byte[] bits = new byte[raw.length + 1];
+        System.arraycopy(raw, 0, bits, 1, raw.length);

Review Comment:
   This array copy can be avoided:
   ```
   private static final byte[] NO_UNUSED_BITS = { 0 };
   ```
   and then below instead of `encode(0x03, bits)` use `encode(0x03, 
NO_UNUSED_BITS, raw)`.



##########
sshd-common/src/main/java/org/apache/sshd/common/util/security/mldsa/MLDSAUtils.java:
##########
@@ -0,0 +1,219 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.common.util.security.mldsa;
+
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.security.Key;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.Arrays;
+import java.util.Objects;
+
+import org.apache.sshd.common.util.ValidateUtils;
+import org.apache.sshd.common.util.io.der.ASN1Object;
+import org.apache.sshd.common.util.io.der.DERParser;
+import org.apache.sshd.common.util.io.der.DERWriter;
+import org.apache.sshd.common.util.security.MLDSAParameterSets;
+import org.apache.sshd.common.util.security.SecurityUtils;
+
+/**
+ * Utilities to extract ML-DSA key bytes and construct keys using RFC 9881 
encodings.
+ *
+ * @see    <a href="https://www.rfc-editor.org/rfc/rfc9881";>RFC 9881</a>
+ * @author <a href="mailto:[email protected]";>Apache MINA SSHD Project</a>
+ */
+public final class MLDSAUtils {
+    private static final byte[] OID_PREFIX = { 0x60, (byte) 0x86, 0x48, 0x01, 
0x65, 0x03, 0x04, 0x03 };
+
+    private MLDSAUtils() {
+        throw new UnsupportedOperationException("No instance allowed");
+    }
+
+    /**
+     * Retrieves the parameter set of an ML-DSA key.
+     *
+     * @param  key                     the key
+     * @return                         the parameter set
+     * @throws InvalidKeySpecException if the key is not an ML-DSA key or its 
encoding is invalid
+     */
+    public static MLDSAParameterSets getParameters(Key key) throws 
InvalidKeySpecException {
+        Objects.requireNonNull(key, "No key provided");
+        String algorithm = key.getAlgorithm();
+        MLDSAParameterSets named = MLDSAParameterSets.fromJceName(algorithm);
+        if (named == null
+                && !SecurityUtils.ML_DSA.equalsIgnoreCase(algorithm)
+                && !"MLDSA".equalsIgnoreCase(algorithm)) {
+            throw new InvalidKeySpecException("Not an ML-DSA key: " + 
algorithm);
+        }
+        if (named != null && key.getEncoded() == null) {
+            return named;
+        }
+        try (KeyDERParser encoded = sequence(key.getEncoded())) {
+            if (key instanceof PrivateKey) {
+                encoded.readObject(0x02);
+            }
+            MLDSAParameterSets params = readAlgorithm(encoded);
+            if (named != null && named != params) {
+                throw new InvalidKeySpecException("ML-DSA algorithm and OID 
disagree");
+            }
+            return params;
+        } catch (IOException e) {
+            throw new InvalidKeySpecException("Invalid ML-DSA key encoding", 
e);
+        }
+    }
+
+    /**
+     * Retrieves the raw bytes from an ML-DSA public key.
+     *
+     * @param  key                     the public key
+     * @return                         the raw public key bytes
+     * @throws InvalidKeySpecException if the public key encoding is invalid
+     */
+    public static byte[] getRawBytes(PublicKey key) throws 
InvalidKeySpecException {
+        Objects.requireNonNull(key, "No public key provided");
+        try (KeyDERParser encoded = sequence(key.getEncoded())) {
+            MLDSAParameterSets params = readAlgorithm(encoded);
+            byte[] bits = encoded.readObject(0x03).getValue();
+            encoded.requireEnd();
+            if (bits.length != params.getPublicKeySize() + 1 || bits[0] != 0) {
+                throw new InvalidKeySpecException("Invalid ML-DSA public key 
BIT STRING");
+            }
+            MLDSAParameterSets named = 
MLDSAParameterSets.fromJceName(key.getAlgorithm());
+            if (named != null && named != params) {
+                throw new InvalidKeySpecException("ML-DSA algorithm and OID 
disagree");
+            }
+            return Arrays.copyOfRange(bits, 1, bits.length);
+        } catch (IOException e) {
+            throw new InvalidKeySpecException("Invalid ML-DSA public key 
encoding", e);
+        }
+    }
+
+    /**
+     * Constructs an ML-DSA public key from raw bytes.
+     *
+     * @param  params                   the parameter set
+     * @param  raw                      the raw public key bytes
+     * @return                          the public key
+     * @throws GeneralSecurityException if the bytes have the wrong length or 
the key cannot be constructed
+     */
+    public static PublicKey getPublicKey(MLDSAParameterSets params, byte[] 
raw) throws GeneralSecurityException {
+        Objects.requireNonNull(params, "No ML-DSA parameters provided");
+        requireLength(raw, params.getPublicKeySize(), "public key");
+        byte[] bits = new byte[raw.length + 1];
+        System.arraycopy(raw, 0, bits, 1, raw.length);
+        try {
+            byte[] encoded = encode(0x30, algorithm(params), encode(0x03, 
bits));

Review Comment:
   Define constants for these magic numbers. TAG_SEQUENCE (0x30), TAG_OID 
(0x06), TAG_BITSTRING (0x03), TAG_INTEGER (0x02) or some such.
   
   Also note: the x509 prefix for these keys is static. Perhaps an approach as 
taken in the ed25519 code where the whole prefixes are static arrays that then 
simply have the raw key bytes appended is simpler than actually writing the 
DER. Which static prefix to use could be determined by the params (for 
instance, public key length).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to