chore: checkpoint before Python removal

This commit is contained in:
2026-03-26 22:33:59 +00:00
parent 683cec9307
commit e568ddf82a
29972 changed files with 11269302 additions and 2 deletions

113
vendor/ssh-key/src/public/dsa.rs vendored Normal file
View File

@@ -0,0 +1,113 @@
//! Digital Signature Algorithm (DSA) public keys.
use crate::{Error, Mpint, Result};
use core::hash::{Hash, Hasher};
use encoding::{CheckedSum, Decode, Encode, Reader, Writer};
/// Digital Signature Algorithm (DSA) public key.
///
/// Described in [FIPS 186-4 § 4.1](https://csrc.nist.gov/publications/detail/fips/186/4/final).
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct DsaPublicKey {
/// Prime modulus.
pub p: Mpint,
/// Prime divisor of `p - 1`.
pub q: Mpint,
/// Generator of a subgroup of order `q` in the multiplicative group
/// `GF(p)`, such that `1 < g < p`.
pub g: Mpint,
/// The public key, where `y = gˣ mod p`.
pub y: Mpint,
}
impl Decode for DsaPublicKey {
type Error = Error;
fn decode(reader: &mut impl Reader) -> Result<Self> {
let p = Mpint::decode(reader)?;
let q = Mpint::decode(reader)?;
let g = Mpint::decode(reader)?;
let y = Mpint::decode(reader)?;
Ok(Self { p, q, g, y })
}
}
impl Encode for DsaPublicKey {
fn encoded_len(&self) -> encoding::Result<usize> {
[
self.p.encoded_len()?,
self.q.encoded_len()?,
self.g.encoded_len()?,
self.y.encoded_len()?,
]
.checked_sum()
}
fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
self.p.encode(writer)?;
self.q.encode(writer)?;
self.g.encode(writer)?;
self.y.encode(writer)
}
}
impl Hash for DsaPublicKey {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.p.as_bytes().hash(state);
self.q.as_bytes().hash(state);
self.g.as_bytes().hash(state);
self.y.as_bytes().hash(state);
}
}
#[cfg(feature = "dsa")]
impl TryFrom<DsaPublicKey> for dsa::VerifyingKey {
type Error = Error;
fn try_from(key: DsaPublicKey) -> Result<dsa::VerifyingKey> {
dsa::VerifyingKey::try_from(&key)
}
}
#[cfg(feature = "dsa")]
impl TryFrom<&DsaPublicKey> for dsa::VerifyingKey {
type Error = Error;
fn try_from(key: &DsaPublicKey) -> Result<dsa::VerifyingKey> {
let components = dsa::Components::from_components(
dsa::BigUint::try_from(&key.p)?,
dsa::BigUint::try_from(&key.q)?,
dsa::BigUint::try_from(&key.g)?,
)?;
dsa::VerifyingKey::from_components(components, dsa::BigUint::try_from(&key.y)?)
.map_err(|_| Error::Crypto)
}
}
#[cfg(feature = "dsa")]
impl TryFrom<dsa::VerifyingKey> for DsaPublicKey {
type Error = Error;
fn try_from(key: dsa::VerifyingKey) -> Result<DsaPublicKey> {
DsaPublicKey::try_from(&key)
}
}
#[cfg(feature = "dsa")]
impl TryFrom<&dsa::VerifyingKey> for DsaPublicKey {
type Error = Error;
fn try_from(key: &dsa::VerifyingKey) -> Result<DsaPublicKey> {
Ok(DsaPublicKey {
p: key.components().p().try_into()?,
q: key.components().q().try_into()?,
g: key.components().g().try_into()?,
y: key.y().try_into()?,
})
}
}

202
vendor/ssh-key/src/public/ecdsa.rs vendored Normal file
View File

