// Copyright 2026 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build go1.27 && !fips140v1.0

package ssh

import (
	
	
	
	
)

// mldsaKeyAlgos are the ML-DSA public key algorithms implemented by this
// package.
var mldsaKeyAlgos = []string{
	KeyAlgoMLDSA44,
	KeyAlgoMLDSA65,
	KeyAlgoMLDSA87,
}

// mldsaCertAlgos are the certificate algorithms for the keys in mldsaKeyAlgos.
var mldsaCertAlgos = []string{
	CertAlgoMLDSA44v01Go,
	CertAlgoMLDSA65v01Go,
	CertAlgoMLDSA87v01Go,
}

var errNotMLDSAKey = errors.New("ssh: not an ML-DSA key")

// mldsaParameters returns the ML-DSA parameter set for the given public key
// algorithm name.
func mldsaParameters( string) (mldsa.Parameters, error) {
	switch  {
	case KeyAlgoMLDSA44:
		return mldsa.MLDSA44(), nil
	case KeyAlgoMLDSA65:
		return mldsa.MLDSA65(), nil
	case KeyAlgoMLDSA87:
		return mldsa.MLDSA87(), nil
	default:
		return mldsa.Parameters{}, fmt.Errorf("ssh: not an ML-DSA algorithm: %q", )
	}
}

// mldsaKeyAlgo returns the public key algorithm name for the given ML-DSA
// parameter set.
func mldsaKeyAlgo( mldsa.Parameters) string {
	switch  {
	case mldsa.MLDSA44():
		return KeyAlgoMLDSA44
	case mldsa.MLDSA65():
		return KeyAlgoMLDSA65
	case mldsa.MLDSA87():
		return KeyAlgoMLDSA87
	default:
		panic("ssh: internal error: unknown ML-DSA parameter set: " + .String())
	}
}

// mldsaPublicKey implements PublicKey for the ML-DSA algorithms of [SSH-MLDSA].
type mldsaPublicKey struct {
	key *mldsa.PublicKey
}

func ( *mldsaPublicKey) () string {
	return mldsaKeyAlgo(.key.Parameters())
}

func parseMLDSA( []byte,  string) ( PublicKey,  []byte,  error) {
	,  := mldsaParameters()
	if  != nil {
		return nil, nil, 
	}

	var  struct {
		 []byte
		     []byte `ssh:"rest"`
	}

	if  := Unmarshal(, &);  != nil {
		return nil, nil, 
	}

	,  := mldsa.NewPublicKey(, .)
	if  != nil {
		return nil, nil, fmt.Errorf("ssh: invalid %s public key: %v", , )
	}

	return &mldsaPublicKey{key: }, ., nil
}

func ( *mldsaPublicKey) () []byte {
	 := struct {
		     string
		 []byte
	}{
		.Type(),
		.key.Bytes(),
	}
	return Marshal(&)
}

func ( *mldsaPublicKey) ( []byte,  *Signature) error {
	if .Format != .Type() {
		return fmt.Errorf("ssh: signature type %q for key type %q", .Format, .Type())
	}
	// nil options select pure ML-DSA with an empty context, as required by
	// [SSH-MLDSA], Sections 6 and 8.
	if  := mldsa.Verify(.key, , .Blob, nil);  != nil {
		return errors.New("ssh: signature did not verify")
	}

	return nil
}

func ( *mldsaPublicKey) () crypto.PublicKey {
	return .key
}

// newMLDSAPublicKey returns a PublicKey wrapping key.
func newMLDSAPublicKey( crypto.PublicKey) (PublicKey, error) {
	,  := .(*mldsa.PublicKey)
	if ! {
		return nil, errNotMLDSAKey
	}
	if  == nil || * == (mldsa.PublicKey{}) {
		return nil, errors.New("ssh: invalid ML-DSA public key")
	}
	return &mldsaPublicKey{key: }, nil
}