diff --git a/src/Renci.SshNet/PrivateKeyFile.PKCS8.cs b/src/Renci.SshNet/PrivateKeyFile.PKCS8.cs index 45ba357d3..04199ebd8 100644 --- a/src/Renci.SshNet/PrivateKeyFile.PKCS8.cs +++ b/src/Renci.SshNet/PrivateKeyFile.PKCS8.cs @@ -7,6 +7,7 @@ using Org.BouncyCastle.Asn1.EdEC; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Asn1.X9; +using Org.BouncyCastle.Math.EC.Rfc8032; using Org.BouncyCastle.Pkcs; using Renci.SshNet.Common; @@ -84,7 +85,17 @@ public Key Parse() if (algorithmOid.Equals(EdECObjectIdentifiers.id_Ed25519)) { - return new ED25519Key(key); + // RFC 8410 section 7: the privateKey field holds a CurvePrivateKey OCTET STRING. + var curvePrivateKeyReader = new AsnReader(key, AsnEncodingRules.DER); + var seed = curvePrivateKeyReader.ReadOctetString(); + curvePrivateKeyReader.ThrowIfNotEmpty(); + + if (seed.Length != Ed25519.SecretKeySize) + { + throw new SshException(string.Format(CultureInfo.InvariantCulture, "Invalid Ed25519 private key length {0}.", seed.Length)); + } + + return new ED25519Key(seed); } throw new SshException(string.Format(CultureInfo.InvariantCulture, "Private key algorithm \"{0}\" is not supported.", algorithmOid)); diff --git a/test/Renci.SshNet.Tests/Classes/PrivateKeyFileTest.cs b/test/Renci.SshNet.Tests/Classes/PrivateKeyFileTest.cs index 8ac1e2056..c383dd472 100644 --- a/test/Renci.SshNet.Tests/Classes/PrivateKeyFileTest.cs +++ b/test/Renci.SshNet.Tests/Classes/PrivateKeyFileTest.cs @@ -379,6 +379,29 @@ public void Test_PrivateKey(string name, string passPhrase, Type expectedKeyType } } + [TestMethod] + [DataRow("Key.OPENSSH.ED25519.PKCS8.Encrypted.Aes.256.CBC.12345.txt", "12345")] + [DataRow("Key.OPENSSH.ED25519.PKCS8.txt", null)] + [DataRow("Key.OPENSSH.ED25519.txt", null)] + public void Test_PrivateKey_ED25519_KeyMaterial(string name, string passPhrase) + { + // The PKCS#8 files hold the same key as Key.OPENSSH.ED25519.txt. + // openssl pkey -in Key.OPENSSH.ED25519.PKCS8.txt -outform DER | tail -c 32 | base64 + var expectedPrivateKey = Convert.FromBase64String("AMwRdTD1Ma7PsnKSYdvM86Pxd5ulnCjvqK7Em0eS8Ck="); + + // cut -d' ' -f2 Key.OPENSSH.ED25519.pub | base64 -d | tail -c 32 | base64 + var expectedPublicKey = Convert.FromBase64String("DQlmcNCvFBlw0At9lgbss8BbUxgQa9VbmeN7s6UwYyI="); + + using (var stream = GetData(name)) + { + var pkFile = new PrivateKeyFile(stream, passPhrase); + + var key = Assert.IsInstanceOfType(pkFile.Key); + CollectionAssert.AreEqual(expectedPrivateKey, key.PrivateKey); + CollectionAssert.AreEqual(expectedPublicKey, key.PublicKey); + } + } + [TestMethod] public void Test_Certificate_OPENSSH_RSA() {