@@ -0,0 +1,202 @@
//! Elliptic Curve Digital Signature Algorithm (ECDSA) public keys.
use crate::{Algorithm, EcdsaCurve, Error, Result};
use core::fmt;
use encoding::{CheckedSum, Decode, Encode, Reader, Writer};
use sec1::consts::{U32, U48, U66};
/// ECDSA/NIST P-256 public key.
pub type EcdsaNistP256PublicKey = sec1::EncodedPoint<U32>;
/// ECDSA/NIST P-384 public key.
pub type EcdsaNistP384PublicKey = sec1::EncodedPoint<U48>;
/// ECDSA/NIST P-521 public key.
pub type EcdsaNistP521PublicKey = sec1::EncodedPoint<U66>;
/// Elliptic Curve Digital Signature Algorithm (ECDSA) public key.
///
/// Public keys are represented as [`sec1::EncodedPoint`] and require the
/// `sec1` feature of this crate is enabled (which it is by default).
///
/// Described in [FIPS 186-4](https://csrc.nist.gov/publications/detail/fips/186/4/final).
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum EcdsaPublicKey {
/// NIST P-256 ECDSA public key.
NistP256(EcdsaNistP256PublicKey),
/// NIST P-384 ECDSA public key.
NistP384(EcdsaNistP384PublicKey),
/// NIST P-521 ECDSA public key.
NistP521(EcdsaNistP521PublicKey),
}
impl EcdsaPublicKey {
/// Maximum size of a SEC1-encoded ECDSA public key (i.e. curve point).
///
/// This is the size of 2 * P-521 field elements (2 * 66 = 132) which
/// represent the affine coordinates of a curve point plus one additional
/// byte for the SEC1 "tag" identifying the curve point encoding.
const MAX_SIZE: usize = 133;
/// Parse an ECDSA public key from a SEC1-encoded point.
///
/// Determines the key type from the SEC1 tag byte and length.
pub fn from_sec1_bytes(bytes: &[u8]) -> Result<Self> {
match bytes {
[tag, rest @ ..] => {
let point_size = match sec1::point::Tag::from_u8(*tag)? {
sec1::point::Tag::CompressedEvenY | sec1::point::Tag::CompressedOddY => {
rest.len()
}
sec1::point::Tag::Uncompressed => rest.len() / 2,
_ => return Err(Error::AlgorithmUnknown),
};
match point_size {
32 => Ok(Self::NistP256(EcdsaNistP256PublicKey::from_bytes(bytes)?)),
48 => Ok(Self::NistP384(EcdsaNistP384PublicKey::from_bytes(bytes)?)),
66 => Ok(Self::NistP521(EcdsaNistP521PublicKey::from_bytes(bytes)?)),
_ => Err(encoding::Error::Length.into()),
}
}
_ => Err(encoding::Error::Length.into()),
}
}
/// Borrow the SEC1-encoded key data as bytes.
pub fn as_sec1_bytes(&self) -> &[u8] {
match self {
EcdsaPublicKey::NistP256(point) => point.as_bytes(),
EcdsaPublicKey::NistP384(point) => point.as_bytes(),
EcdsaPublicKey::NistP521(point) => point.as_bytes(),
}
}
/// Get the [`Algorithm`] for this public key type.
pub fn algorithm(&self) -> Algorithm {
Algorithm::Ecdsa {
curve: self.curve(),
}
}
/// Get the [`EcdsaCurve`] for this key.
pub fn curve(&self) -> EcdsaCurve {
match self {
EcdsaPublicKey::NistP256(_) => EcdsaCurve::NistP256,
EcdsaPublicKey::NistP384(_) => EcdsaCurve::NistP384,
EcdsaPublicKey::NistP521(_) => EcdsaCurve::NistP521,
}
}
}
impl AsRef<[u8]> for EcdsaPublicKey {
fn as_ref(&self) -> &[u8] {
self.as_sec1_bytes()
}
}
impl Decode for EcdsaPublicKey {
type Error = Error;
fn decode(reader: &mut impl Reader) -> Result<Self> {
let curve = EcdsaCurve::decode(reader)?;
let mut buf = [0u8; Self::MAX_SIZE];
let key = Self::from_sec1_bytes(reader.read_byten(&mut buf)?)?;
if key.curve() == curve {
Ok(key)
} else {
Err(Error::AlgorithmUnknown)
}
}
}
impl Encode for EcdsaPublicKey {
fn encoded_len(&self) -> encoding::Result<usize> {
[
self.curve().encoded_len()?,
4, // uint32 length prefix
self.as_ref().len(),
]
.checked_sum()
}
fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
self.curve().encode(writer)?;
self.as_ref().encode(writer)?;
Ok(())
}
}
impl fmt::Display for EcdsaPublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self:X}")
}
}
impl fmt::LowerHex for EcdsaPublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for byte in self.as_sec1_bytes() {
write!(f, "{byte:02x}")?;
}
Ok(())
}
}
impl fmt::UpperHex for EcdsaPublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for byte in self.as_sec1_bytes() {
write!(f, "{byte:02X}")?;
}
Ok(())
}
}
macro_rules! impl_ecdsa_for_curve {
($krate:ident, $feature:expr, $curve:ident) => {
#[cfg(feature = $feature)]
impl TryFrom<EcdsaPublicKey> for $krate::ecdsa::VerifyingKey {
type Error = Error;
fn try_from(key: EcdsaPublicKey) -> Result<$krate::ecdsa::VerifyingKey> {
$krate::ecdsa::VerifyingKey::try_from(&key)
}
}
#[cfg(feature = $feature)]
impl TryFrom<&EcdsaPublicKey> for $krate::ecdsa::VerifyingKey {
type Error = Error;
fn try_from(public_key: &EcdsaPublicKey) -> Result<$krate::ecdsa::VerifyingKey> {
match public_key {
EcdsaPublicKey::$curve(key) => {
$krate::ecdsa::VerifyingKey::from_encoded_point(key)
.map_err(|_| Error::Crypto)
}
_ => Err(Error::AlgorithmUnknown),
}
}
}
#[cfg(feature = $feature)]
impl From<$krate::ecdsa::VerifyingKey> for EcdsaPublicKey {
fn from(key: $krate::ecdsa::VerifyingKey) -> EcdsaPublicKey {
EcdsaPublicKey::from(&key)
}
}
#[cfg(feature = $feature)]
impl From<&$krate::ecdsa::VerifyingKey> for EcdsaPublicKey {
fn from(key: &$krate::ecdsa::VerifyingKey) -> EcdsaPublicKey {
EcdsaPublicKey::$curve(key.to_encoded_point(false))
}
}
};
}
impl_ecdsa_for_curve!(p256, "p256", NistP256);
impl_ecdsa_for_curve!(p384, "p384", NistP384);
impl_ecdsa_for_curve!(p521, "p521", NistP521);

108
vendor/ssh-key/src/public/ed25519.rs vendored Normal file
View File

@@ -0,0 +1,108 @@
//! Ed25519 public keys.
//!
//! Edwards Digital Signature Algorithm (EdDSA) over Curve25519.
use crate::{Error, Result};
use core::fmt;
use encoding::{CheckedSum, Decode, Encode, Reader, Writer};
/// Ed25519 public key.
// TODO(tarcieri): use `ed25519::PublicKey`? (doesn't exist yet)
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct Ed25519PublicKey(pub [u8; Self::BYTE_SIZE]);
impl Ed25519PublicKey {
/// Size of an Ed25519 public key in bytes.
pub const BYTE_SIZE: usize = 32;
}
impl AsRef<[u8; Self::BYTE_SIZE]> for Ed25519PublicKey {
fn as_ref(&self) -> &[u8; Self::BYTE_SIZE] {
&self.0
}
}
impl Decode for Ed25519PublicKey {
type Error = Error;
fn decode(reader: &mut impl Reader) -> Result<Self> {
let mut bytes = [0u8; Self::BYTE_SIZE];
reader.read_prefixed(|reader| reader.read(&mut bytes))?;
Ok(Self(bytes))
}
}
impl Encode for Ed25519PublicKey {
fn encoded_len(&self) -> encoding::Result<usize> {
[4, Self::BYTE_SIZE].checked_sum()
}
fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
self.0.encode(writer)?;
Ok(())
}
}
impl TryFrom<&[u8]> for Ed25519PublicKey {
type Error = Error;
fn try_from(bytes: &[u8]) -> Result<Self> {
Ok(Self(bytes.try_into()?))
}
}
impl fmt::Display for Ed25519PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self:X}")
}
}
impl fmt::LowerHex for Ed25519PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for byte in self.as_ref() {
write!(f, "{byte:02x}")?;
}
Ok(())
}
}
impl fmt::UpperHex for Ed25519PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for byte in self.as_ref() {
write!(f, "{byte:02X}")?;
}
Ok(())
}
}
#[cfg(feature = "ed25519")]
impl TryFrom<Ed25519PublicKey> for ed25519_dalek::VerifyingKey {
type Error = Error;
fn try_from(key: Ed25519PublicKey) -> Result<ed25519_dalek::VerifyingKey> {
ed25519_dalek::VerifyingKey::try_from(&key)
}
}
#[cfg(feature = "ed25519")]
impl TryFrom<&Ed25519PublicKey> for ed25519_dalek::VerifyingKey {
type Error = Error;
fn try_from(key: &Ed25519PublicKey) -> Result<ed25519_dalek::VerifyingKey> {
ed25519_dalek::VerifyingKey::from_bytes(key.as_ref()).map_err(|_| Error::Crypto)
}
}
#[cfg(feature = "ed25519")]
impl From<ed25519_dalek::VerifyingKey> for Ed25519PublicKey {
fn from(key: ed25519_dalek::VerifyingKey) -> Ed25519PublicKey {
Ed25519PublicKey::from(&key)
}
}
#[cfg(feature = "ed25519")]
impl From<&ed25519_dalek::VerifyingKey> for Ed25519PublicKey {
fn from(key: &ed25519_dalek::VerifyingKey) -> Ed25519PublicKey {
Ed25519PublicKey(key.to_bytes())
}
}

301
vendor/ssh-key/src/public/key_data.rs vendored Normal file
View File

@@ -0,0 +1,301 @@
//! Public key data.
use super::{Ed25519PublicKey, SkEd25519};
use crate::{Algorithm, Error, Fingerprint, HashAlg, Result};
use encoding::{CheckedSum, Decode, Encode, Reader, Writer};
#[cfg(feature = "alloc")]
use super::{DsaPublicKey, OpaquePublicKey, RsaPublicKey};
#[cfg(feature = "ecdsa")]
use super::{EcdsaPublicKey, SkEcdsaSha2NistP256};
/// Public key data.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum KeyData {
/// Digital Signature Algorithm (DSA) public key data.
#[cfg(feature = "alloc")]
Dsa(DsaPublicKey),
/// Elliptic Curve Digital Signature Algorithm (ECDSA) public key data.
#[cfg(feature = "ecdsa")]
Ecdsa(EcdsaPublicKey),
/// Ed25519 public key data.
Ed25519(Ed25519PublicKey),
/// RSA public key data.
#[cfg(feature = "alloc")]
Rsa(RsaPublicKey),
/// Security Key (FIDO/U2F) using ECDSA/NIST P-256 as specified in [PROTOCOL.u2f].
///
/// [PROTOCOL.u2f]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.u2f?annotate=HEAD
#[cfg(feature = "ecdsa")]
SkEcdsaSha2NistP256(SkEcdsaSha2NistP256),
/// Security Key (FIDO/U2F) using Ed25519 as specified in [PROTOCOL.u2f].
///
/// [PROTOCOL.u2f]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.u2f?annotate=HEAD
SkEd25519(SkEd25519),
/// Opaque public key data.
#[cfg(feature = "alloc")]
Other(OpaquePublicKey),
}
impl KeyData {
/// Get the [`Algorithm`] for this public key.
pub fn algorithm(&self) -> Algorithm {
match self {
#[cfg(feature = "alloc")]
Self::Dsa(_) => Algorithm::Dsa,
#[cfg(feature = "ecdsa")]
Self::Ecdsa(key) => key.algorithm(),
Self::Ed25519(_) => Algorithm::Ed25519,
#[cfg(feature = "alloc")]
Self::Rsa(_) => Algorithm::Rsa { hash: None },
#[cfg(feature = "ecdsa")]
Self::SkEcdsaSha2NistP256(_) => Algorithm::SkEcdsaSha2NistP256,
Self::SkEd25519(_) => Algorithm::SkEd25519,
#[cfg(feature = "alloc")]
Self::Other(key) => key.algorithm(),
}
}
/// Get DSA public key if this key is the correct type.
#[cfg(feature = "alloc")]
pub fn dsa(&self) -> Option<&DsaPublicKey> {
match self {
Self::Dsa(key) => Some(key),
_ => None,
}
}
/// Get ECDSA public key if this key is the correct type.
#[cfg(feature = "ecdsa")]
pub fn ecdsa(&self) -> Option<&EcdsaPublicKey> {
match self {
Self::Ecdsa(key) => Some(key),
_ => None,
}
}
/// Get Ed25519 public key if this key is the correct type.
pub fn ed25519(&self) -> Option<&Ed25519PublicKey> {
match self {
Self::Ed25519(key) => Some(key),
#[allow(unreachable_patterns)]
_ => None,
}
}
/// Compute key fingerprint.
///
/// Use [`Default::default()`] to use the default hash function (SHA-256).
pub fn fingerprint(&self, hash_alg: HashAlg) -> Fingerprint {
Fingerprint::new(hash_alg, self)
}
/// Get RSA public key if this key is the correct type.
#[cfg(feature = "alloc")]
pub fn rsa(&self) -> Option<&RsaPublicKey> {
match self {
Self::Rsa(key) => Some(key),
_ => None,
}
}
/// Get FIDO/U2F ECDSA/NIST P-256 public key if this key is the correct type.
#[cfg(feature = "ecdsa")]
pub fn sk_ecdsa_p256(&self) -> Option<&SkEcdsaSha2NistP256> {
match self {
Self::SkEcdsaSha2NistP256(sk) => Some(sk),
_ => None,
}
}
/// Get FIDO/U2F Ed25519 public key if this key is the correct type.
pub fn sk_ed25519(&self) -> Option<&SkEd25519> {
match self {
Self::SkEd25519(sk) => Some(sk),
_ => None,
}
}
/// Get the custom, opaque public key if this key is the correct type.
#[cfg(feature = "alloc")]
pub fn other(&self) -> Option<&OpaquePublicKey> {
match self {
Self::Other(key) => Some(key),
_ => None,
}
}
/// Is this key a DSA key?
#[cfg(feature = "alloc")]
pub fn is_dsa(&self) -> bool {
matches!(self, Self::Dsa(_))
}
/// Is this key an ECDSA key?
#[cfg(feature = "ecdsa")]
pub fn is_ecdsa(&self) -> bool {
matches!(self, Self::Ecdsa(_))
}
/// Is this key an Ed25519 key?
pub fn is_ed25519(&self) -> bool {
matches!(self, Self::Ed25519(_))
}
/// Is this key an RSA key?
#[cfg(feature = "alloc")]
pub fn is_rsa(&self) -> bool {
matches!(self, Self::Rsa(_))
}
/// Is this key a FIDO/U2F ECDSA/NIST P-256 key?
#[cfg(feature = "ecdsa")]
pub fn is_sk_ecdsa_p256(&self) -> bool {
matches!(self, Self::SkEcdsaSha2NistP256(_))
}
/// Is this key a FIDO/U2F Ed25519 key?
pub fn is_sk_ed25519(&self) -> bool {
matches!(self, Self::SkEd25519(_))
}
/// Is this a key with a custom algorithm?
#[cfg(feature = "alloc")]
pub fn is_other(&self) -> bool {
matches!(self, Self::Other(_))
}
/// Decode [`KeyData`] for the specified algorithm.
pub(crate) fn decode_as(reader: &mut impl Reader, algorithm: Algorithm) -> Result<Self> {
match algorithm {
#[cfg(feature = "alloc")]
Algorithm::Dsa => DsaPublicKey::decode(reader).map(Self::Dsa),
#[cfg(feature = "ecdsa")]
Algorithm::Ecdsa { curve } => match EcdsaPublicKey::decode(reader)? {
key if key.curve() == curve => Ok(Self::Ecdsa(key)),
_ => Err(Error::AlgorithmUnknown),
},
Algorithm::Ed25519 => Ed25519PublicKey::decode(reader).map(Self::Ed25519),
#[cfg(feature = "alloc")]
Algorithm::Rsa { .. } => RsaPublicKey::decode(reader).map(Self::Rsa),
#[cfg(feature = "ecdsa")]
Algorithm::SkEcdsaSha2NistP256 => {
SkEcdsaSha2NistP256::decode(reader).map(Self::SkEcdsaSha2NistP256)
}
Algorithm::SkEd25519 => SkEd25519::decode(reader).map(Self::SkEd25519),
#[cfg(feature = "alloc")]
Algorithm::Other(_) => OpaquePublicKey::decode_as(reader, algorithm).map(Self::Other),
#[allow(unreachable_patterns)]
_ => Err(Error::AlgorithmUnknown),
}
}
/// Get the encoded length of this key data without a leading algorithm
/// identifier.
pub(crate) fn encoded_key_data_len(&self) -> encoding::Result<usize> {
match self {
#[cfg(feature = "alloc")]
Self::Dsa(key) => key.encoded_len(),
#[cfg(feature = "ecdsa")]
Self::Ecdsa(key) => key.encoded_len(),
Self::Ed25519(key) => key.encoded_len(),
#[cfg(feature = "alloc")]
Self::Rsa(key) => key.encoded_len(),
#[cfg(feature = "ecdsa")]
Self::SkEcdsaSha2NistP256(sk) => sk.encoded_len(),
Self::SkEd25519(sk) => sk.encoded_len(),
#[cfg(feature = "alloc")]
Self::Other(other) => other.key.encoded_len(),
}
}
/// Encode the key data without a leading algorithm identifier.
pub(crate) fn encode_key_data(&self, writer: &mut impl Writer) -> encoding::Result<()> {
match self {
#[cfg(feature = "alloc")]
Self::Dsa(key) => key.encode(writer),
#[cfg(feature = "ecdsa")]
Self::Ecdsa(key) => key.encode(writer),
Self::Ed25519(key) => key.encode(writer),
#[cfg(feature = "alloc")]
Self::Rsa(key) => key.encode(writer),
#[cfg(feature = "ecdsa")]
Self::SkEcdsaSha2NistP256(sk) => sk.encode(writer),
Self::SkEd25519(sk) => sk.encode(writer),
#[cfg(feature = "alloc")]
Self::Other(other) => other.key.encode(writer),
}
}
}
impl Decode for KeyData {
type Error = Error;
fn decode(reader: &mut impl Reader) -> Result<Self> {
let algorithm = Algorithm::decode(reader)?;
Self::decode_as(reader, algorithm)
}
}
impl Encode for KeyData {
fn encoded_len(&self) -> encoding::Result<usize> {
[
self.algorithm().encoded_len()?,
self.encoded_key_data_len()?,
]
.checked_sum()
}
fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
self.algorithm().encode(writer)?;
self.encode_key_data(writer)
}
}
#[cfg(feature = "alloc")]
impl From<DsaPublicKey> for KeyData {
fn from(public_key: DsaPublicKey) -> KeyData {
Self::Dsa(public_key)
}
}
#[cfg(feature = "ecdsa")]
impl From<EcdsaPublicKey> for KeyData {
fn from(public_key: EcdsaPublicKey) -> KeyData {
Self::Ecdsa(public_key)
}
}
impl From<Ed25519PublicKey> for KeyData {
fn from(public_key: Ed25519PublicKey) -> KeyData {
Self::Ed25519(public_key)
}
}
#[cfg(feature = "alloc")]
impl From<RsaPublicKey> for KeyData {
fn from(public_key: RsaPublicKey) -> KeyData {
Self::Rsa(public_key)
}
}
#[cfg(feature = "ecdsa")]
impl From<SkEcdsaSha2NistP256> for KeyData {
fn from(public_key: SkEcdsaSha2NistP256) -> KeyData {
Self::SkEcdsaSha2NistP256(public_key)
}
}
impl From<SkEd25519> for KeyData {
fn from(public_key: SkEd25519) -> KeyData {
Self::SkEd25519(public_key)
}
}

98
vendor/ssh-key/src/public/opaque.rs vendored Normal file
View File

@@ -0,0 +1,98 @@
//! Opaque public keys.
//!
//! [`OpaquePublicKey`] represents a public key meant to be used with an algorithm unknown to this
//! crate, i.e. public keys that use a custom algorithm as specified in [RFC4251 § 6].
//!
//! They are said to be opaque, because the meaning of their underlying byte representation is not
//! specified.
//!
//! [RFC4251 § 6]: https://www.rfc-editor.org/rfc/rfc4251.html#section-6
use crate::{Algorithm, Error, Result};
use alloc::vec::Vec;
use encoding::{Decode, Encode, Reader, Writer};
/// An opaque public key with a custom algorithm name.
///
/// The encoded representation of an `OpaquePublicKey` is the encoded representation of its
/// [`OpaquePublicKeyBytes`].
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct OpaquePublicKey {
/// The [`Algorithm`] of this public key.
pub algorithm: Algorithm,
/// The key data
pub key: OpaquePublicKeyBytes,
}
/// The underlying representation of an [`OpaquePublicKey`].
///
/// The encoded representation of an `OpaquePublicKeyBytes` consists of a 4-byte length prefix,
/// followed by its byte representation.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct OpaquePublicKeyBytes(Vec<u8>);
impl OpaquePublicKey {
/// Create a new `OpaquePublicKey`.
pub fn new(key: Vec<u8>, algorithm: Algorithm) -> Self {
Self {
key: OpaquePublicKeyBytes(key),
algorithm,
}
}
/// Get the [`Algorithm`] for this public key type.
pub fn algorithm(&self) -> Algorithm {
self.algorithm.clone()
}
/// Decode [`OpaquePublicKey`] for the specified algorithm.
pub(super) fn decode_as(reader: &mut impl Reader, algorithm: Algorithm) -> Result<Self> {
Ok(Self {
algorithm,
key: OpaquePublicKeyBytes::decode(reader)?,
})
}
}
impl Decode for OpaquePublicKeyBytes {
type Error = Error;
fn decode(reader: &mut impl Reader) -> Result<Self> {
let len = usize::decode(reader)?;
let mut bytes = vec![0; len];
reader.read(&mut bytes)?;
Ok(Self(bytes))
}
}
impl Encode for OpaquePublicKeyBytes {
fn encoded_len(&self) -> encoding::Result<usize> {
self.0.encoded_len()
}
fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
self.0.encode(writer)
}
}
impl Encode for OpaquePublicKey {
fn encoded_len(&self) -> encoding::Result<usize> {
self.key.encoded_len()
}
fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
self.key.encode(writer)
}
}
impl AsRef<[u8]> for OpaquePublicKey {
fn as_ref(&self) -> &[u8] {
self.key.as_ref()
}
}
impl AsRef<[u8]> for OpaquePublicKeyBytes {
fn as_ref(&self) -> &[u8] {
&self.0
}
}

120
vendor/ssh-key/src/public/rsa.rs vendored Normal file
View File

@@ -0,0 +1,120 @@
//! RivestShamirAdleman (RSA) public keys.
use crate::{Error, Mpint, Result};
use core::hash::{Hash, Hasher};
use encoding::{CheckedSum, Decode, Encode, Reader, Writer};
#[cfg(feature = "rsa")]
use {
crate::private::RsaKeypair,
rsa::{pkcs1v15, traits::PublicKeyParts},
sha2::{digest::const_oid::AssociatedOid, Digest},
};
/// RSA public key.
///
/// Described in [RFC4253 § 6.6](https://datatracker.ietf.org/doc/html/rfc4253#section-6.6).
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct RsaPublicKey {
/// RSA public exponent.
pub e: Mpint,
/// RSA modulus.
pub n: Mpint,
}
impl RsaPublicKey {
/// Minimum allowed RSA key size.
#[cfg(feature = "rsa")]
pub(crate) const MIN_KEY_SIZE: usize = RsaKeypair::MIN_KEY_SIZE;
}
impl Decode for RsaPublicKey {
type Error = Error;
fn decode(reader: &mut impl Reader) -> Result<Self> {
let e = Mpint::decode(reader)?;
let n = Mpint::decode(reader)?;
Ok(Self { e, n })
}
}
impl Encode for RsaPublicKey {
fn encoded_len(&self) -> encoding::Result<usize> {
[self.e.encoded_len()?, self.n.encoded_len()?].checked_sum()
}
fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
self.e.encode(writer)?;
self.n.encode(writer)
}
}
impl Hash for RsaPublicKey {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.e.as_bytes().hash(state);
self.n.as_bytes().hash(state);
}
}
#[cfg(feature = "rsa")]
impl TryFrom<RsaPublicKey> for rsa::RsaPublicKey {
type Error = Error;
fn try_from(key: RsaPublicKey) -> Result<rsa::RsaPublicKey> {
rsa::RsaPublicKey::try_from(&key)
}
}
#[cfg(feature = "rsa")]
impl TryFrom<&RsaPublicKey> for rsa::RsaPublicKey {
type Error = Error;
fn try_from(key: &RsaPublicKey) -> Result<rsa::RsaPublicKey> {
let ret = rsa::RsaPublicKey::new(
rsa::BigUint::try_from(&key.n)?,
rsa::BigUint::try_from(&key.e)?,
)
.map_err(|_| Error::Crypto)?;
if ret.size().saturating_mul(8) >= RsaPublicKey::MIN_KEY_SIZE {
Ok(ret)
} else {
Err(Error::Crypto)
}
}
}
#[cfg(feature = "rsa")]
impl TryFrom<rsa::RsaPublicKey> for RsaPublicKey {
type Error = Error;
fn try_from(key: rsa::RsaPublicKey) -> Result<RsaPublicKey> {
RsaPublicKey::try_from(&key)
}
}
#[cfg(feature = "rsa")]
impl TryFrom<&rsa::RsaPublicKey> for RsaPublicKey {
type Error = Error;
fn try_from(key: &rsa::RsaPublicKey) -> Result<RsaPublicKey> {
Ok(RsaPublicKey {
e: key.e().try_into()?,
n: key.n().try_into()?,
})
}
}
#[cfg(feature = "rsa")]
impl<D> TryFrom<&RsaPublicKey> for pkcs1v15::VerifyingKey<D>
where
D: Digest + AssociatedOid,
{
type Error = Error;
fn try_from(key: &RsaPublicKey) -> Result<pkcs1v15::VerifyingKey<D>> {
Ok(pkcs1v15::VerifyingKey::new(key.try_into()?))
}
}

211
vendor/ssh-key/src/public/sk.rs vendored Normal file
View File

@@ -0,0 +1,211 @@
//! Security Key (FIDO/U2F) public keys as described in [PROTOCOL.u2f].
//!
//! [PROTOCOL.u2f]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.u2f?annotate=HEAD
use super::Ed25519PublicKey;
use crate::{Error, Result};
use encoding::{CheckedSum, Decode, Encode, Reader, Writer};
#[cfg(feature = "alloc")]
use alloc::{borrow::ToOwned, string::String};
#[cfg(feature = "ecdsa")]
use crate::{public::ecdsa::EcdsaNistP256PublicKey, EcdsaCurve};
/// Default FIDO/U2F Security Key application string.
const DEFAULT_APPLICATION_STRING: &str = "ssh:";
/// Security Key (FIDO/U2F) ECDSA/NIST P-256 public key as specified in
/// [PROTOCOL.u2f](https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.u2f?annotate=HEAD).
#[cfg(feature = "ecdsa")]
#[derive(Clone, Debug, Eq, Ord, Hash, PartialEq, PartialOrd)]
pub struct SkEcdsaSha2NistP256 {
/// Elliptic curve point representing a public key.
ec_point: EcdsaNistP256PublicKey,
/// FIDO/U2F application (typically `ssh:`)
#[cfg(feature = "alloc")]
application: String,
}
#[cfg(feature = "ecdsa")]
impl SkEcdsaSha2NistP256 {
/// Construct new instance of SkEcdsaSha2NistP256.
#[cfg(feature = "alloc")]
pub fn new(ec_point: EcdsaNistP256PublicKey, application: impl Into<String>) -> Self {
SkEcdsaSha2NistP256 {
ec_point,
application: application.into(),
}
}
/// Get the elliptic curve point for this Security Key.
pub fn ec_point(&self) -> &EcdsaNistP256PublicKey {
&self.ec_point
}
/// Get the FIDO/U2F application (typically `ssh:`).
#[cfg(not(feature = "alloc"))]
pub fn application(&self) -> &str {
DEFAULT_APPLICATION_STRING
}
/// Get the FIDO/U2F application (typically `ssh:`).
#[cfg(feature = "alloc")]
pub fn application(&self) -> &str {
&self.application
}
}
#[cfg(feature = "ecdsa")]
impl Decode for SkEcdsaSha2NistP256 {
type Error = Error;
fn decode(reader: &mut impl Reader) -> Result<Self> {
if EcdsaCurve::decode(reader)? != EcdsaCurve::NistP256 {
return Err(Error::Crypto);
}
let mut buf = [0u8; 65];
let ec_point = EcdsaNistP256PublicKey::from_bytes(reader.read_byten(&mut buf)?)?;
// application string (e.g. `ssh:`)
#[cfg(not(feature = "alloc"))]
reader.drain_prefixed()?;
Ok(Self {
ec_point,
#[cfg(feature = "alloc")]
application: String::decode(reader)?,
})
}
}
#[cfg(feature = "ecdsa")]
impl Encode for SkEcdsaSha2NistP256 {
fn encoded_len(&self) -> encoding::Result<usize> {
[
EcdsaCurve::NistP256.encoded_len()?,
self.ec_point.as_bytes().encoded_len()?,
self.application().encoded_len()?,
]
.checked_sum()
}
fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
EcdsaCurve::NistP256.encode(writer)?;
self.ec_point.as_bytes().encode(writer)?;
self.application().encode(writer)?;
Ok(())
}
}
#[cfg(feature = "ecdsa")]
impl From<EcdsaNistP256PublicKey> for SkEcdsaSha2NistP256 {
fn from(ec_point: EcdsaNistP256PublicKey) -> SkEcdsaSha2NistP256 {
SkEcdsaSha2NistP256 {
ec_point,
#[cfg(feature = "alloc")]
application: DEFAULT_APPLICATION_STRING.to_owned(),
}
}
}
#[cfg(feature = "ecdsa")]
impl From<SkEcdsaSha2NistP256> for EcdsaNistP256PublicKey {
fn from(sk: SkEcdsaSha2NistP256) -> EcdsaNistP256PublicKey {
sk.ec_point
}
}
/// Security Key (FIDO/U2F) Ed25519 public key as specified in
/// [PROTOCOL.u2f](https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.u2f?annotate=HEAD).
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)]
pub struct SkEd25519 {
/// Ed25519 public key.
public_key: Ed25519PublicKey,
/// FIDO/U2F application (typically `ssh:`)
#[cfg(feature = "alloc")]
application: String,
}
impl SkEd25519 {
/// Construct new instance of SkEd25519.
#[cfg(feature = "alloc")]
pub fn new(public_key: Ed25519PublicKey, application: impl Into<String>) -> Self {
SkEd25519 {
public_key,
application: application.into(),
}
}
/// Get the Ed25519 private key for this security key.
pub fn public_key(&self) -> &Ed25519PublicKey {
&self.public_key
}
/// Get the FIDO/U2F application (typically `ssh:`).
#[cfg(not(feature = "alloc"))]
pub fn application(&self) -> &str {
DEFAULT_APPLICATION_STRING
}
/// Get the FIDO/U2F application (typically `ssh:`).
#[cfg(feature = "alloc")]
pub fn application(&self) -> &str {
&self.application
}
}
impl Decode for SkEd25519 {
type Error = Error;
fn decode(reader: &mut impl Reader) -> Result<Self> {
let public_key = Ed25519PublicKey::decode(reader)?;
// application string (e.g. `ssh:`)
#[cfg(not(feature = "alloc"))]
reader.drain_prefixed()?;
Ok(Self {
public_key,
#[cfg(feature = "alloc")]
application: String::decode(reader)?,
})
}
}
impl Encode for SkEd25519 {
fn encoded_len(&self) -> encoding::Result<usize> {
[
self.public_key.encoded_len()?,
self.application().encoded_len()?,
]
.checked_sum()
}
fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
self.public_key.encode(writer)?;
self.application().encode(writer)?;
Ok(())
}
}
impl From<Ed25519PublicKey> for SkEd25519 {
fn from(public_key: Ed25519PublicKey) -> SkEd25519 {
SkEd25519 {
public_key,
#[cfg(feature = "alloc")]
application: DEFAULT_APPLICATION_STRING.to_owned(),
}
}
}
impl From<SkEd25519> for Ed25519PublicKey {
fn from(sk: SkEd25519) -> Ed25519PublicKey {
sk.public_key
}
}

192
vendor/ssh-key/src/public/ssh_format.rs vendored Normal file
View File

@@ -0,0 +1,192 @@
//! Support for OpenSSH-formatted public keys, a.k.a. `SSH-format`.
//!
//! These keys have the form:
//!
//! ```text
//! <algorithm id> <base64 key data> <comment>
//! ```
//!
//! ## Example
//!
//! ```text
//! ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILM+rvN+ot98qgEN796jTiQfZfG1KaT0PtFDJ/XFSqti user@example.com
//! ```
use crate::Result;
use core::str;
use encoding::{Base64Writer, Encode};
#[cfg(feature = "alloc")]
use {alloc::string::String, encoding::CheckedSum};
/// OpenSSH public key (a.k.a. `SSH-format`) decoder/encoder.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct SshFormat<'a> {
/// Algorithm identifier
pub(crate) algorithm_id: &'a str,
/// Base64-encoded key data
pub(crate) base64_data: &'a [u8],
/// Comment
#[cfg_attr(not(feature = "alloc"), allow(dead_code))]
pub(crate) comment: &'a str,
}
impl<'a> SshFormat<'a> {
/// Parse the given binary data.
pub(crate) fn decode(mut bytes: &'a [u8]) -> Result<Self> {
let algorithm_id = decode_segment_str(&mut bytes)?;
let base64_data = decode_segment(&mut bytes)?;
let comment = str::from_utf8(bytes)?.trim_end();
if algorithm_id.is_empty() || base64_data.is_empty() {
// TODO(tarcieri): better errors for these cases?
return Err(encoding::Error::Length.into());
}
Ok(Self {
algorithm_id,
base64_data,
comment,
})
}
/// Encode data with OpenSSH public key encapsulation.
pub(crate) fn encode<'o, K>(
algorithm_id: &str,
key: &K,
comment: &str,
out: &'o mut [u8],
) -> Result<&'o str>
where
K: Encode,
{
let mut offset = 0;
encode_str(out, &mut offset, algorithm_id)?;
encode_str(out, &mut offset, " ")?;
let mut writer = Base64Writer::new(&mut out[offset..])?;
key.encode(&mut writer)?;
let base64_len = writer.finish()?.len();
offset = offset
.checked_add(base64_len)
.ok_or(encoding::Error::Length)?;
if !comment.is_empty() {
encode_str(out, &mut offset, " ")?;
encode_str(out, &mut offset, comment)?;
}
Ok(str::from_utf8(&out[..offset])?)
}
/// Encode string with OpenSSH public key encapsulation.
#[cfg(feature = "alloc")]
pub(crate) fn encode_string<K>(algorithm_id: &str, key: &K, comment: &str) -> Result<String>
where
K: Encode,
{
let encoded_len = [
2, // interstitial spaces
algorithm_id.len(),
base64_len_approx(key.encoded_len()?),
comment.len(),
]
.checked_sum()?;
let mut out = vec![0u8; encoded_len];
let actual_len = Self::encode(algorithm_id, key, comment, &mut out)?.len();
out.truncate(actual_len);
Ok(String::from_utf8(out)?)
}
}
/// Get the estimated length of data when encoded as Base64.
///
/// This is an upper bound where the actual length might be slightly shorter,
/// and can be used to estimate the capacity of an output buffer. However, the
/// final result may need to be sliced and should use the actual encoded length
/// rather than this estimate.
#[cfg(feature = "alloc")]
fn base64_len_approx(input_len: usize) -> usize {
(((input_len.saturating_mul(4)) / 3).saturating_add(3)) & !3
}
/// Parse a segment of the public key.
fn decode_segment<'a>(bytes: &mut &'a [u8]) -> Result<&'a [u8]> {
let start = *bytes;
let mut len = 0usize;
loop {
match *bytes {
[b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'+' | b'-' | b'/' | b'=' | b'@' | b'.', rest @ ..] =>
{
// Valid character; continue
*bytes = rest;
len = len.checked_add(1).ok_or(encoding::Error::Length)?;
}
[b' ', rest @ ..] => {
// Encountered space; we're done
*bytes = rest;
return start
.get(..len)
.ok_or_else(|| encoding::Error::Length.into());
}
[_, ..] => {
// Invalid character
return Err(encoding::Error::CharacterEncoding.into());
}
[] => {
// End of input, could be truncated or could be no comment
return start
.get(..len)
.ok_or_else(|| encoding::Error::Length.into());
}
}
}
}
/// Parse a segment of the public key as a `&str`.
fn decode_segment_str<'a>(bytes: &mut &'a [u8]) -> Result<&'a str> {
str::from_utf8(decode_segment(bytes)?).map_err(|_| encoding::Error::CharacterEncoding.into())
}
/// Encode a segment of the public key.
fn encode_str(out: &mut [u8], offset: &mut usize, s: &str) -> Result<()> {
let bytes = s.as_bytes();
if out.len()
< offset
.checked_add(bytes.len())
.ok_or(encoding::Error::Length)?
{
return Err(encoding::Error::Length.into());
}
out[*offset..][..bytes.len()].copy_from_slice(bytes);
*offset = offset
.checked_add(bytes.len())
.ok_or(encoding::Error::Length)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::SshFormat;
const EXAMPLE_KEY: &str = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILM+rvN+ot98qgEN796jTiQfZfG1KaT0PtFDJ/XFSqti user@example.com";
#[test]
fn decode() {
let encapsulation = SshFormat::decode(EXAMPLE_KEY.as_bytes()).unwrap();
assert_eq!(encapsulation.algorithm_id, "ssh-ed25519");
assert_eq!(
encapsulation.base64_data,
b"AAAAC3NzaC1lZDI1NTE5AAAAILM+rvN+ot98qgEN796jTiQfZfG1KaT0PtFDJ/XFSqti"
);
assert_eq!(encapsulation.comment, "user@example.com");
}
}