diff options
author | Peter Dettman <peter.dettman@bouncycastle.org> | 2023-04-16 00:06:04 +0700 |
---|---|---|
committer | Peter Dettman <peter.dettman@bouncycastle.org> | 2023-04-16 00:06:04 +0700 |
commit | 0e7c2681817b841c47f76e008046ab4624c9a311 (patch) | |
tree | fa8c86fec08fc796bb6d427290f114a8671f73e7 | |
parent | Refactor NameConstraints (diff) | |
parent | Fixes and improvements for github_439 (diff) | |
download | BouncyCastle.NET-ed25519-0e7c2681817b841c47f76e008046ab4624c9a311.tar.xz |
Merge branch 'anhvo/PortOpenSshUtil'
-rw-r--r-- | crypto/src/crypto/parameters/ECKeyParameters.cs | 1 | ||||
-rw-r--r-- | crypto/src/crypto/util/OpenSshPrivateKeyUtilities.cs | 288 | ||||
-rw-r--r-- | crypto/src/crypto/util/OpenSshPublicKeyUtilities.cs | 163 | ||||
-rw-r--r-- | crypto/src/crypto/util/SshBuffer.cs | 162 | ||||
-rw-r--r-- | crypto/src/crypto/util/SshBuilder.cs | 78 | ||||
-rw-r--r-- | crypto/src/crypto/util/SshNamedCurves.cs | 107 | ||||
-rw-r--r-- | crypto/test/src/crypto/test/OpenSshKeyParsingTest.cs | 490 |
7 files changed, 1289 insertions, 0 deletions
diff --git a/crypto/src/crypto/parameters/ECKeyParameters.cs b/crypto/src/crypto/parameters/ECKeyParameters.cs index ed8537f3d..b015433ab 100644 --- a/crypto/src/crypto/parameters/ECKeyParameters.cs +++ b/crypto/src/crypto/parameters/ECKeyParameters.cs @@ -40,6 +40,7 @@ namespace Org.BouncyCastle.Crypto.Parameters this.algorithm = VerifyAlgorithmName(algorithm); this.parameters = parameters; + this.publicKeyParamSet = (parameters as ECNamedDomainParameters)?.Name; } protected ECKeyParameters( diff --git a/crypto/src/crypto/util/OpenSshPrivateKeyUtilities.cs b/crypto/src/crypto/util/OpenSshPrivateKeyUtilities.cs new file mode 100644 index 000000000..aa934b1d6 --- /dev/null +++ b/crypto/src/crypto/util/OpenSshPrivateKeyUtilities.cs @@ -0,0 +1,288 @@ +using System; +using System.Text; + +using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Asn1.Pkcs; +using Org.BouncyCastle.Asn1.Sec; +using Org.BouncyCastle.Asn1.X9; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Math; +using Org.BouncyCastle.Pkcs; +using Org.BouncyCastle.Utilities; + +namespace Org.BouncyCastle.Crypto.Utilities +{ + public static class OpenSshPrivateKeyUtilities + { + /// <summary>Magic value for proprietary OpenSSH private key.</summary> + /// <remarks>C string so null terminated.</remarks> + private static readonly byte[] AUTH_MAGIC = Encoding.ASCII.GetBytes("openssh-key-v1\0"); + + /** + * Encode a cipher parameters into an OpenSSH private key. + * This does not add headers like ----BEGIN RSA PRIVATE KEY---- + * + * @param parameters the cipher parameters. + * @return a byte array + */ + public static byte[] EncodePrivateKey(AsymmetricKeyParameter parameters) + { + if (parameters == null) + throw new ArgumentNullException(nameof(parameters)); + + if (parameters is RsaPrivateCrtKeyParameters || parameters is ECPrivateKeyParameters) + { + PrivateKeyInfo pInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(parameters); + return pInfo.ParsePrivateKey().GetEncoded(); + } + else if (parameters is DsaPrivateKeyParameters dsaPrivateKey) + { + DsaParameters dsaparameters = dsaPrivateKey.Parameters; + + Asn1EncodableVector vec = new Asn1EncodableVector + { + new DerInteger(0), + new DerInteger(dsaparameters.P), + new DerInteger(dsaparameters.Q), + new DerInteger(dsaparameters.G) + }; + + // public key = g.modPow(x, p); + BigInteger pubKey = dsaparameters.P.ModPow(dsaPrivateKey.X, dsaparameters.P); + vec.Add(new DerInteger(pubKey)); + vec.Add(new DerInteger(dsaPrivateKey.X)); + try + { + return new DerSequence(vec).GetEncoded(); + } + catch (Exception ex) + { + throw new InvalidOperationException("unable to encode DSAPrivateKeyParameters " + ex.Message); + } + } + else if (parameters is Ed25519PrivateKeyParameters ed25519PrivateKey) + { + Ed25519PublicKeyParameters publicKeyParameters = ed25519PrivateKey.GeneratePublicKey(); + + SshBuilder builder = new SshBuilder(); + builder.WriteBytes(AUTH_MAGIC); + builder.WriteStringAscii("none"); // cipher name + builder.WriteStringAscii("none"); // KDF name + builder.WriteStringAscii(""); // KDF options + + builder.U32(1); // Number of keys + + { + byte[] pkEncoded = OpenSshPublicKeyUtilities.EncodePublicKey(publicKeyParameters); + builder.WriteBlock(pkEncoded); + } + + { + SshBuilder pkBuild = new SshBuilder(); + + int checkint = CryptoServicesRegistrar.GetSecureRandom().NextInt(); + pkBuild.U32((uint)checkint); + pkBuild.U32((uint)checkint); + + pkBuild.WriteStringAscii("ssh-ed25519"); + + // Public key (as part of private key pair) + byte[] pubKeyEncoded = publicKeyParameters.GetEncoded(); + pkBuild.WriteBlock(pubKeyEncoded); + + // The private key in SSH is 64 bytes long and is the concatenation of the private and the public keys + pkBuild.WriteBlock(Arrays.Concatenate(ed25519PrivateKey.GetEncoded(), pubKeyEncoded)); + + // Comment for this private key (empty) + pkBuild.WriteStringUtf8(""); + + builder.WriteBlock(pkBuild.GetPaddedBytes()); + } + + return builder.GetBytes(); + } + + throw new ArgumentException("unable to convert " + Platform.GetTypeName(parameters) + " to openssh private key"); + } + + /** + * Parse a private key. + * <p/> + * This method accepts the body of the OpenSSH private key. + * The easiest way to extract the body is to use PemReader, for example: + * <p/> + * byte[] blob = new PemReader([reader]).readPemObject().getContent(); + * CipherParameters params = parsePrivateKeyBlob(blob); + * + * @param blob The key. + * @return A cipher parameters instance. + */ + public static AsymmetricKeyParameter ParsePrivateKeyBlob(byte[] blob) + { + AsymmetricKeyParameter result = null; + + if (blob[0] == 0x30) + { + Asn1Sequence sequence = Asn1Sequence.GetInstance(blob); + + if (sequence.Count == 6) + { + if (AllIntegers(sequence) && ((DerInteger)sequence[0]).PositiveValue.Equals(BigIntegers.Zero)) + { + // length of 6 and all Integers -- DSA + result = new DsaPrivateKeyParameters( + ((DerInteger)sequence[5]).PositiveValue, + new DsaParameters( + ((DerInteger)sequence[1]).PositiveValue, + ((DerInteger)sequence[2]).PositiveValue, + ((DerInteger)sequence[3]).PositiveValue) + ); + } + } + else if (sequence.Count == 9) + { + if (AllIntegers(sequence) && ((DerInteger)sequence[0]).PositiveValue.Equals(BigIntegers.Zero)) + { + // length of 8 and all Integers -- RSA + RsaPrivateKeyStructure rsaPrivateKey = RsaPrivateKeyStructure.GetInstance(sequence); + + result = new RsaPrivateCrtKeyParameters( + rsaPrivateKey.Modulus, + rsaPrivateKey.PublicExponent, + rsaPrivateKey.PrivateExponent, + rsaPrivateKey.Prime1, + rsaPrivateKey.Prime2, + rsaPrivateKey.Exponent1, + rsaPrivateKey.Exponent2, + rsaPrivateKey.Coefficient); + } + } + else if (sequence.Count == 4) + { + if (sequence[3] is Asn1TaggedObject && sequence[2] is Asn1TaggedObject) + { + ECPrivateKeyStructure ecPrivateKey = ECPrivateKeyStructure.GetInstance(sequence); + DerObjectIdentifier curveOID = DerObjectIdentifier.GetInstance(ecPrivateKey.GetParameters()); + X9ECParameters x9Params = ECNamedCurveTable.GetByOid(curveOID); + result = new ECPrivateKeyParameters( + ecPrivateKey.GetKey(), + new ECNamedDomainParameters( + curveOID, + x9Params)); + } + } + } + else + { + SshBuffer kIn = new SshBuffer(AUTH_MAGIC, blob); + + string cipherName = kIn.ReadStringAscii(); + if (!"none".Equals(cipherName)) + throw new InvalidOperationException("encrypted keys not supported"); + + // KDF name + kIn.SkipBlock(); + + // KDF options + kIn.SkipBlock(); + + int publicKeyCount = kIn.ReadU32(); + if (publicKeyCount != 1) + throw new InvalidOperationException("multiple keys not supported"); + + // Burn off public key. + OpenSshPublicKeyUtilities.ParsePublicKey(kIn.ReadBlock()); + + byte[] privateKeyBlock = kIn.ReadPaddedBlock(); + + if (kIn.HasRemaining()) + throw new InvalidOperationException("decoded key has trailing data"); + + SshBuffer pkIn = new SshBuffer(privateKeyBlock); + int check1 = pkIn.ReadU32(); + int check2 = pkIn.ReadU32(); + + if (check1 != check2) + throw new InvalidOperationException("private key check values are not the same"); + + string keyType = pkIn.ReadStringAscii(); + + if ("ssh-ed25519".Equals(keyType)) + { + // Public key + pkIn.SkipBlock(); + + // Private key value.. +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + ReadOnlySpan<byte> edPrivateKey = pkIn.ReadBlockSpan(); +#else + byte[] edPrivateKey = pkIn.ReadBlock(); +#endif + + if (edPrivateKey.Length != Ed25519PrivateKeyParameters.KeySize + Ed25519PublicKeyParameters.KeySize) + throw new InvalidOperationException("private key value of wrong length"); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + result = new Ed25519PrivateKeyParameters(edPrivateKey[..Ed25519PrivateKeyParameters.KeySize]); +#else + result = new Ed25519PrivateKeyParameters(edPrivateKey, 0); +#endif + } + else if (keyType.StartsWith("ecdsa")) + { + var curveName = pkIn.ReadStringAscii(); + + var oid = SshNamedCurves.GetOid(curveName) ?? + throw new InvalidOperationException("OID not found for: " + keyType); + + var x9ECParameters = SshNamedCurves.GetByOid(oid) ?? + throw new InvalidOperationException("Curve not found for: " + oid); + + // Skip public key. + pkIn.SkipBlock(); + + var d = pkIn.ReadMpintPositive(); + + result = new ECPrivateKeyParameters(d, new ECNamedDomainParameters(oid, x9ECParameters)); + } + else if (keyType.StartsWith("ssh-rsa")) + { + BigInteger modulus = pkIn.ReadMpintPositive(); + BigInteger pubExp = pkIn.ReadMpintPositive(); + BigInteger privExp = pkIn.ReadMpintPositive(); + BigInteger coef = pkIn.ReadMpintPositive(); + BigInteger p = pkIn.ReadMpintPositive(); + BigInteger q = pkIn.ReadMpintPositive(); + + BigInteger pSub1 = p.Subtract(BigIntegers.One); + BigInteger qSub1 = q.Subtract(BigIntegers.One); + BigInteger dP = privExp.Remainder(pSub1); + BigInteger dQ = privExp.Remainder(qSub1); + + result = new RsaPrivateCrtKeyParameters(modulus, pubExp, privExp, p, q, dP, dQ, coef); + } + + // Comment for private key + pkIn.SkipBlock(); + + if (pkIn.HasRemaining()) + throw new ArgumentException("private key block has trailing data"); + } + + return result ?? throw new ArgumentException("unable to parse key"); ; + } + + /** + * allIntegers returns true if the sequence holds only DerInteger types. + **/ + private static bool AllIntegers(Asn1Sequence sequence) + { + for (int t = 0; t < sequence.Count; t++) + { + if (!(sequence[t] is DerInteger)) + return false; + } + return true; + } + } +} diff --git a/crypto/src/crypto/util/OpenSshPublicKeyUtilities.cs b/crypto/src/crypto/util/OpenSshPublicKeyUtilities.cs new file mode 100644 index 000000000..f04ab85f7 --- /dev/null +++ b/crypto/src/crypto/util/OpenSshPublicKeyUtilities.cs @@ -0,0 +1,163 @@ +using System; + +using Org.BouncyCastle.Asn1.X9; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Math; +using Org.BouncyCastle.Utilities; + +namespace Org.BouncyCastle.Crypto.Utilities +{ + public static class OpenSshPublicKeyUtilities + { + private static readonly string RSA = "ssh-rsa"; + private static readonly string ECDSA = "ecdsa"; + private static readonly string ED_25519 = "ssh-ed25519"; + private static readonly string DSS = "ssh-dss"; + + /** + * Parse a public key. + * <p/> + * This method accepts the bytes that are Base64 encoded in an OpenSSH public key file. + * + * @param encoded The key. + * @return An AsymmetricKeyParameter instance. + */ + public static AsymmetricKeyParameter ParsePublicKey(byte[] encoded) + { + SshBuffer buffer = new SshBuffer(encoded); + return ParsePublicKey(buffer); + } + + /** + * Encode a public key from an AsymmetricKeyParameter instance. + * + * @param cipherParameters The key to encode. + * @return the key OpenSSH encoded. + * @throws IOException + */ + public static byte[] EncodePublicKey(AsymmetricKeyParameter cipherParameters) + { + if (cipherParameters == null) + throw new ArgumentNullException(nameof(cipherParameters)); + if (cipherParameters.IsPrivate) + throw new ArgumentException("Not a public key", nameof(cipherParameters)); + + if (cipherParameters is RsaKeyParameters rsaPubKey) + { + SshBuilder builder = new SshBuilder(); + builder.WriteStringAscii(RSA); + builder.WriteMpint(rsaPubKey.Exponent); + builder.WriteMpint(rsaPubKey.Modulus); + return builder.GetBytes(); + } + else if (cipherParameters is ECPublicKeyParameters ecPublicKey) + { + string curveName = null; + + var oid = ecPublicKey.PublicKeyParamSet; + if (oid != null) + { + curveName = SshNamedCurves.GetName(oid); + } + + if (curveName == null) + throw new ArgumentException("unable to derive ssh curve name for EC public key"); + + SshBuilder builder = new SshBuilder(); + builder.WriteStringAscii(ECDSA + "-sha2-" + curveName); // Magic + builder.WriteStringAscii(curveName); + builder.WriteBlock(ecPublicKey.Q.GetEncoded(false)); //Uncompressed + return builder.GetBytes(); + } + else if (cipherParameters is DsaPublicKeyParameters dsaPubKey) + { + DsaParameters dsaParams = dsaPubKey.Parameters; + + SshBuilder builder = new SshBuilder(); + builder.WriteStringAscii(DSS); + builder.WriteMpint(dsaParams.P); + builder.WriteMpint(dsaParams.Q); + builder.WriteMpint(dsaParams.G); + builder.WriteMpint(dsaPubKey.Y); + return builder.GetBytes(); + } + else if (cipherParameters is Ed25519PublicKeyParameters ed25519PublicKey) + { + SshBuilder builder = new SshBuilder(); + builder.WriteStringAscii(ED_25519); + builder.WriteBlock(ed25519PublicKey.GetEncoded()); + return builder.GetBytes(); + } + + throw new ArgumentException("unable to convert " + Platform.GetTypeName(cipherParameters) + " to private key"); + } + + /** + * Parse a public key from an SSHBuffer instance. + * + * @param buffer containing the SSH public key. + * @return A CipherParameters instance. + */ + private static AsymmetricKeyParameter ParsePublicKey(SshBuffer buffer) + { + AsymmetricKeyParameter result = null; + + string magic = buffer.ReadStringAscii(); + if (RSA.Equals(magic)) + { + BigInteger e = buffer.ReadMpintPositive(); + BigInteger n = buffer.ReadMpintPositive(); + result = new RsaKeyParameters(false, n, e); + } + else if (DSS.Equals(magic)) + { + BigInteger p = buffer.ReadMpintPositive(); + BigInteger q = buffer.ReadMpintPositive(); + BigInteger g = buffer.ReadMpintPositive(); + BigInteger pubKey = buffer.ReadMpintPositive(); + + result = new DsaPublicKeyParameters(pubKey, new DsaParameters(p, q, g)); + } + else if (magic.StartsWith(ECDSA)) + { + var curveName = buffer.ReadStringAscii(); + + var oid = SshNamedCurves.GetOid(curveName); + + X9ECParameters x9ECParameters = oid == null ? null : SshNamedCurves.GetByOid(oid); + if (x9ECParameters == null) + { + throw new InvalidOperationException( + "unable to find curve for " + magic + " using curve name " + curveName); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + ReadOnlySpan<byte> pointEncoding = buffer.ReadBlockSpan(); +#else + byte[] pointEncoding = buffer.ReadBlock(); +#endif + var point = x9ECParameters.Curve.DecodePoint(pointEncoding); + + result = new ECPublicKeyParameters(point, new ECNamedDomainParameters(oid, x9ECParameters)); + } + else if (ED_25519.Equals(magic)) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + ReadOnlySpan<byte> pubKeyBytes = buffer.ReadBlockSpan(); +#else + byte[] pubKeyBytes = buffer.ReadBlock(); +#endif + + result = new Ed25519PublicKeyParameters(pubKeyBytes); + } + + if (result == null) + throw new ArgumentException("unable to parse key"); + + if (buffer.HasRemaining()) + throw new ArgumentException("decoded key has trailing data"); + + return result; + } + } +} diff --git a/crypto/src/crypto/util/SshBuffer.cs b/crypto/src/crypto/util/SshBuffer.cs new file mode 100644 index 000000000..0df123388 --- /dev/null +++ b/crypto/src/crypto/util/SshBuffer.cs @@ -0,0 +1,162 @@ +using System; +using System.Text; + +using Org.BouncyCastle.Math; +using Org.BouncyCastle.Utilities; + +namespace Org.BouncyCastle.Crypto.Utilities +{ + internal class SshBuffer + { + private readonly byte[] buffer; + private int pos = 0; + + internal SshBuffer(byte[] magic, byte[] buffer) + { + this.buffer = buffer; + for (int i = 0; i != magic.Length; i++) + { + if (magic[i] != buffer[i]) + throw new ArgumentException("magic-number incorrect"); + } + + pos += magic.Length; + } + + internal SshBuffer(byte[] buffer) + { + this.buffer = buffer; + } + + public int ReadU32() + { + if (pos > buffer.Length - 4) + throw new ArgumentOutOfRangeException("4 bytes for U32 exceeds buffer."); + + int i = (int)Pack.BE_To_UInt32(buffer, pos); + pos += 4; + return i; + } + + public string ReadStringAscii() + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + return Encoding.ASCII.GetString(ReadBlockSpan()); +#else + return Encoding.ASCII.GetString(ReadBlock()); +#endif + } + + public string ReadStringUtf8() + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + return Encoding.UTF8.GetString(ReadBlockSpan()); +#else + return Encoding.UTF8.GetString(ReadBlock()); +#endif + } + + public byte[] ReadBlock() + { + int len = ReadU32(); + if (len == 0) + return Arrays.EmptyBytes; + if (pos > buffer.Length - len) + throw new InvalidOperationException("not enough data for block"); + + int start = pos; pos += len; + return Arrays.CopyOfRange(buffer, start, pos); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + public ReadOnlySpan<byte> ReadBlockSpan() + { + int len = ReadU32(); + if (len == 0) + return ReadOnlySpan<byte>.Empty; + if (pos > buffer.Length - len) + throw new InvalidOperationException("not enough data for block"); + + int start = pos; pos += len; + return buffer.AsSpan(start, len); + } +#endif + + public void SkipBlock() + { + int len = ReadU32(); + if (pos > buffer.Length - len) + throw new InvalidOperationException("not enough data for block"); + + pos += len; + } + + public byte[] ReadPaddedBlock() + { + return ReadPaddedBlock(8); + } + + public byte[] ReadPaddedBlock(int blockSize) + { + int len = ReadU32(); + if (len == 0) + return Arrays.EmptyBytes; + if (pos > buffer.Length - len) + throw new InvalidOperationException("not enough data for block"); + + int align = len % blockSize; + if (0 != align) + throw new InvalidOperationException("missing padding"); + + int start = pos; pos += len; + int end = pos; + + if (len > 0) + { + // TODO If encryption is supported, should be constant-time + int lastByte = buffer[pos - 1] & 0xFF; + if (0 < lastByte && lastByte < blockSize) + { + int padCount = lastByte; + end -= padCount; + + for (int i = 1, padPos = end; i <= padCount; ++i, ++padPos) + { + if (i != (buffer[padPos] & 0xFF)) + throw new InvalidOperationException("incorrect padding"); + } + } + } + + return Arrays.CopyOfRange(buffer, start, end); + } + + public BigInteger ReadMpint() + { + int len = ReadU32(); + if (pos > buffer.Length - len) + throw new InvalidOperationException("not enough data for big num"); + + if (len == 0) + return BigInteger.Zero; + if (len == 1 && buffer[pos] == 0) + throw new InvalidOperationException("Zero MUST be stored with length 0"); + if (len > 1 && buffer[pos] == (byte)-(buffer[pos + 1] >> 7)) + throw new InvalidOperationException("Unnecessary leading bytes MUST NOT be included"); + + int start = pos; pos += len; + return new BigInteger(buffer, start, len); + } + + public BigInteger ReadMpintPositive() + { + BigInteger n = ReadMpint(); + if (n.SignValue < 0) + throw new InvalidOperationException("Expected a positive mpint"); + + return n; + } + + public bool HasRemaining() => pos < buffer.Length; + } +} diff --git a/crypto/src/crypto/util/SshBuilder.cs b/crypto/src/crypto/util/SshBuilder.cs new file mode 100644 index 000000000..d631448d5 --- /dev/null +++ b/crypto/src/crypto/util/SshBuilder.cs @@ -0,0 +1,78 @@ +using System; +using System.IO; +using System.Text; + +using Org.BouncyCastle.Math; + +namespace Org.BouncyCastle.Crypto.Utilities +{ + internal class SshBuilder + { + private readonly MemoryStream bos = new MemoryStream(); + + public void U32(uint value) + { + bos.WriteByte(Convert.ToByte(value >> 24 & 0xFF)); + bos.WriteByte(Convert.ToByte(value >> 16 & 0xFF)); + bos.WriteByte(Convert.ToByte(value >> 8 & 0xFF)); + bos.WriteByte(Convert.ToByte(value & 0xFF)); + } + + public void WriteMpint(BigInteger n) + { + WriteBlock(n.ToByteArray()); + } + + public void WriteBlock(byte[] value) + { + U32((uint)value.Length); + WriteBytes(value); + } + + public void WriteBytes(byte[] value) + { + try + { + bos.Write(value, 0, value.Length); + } + catch (IOException e) + { + throw new InvalidOperationException(e.Message, e); + } + } + + public void WriteStringAscii(string str) + { + WriteBlock(Encoding.ASCII.GetBytes(str)); + } + + public void WriteStringUtf8(string str) + { + WriteBlock(Encoding.UTF8.GetBytes(str)); + } + + public byte[] GetBytes() + { + return bos.ToArray(); + } + + public byte[] GetPaddedBytes() + { + return GetPaddedBytes(8); + } + + public byte[] GetPaddedBytes(int blockSize) + { + int align = (int)bos.Length % blockSize; + if (0 != align) + { + int padCount = blockSize - align; + for (int i = 1; i <= padCount; ++i) + { + bos.WriteByte(Convert.ToByte(i)); + } + } + return bos.ToArray(); + } + } +} diff --git a/crypto/src/crypto/util/SshNamedCurves.cs b/crypto/src/crypto/util/SshNamedCurves.cs new file mode 100644 index 000000000..019a4d5f5 --- /dev/null +++ b/crypto/src/crypto/util/SshNamedCurves.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Generic; + +using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Asn1.Sec; +using Org.BouncyCastle.Asn1.X9; +using Org.BouncyCastle.Crypto.Generators; +using Org.BouncyCastle.Utilities.Collections; + +namespace Org.BouncyCastle.Crypto.Utilities +{ + public static class SshNamedCurves + { + private static readonly Dictionary<string, DerObjectIdentifier> objIds = + new Dictionary<string, DerObjectIdentifier>(StringComparer.OrdinalIgnoreCase); + private static readonly Dictionary<DerObjectIdentifier, string> names = + new Dictionary<DerObjectIdentifier, string>(); + + private static void DefineCurveAlias(string name, DerObjectIdentifier oid) + { + if (FindByOidLazy(oid) == null) + throw new InvalidOperationException(); + + objIds.Add(name, oid); + names.Add(oid, name); + } + + private static X9ECParametersHolder FindByOidLazy(DerObjectIdentifier oid) => + ECKeyPairGenerator.FindECCurveByOidLazy(oid); + + static SshNamedCurves() + { + DefineCurveAlias("nistp192", SecObjectIdentifiers.SecP192r1); + DefineCurveAlias("nistp224", SecObjectIdentifiers.SecP224r1); + DefineCurveAlias("nistp256", SecObjectIdentifiers.SecP256r1); + DefineCurveAlias("nistp384", SecObjectIdentifiers.SecP384r1); + DefineCurveAlias("nistp521", SecObjectIdentifiers.SecP521r1); + DefineCurveAlias("nistb233", SecObjectIdentifiers.SecT233r1); + DefineCurveAlias("nistb409", SecObjectIdentifiers.SecT409r1); + DefineCurveAlias("nistk163", SecObjectIdentifiers.SecT163k1); + DefineCurveAlias("nistk233", SecObjectIdentifiers.SecT233k1); + DefineCurveAlias("nistk283", SecObjectIdentifiers.SecT283k1); + DefineCurveAlias("nistk409", SecObjectIdentifiers.SecT409k1); + DefineCurveAlias("nistt571", SecObjectIdentifiers.SecT571k1); + } + + /// <summary>Look up the <see cref="X9ECParameters"/> for the curve with the given name.</summary> + /// <param name="name">The name of the curve.</param> + public static X9ECParameters GetByName(string name) + { + DerObjectIdentifier oid = GetOid(name); + return oid == null ? null : GetByOid(oid); + } + + /// <summary>Look up an <see cref="X9ECParametersHolder"/> for the curve with the given name.</summary> + /// <remarks> + /// Allows accessing the <see cref="Math.EC.ECCurve">curve</see> without necessarily triggering the creation of + /// the full <see cref="X9ECParameters"/>. + /// </remarks> + /// <param name="name">The name of the curve.</param> + public static X9ECParametersHolder GetByNameLazy(string name) + { + DerObjectIdentifier oid = GetOid(name); + return oid == null ? null : GetByOidLazy(oid); + } + + /// <summary>Look up the <see cref="X9ECParameters"/> for the curve with the given + /// <see cref="DerObjectIdentifier">OID</see>.</summary> + /// <param name="oid">The <see cref="DerObjectIdentifier">OID</see> for the curve.</param> + public static X9ECParameters GetByOid(DerObjectIdentifier oid) + { + return GetByOidLazy(oid)?.Parameters; + } + + /// <summary>Look up an <see cref="X9ECParametersHolder"/> for the curve with the given + /// <see cref="DerObjectIdentifier">OID</see>.</summary> + /// <remarks> + /// Allows accessing the <see cref="Math.EC.ECCurve">curve</see> without necessarily triggering the creation of + /// the full <see cref="X9ECParameters"/>. + /// </remarks> + /// <param name="oid">The <see cref="DerObjectIdentifier">OID</see> for the curve.</param> + public static X9ECParametersHolder GetByOidLazy(DerObjectIdentifier oid) + { + return names.ContainsKey(oid) ? FindByOidLazy(oid) : null; + } + + /// <summary>Look up the name of the curve with the given <see cref="DerObjectIdentifier">OID</see>.</summary> + /// <param name="oid">The <see cref="DerObjectIdentifier">OID</see> for the curve.</param> + public static string GetName(DerObjectIdentifier oid) + { + return CollectionUtilities.GetValueOrNull(names, oid); + } + + /// <summary>Look up the <see cref="DerObjectIdentifier">OID</see> of the curve with the given name.</summary> + /// <param name="name">The name of the curve.</param> + public static DerObjectIdentifier GetOid(string name) + { + return CollectionUtilities.GetValueOrNull(objIds, name); + } + + /// <summary>Enumerate the available curve names in this registry.</summary> + public static IEnumerable<string> Names + { + get { return CollectionUtilities.Proxy(objIds.Keys); } + } + } +} diff --git a/crypto/test/src/crypto/test/OpenSshKeyParsingTest.cs b/crypto/test/src/crypto/test/OpenSshKeyParsingTest.cs new file mode 100644 index 000000000..02559b5c9 --- /dev/null +++ b/crypto/test/src/crypto/test/OpenSshKeyParsingTest.cs @@ -0,0 +1,490 @@ +using System; +using System.IO; + +using NUnit.Framework; + +using Org.BouncyCastle.Crypto.Engines; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Crypto.Signers; +using Org.BouncyCastle.Crypto.Utilities; +using Org.BouncyCastle.Math; +using Org.BouncyCastle.Security; +using Org.BouncyCastle.Utilities; +using Org.BouncyCastle.Utilities.Encoders; +using Org.BouncyCastle.Utilities.IO.Pem; + +namespace Org.BouncyCastle.Crypto.Tests +{ + [TestFixture] + public class OpenSshKeyParsingTest + { + private static SecureRandom secureRandom = new SecureRandom(); + + private static readonly string rsa1024Key = + "-----BEGIN OPENSSH PRIVATE KEY-----\n" + + "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAlwAAAAdzc2gtcn\n" + + "NhAAAAAwEAAQAAAIEA37C9iHf9kS3ekS8xVE4p5/bmA7Yc37gXqN10W6c53FzVMiT9ZzVm\n" + + "GXqJCRTpLjlX4NgRGHK3nLwyrEhR5JmTrLAXfwb04y3AcdZWZwkZBiXR2rFToEnXNobrvG\n" + + "gmXEshBvCq6kUcGWf1FnW4av0kbVRkfiAjM1aMae1KIwlNMDcAAAIIVPY+b1T2Pm8AAAAH\n" + + "c3NoLXJzYQAAAIEA37C9iHf9kS3ekS8xVE4p5/bmA7Yc37gXqN10W6c53FzVMiT9ZzVmGX\n" + + "qJCRTpLjlX4NgRGHK3nLwyrEhR5JmTrLAXfwb04y3AcdZWZwkZBiXR2rFToEnXNobrvGgm\n" + + "XEshBvCq6kUcGWf1FnW4av0kbVRkfiAjM1aMae1KIwlNMDcAAAADAQABAAAAgCWqIc/HvH\n" + + "dkjNRPaPP0EVRQm1xGnsgAvGMfnscL+k8jhnZiChUFxcJGgqp3zeeNmkFuwDoonsgSXEns\n" + + "B3YBcf7SE//XNMGrGi2FAQTccoTm80NLY77wONST2DNPqxY5xTsTiOJx/DPnru84laq1ae\n" + + "t7WiNZCxsmuC0sPYDAG515AAAAQQDzeUo4QQbByJ9JVS0zcj26HKwGZSxxVb1Flq2Y+w0W\n" + + "E/4GuYvh3ujXlwEankjYUNGNI0/u0NCzuDPZzBx9LZdeAAAAQQD9TiakDmscY9Dd8bEBL+\n" + + "cAhCHrdxtx9ND/793cQNkpm10NL0Fz4jXQfn2/Z7nLFKmMzJlQXzUHH/itzWg9s0MlAAAA\n" + + "QQDiEe/BJMLRZ+94n98VCEr7E+eG2isQctxiAowH7o/wp5WAkFSD9W58dqUobuneXleG+F\n" + + "DAfXzFhYvNE+TdLXUrAAAADm1hcmtAYmFybmFjbGVzAQIDBA==\n" + + "-----END OPENSSH PRIVATE KEY-----\n"; + private static readonly string rsa2048Key = + "-----BEGIN OPENSSH PRIVATE KEY-----\n" + + "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABFwAAAAdzc2gtcn\n" + + "NhAAAAAwEAAQAAAQEArxWa1zW+Uf0lUrYoL1yqgTYUT1TfUkfojrhguPB1s/1AEMj8sueu\n" + + "YDtLozZW/GB+KwO+nzC48CmqsCbCEOqalmdRIQCCQIBs776c0KLnhqzHCmj0Q+6gM0KvUG\n" + + "z8elzJ8LZuTj5xGRDvFxli4yl2M119X7K2JMci18N95rszioxDECSWg2Arvd25kMKBK5MA\n" + + "qJjosvxr46soRmxiAHeGzinoLXgpLh9axwySpJ0WVGPl079ZtaYs/XpSoh9HXqCgwnsVy9\n" + + "JscWbmtaAktjMw2zTfOvmFs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U63Tmh+2NcB1I6Sb0/CwpBgLH1y0CTB9r\n" + + "c8TLSs6HoHx1lfzOp6Yj7BQ9CWHS94Mi+RYBF+SpaMLoZKqCU4Q3UWiHiOyPnMaohAdvRE\n" + + "gJkaY2OAkFaaCI31rwBrs6b5U/ErtRTUZNJEI7OCi6wDBfBwAAAIEA0ZKyuUW5+VFcTyuR\n" + + "1G0ky5uihtJryFCjA2fzu7tgobm0gsIgSDClp9TdMh5CDyJo0R9fQnH8Lki0Ku+jgc4X+a\n" + + "/XMw47d1iL7Hdu9NAJsplezKD5Unso4xJRXhLnXUT5FT8lSgwE+9xUBuILKUmZQa20ejKM\n" + + "20U6szOxEEclA/8AAAAObWFya0BiYXJuYWNsZXMBAgMEBQ==\n" + + "-----END OPENSSH PRIVATE KEY-----\n"; + private static readonly string rsa3072Key = + "-----BEGIN OPENSSH PRIVATE KEY-----\n" + + "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn\n" + + "NhAAAAAwEAAQAAAYEA34VbMJbV2+ZJyRQANnFkTPNcSPkjBllNbnUrlGFQ9wxRyr6xiVRj\n" + + "LrjIL+dXaJRhFNktI9191AJI9Eiq9+aWnrjH0/SB38L1MRcktuvBwraPO8K0Pj8A2FkqI0\n" + + "uc/XrHLrkg7YbW/So1us1TppOYzuBtGzb8yg2/r+i3ghWT8+h7DWo55pTQGaTHnVyoPPqz\n" + + "IDV9yt63tGeL9M3T+Ts9VIkidjV1XXqitkEtksB7cykt4AV0lkN1BWDNbt71YuYhLjDvTK\n" + + "jzVq3MfYV91Ux9XaL2uF6pD+0kmn8oNEQ7VRAUFlno1/tsdp578vZDd/ycRfOy9GRLqJ5L\n" + + "4mXBsbqxKH9wscHptMgDtqe8B7CxEgU5EZyp8zySPSlwPBebfnr1vemgH4GBfDOA1gZeTK\n" + + "HxiWXXUZBMj+S/fJ1YFJ3c5L3ZcHoES3FiIEy2w7tAwfSubkKbP5Wx0h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v8QikNzurNUuu\n" + + "EBjaVBIjXjgGujTZRuEkpdblHDnoMoSha8JRkBFmokJJT/pF42BwptUHZ07tHT7dqn6zvQ\n" + + "TRTq+HqAmOibx2mxp+aT5KtUuJA/krMNlhqlTKqvOFx/4t5kZ6ciYoVg/DZe717ONZAAAA\n" + + "wCK0Mvik0w29hYEE+hsyLBFQ2CkEpKzvyyIVmckJGJ8zAjjhhs/XUrZGRiKD1swK36YGyd\n" + + "+EnZ7gPATWo6CUJmIbkZvZ3hfVljXSvCHPwg8iGo1MiqHWY4MfIhOgVf/lKB7Mfuj9iF0i\n" + + "WZK3bZvaFY3+uVfTtWO/JfcmWevLeALBDJztaGmO1IPpleh9FMSDa5fK0w3MJfHSAz/YUc\n" + + "maU/1Hz/GdLzgaViewb7Me+Iys27d1YyPwbeXip/vaCPt7bAAAAMEA8+eoaMTJP6FLYC8a\n" + + "IVFfx5OLw4xJo6xRNR2QvcNlneh+uvGK0wEwBnkAL9PURmlQEhFcQdSmIHGKQBUGpQ1Huw\n" + + "ahWPlaSW9xau2vAvJH3oNoocak35fBfLjEI2UNpRHqhLST7aAe4sEw8xP+5khr/NptEk5C\n" + + "X4mRq/4p8REm21tFZt8+VX2DtEKMlYqgAfacgcgV4i2aeo8CJJocH1magby5ZaHJIectAX\n" + + "XHszQAm/CaRNWk7rYyjWLxZgASJ4a/AAAAwQDqmu0ZPlkyULFOk/iScA7vYbfnGWT4qC/m\n" + + "I54sFDulMN847grXfbyri7kf57KBFXbCh7tQb1Xn947MEKu+ibchkntlKxgCJQzH6dxktq\n" + + "yy49d+WLqfjYq1AyDIpgmcdu3pVc8Rxi4GpsHZG1DBf4H9Kc5hw9YnqYXhHHwINNWa07ry\n" + + "xcxQuK2sGkRT7Q2NdfEQ9LG4GNIusJeISJgY9NdDBaXrSODSkJI2KCOxDlNY5NsNXXc0Ty\n" + + "7fLQW04MPjqisAAAAObWFya0BiYXJuYWNsZXMBAgMEBQ==\n" + + "-----END OPENSSH PRIVATE KEY-----\n"; + private static readonly string rsa4096Key = + "-----BEGIN OPENSSH PRIVATE KEY-----\n" + + "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAACFwAAAAdzc2gtcn\n" + + "NhAAAAAwEAAQAAAgEA2UjzaFgy2oYc6eyCk2tHEhMw/D807dSgVmOJz6ZXfbxIgh5aptbj\n" + + "ZG7s2nCR+eURRjVv8avxtB7+sYPirqdch30yaysDAbWtOKTw4efCoxv7ENlcK+hki1Hy+I\n" + + "b0epKQ5qit1k83i5XQbKK98GpKkdunMu2XsOrdZfeM/ALzPKN0ZB+vCbyBQdOy+cauRIdl\n" + + "5ON26RxeTXGFF1UvCZ1d+vZjdce27fxLnM0Df6SdLY5H9m3Y9lm6R4DFHEttvvSnpVj4Ra\n" + + "3lahm7BMBIY5RARuBP4PFewKWcc+ubpq4o01r3D7RX/HswRn2QC86ZiAh6LltRjmSnp0yU\n" + + "iM7SBP7Pdsccb/Vx571YWTileWz1Wc6eEEaBSDaV4aTCSsgEbFpxsqDQ95pee59oJmdLkT\n" + + "NK1sT2ydhfMORCOcl1b4mJhll5zEoICZ8yJt4VNc5zCnu5d77taQKEh7XTaym8Hkp4ROqb\n" + + "Tk/en9HIqvfiTNnVmRGg/S0xkmsIChD7U4ax8CPUHL9EdpwA548PzEyM3ZCH4Zn8V3BTkA\n" + + "1qzDATdB788yGGOfMUmPrj2MMKd+RRuIN8FbHxP8jFVMKZSwwSU0qURItjnb5Xb/qiQr2h\n" + + "Zt6qv3HHFjEhKzKa7H+hDh/CeCQjgH1BnltkzrGgxwQgMDboIq8R2CPkcf1xuNs4PFbxfn\n" + + "cAAAdIBSO/QAUjv0AAAAAHc3NoLXJzYQAAAgEA2UjzaFgy2oYc6eyCk2tHEhMw/D807dSg\n" + + "VmOJz6ZXfbxIgh5aptbjZG7s2nCR+eURRjVv8avxtB7+sYPirqdch30yaysDAbWtOKTw4e\n" + + "fCoxv7ENlcK+hki1Hy+Ib0epKQ5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MHgdTQUsFDHZ5RD3C+A1Jbu\n" + + "Fx9m8zzFcnvElz4rJmRTT53s+iZokvIB1XM4g7V4jAknLHlyUe5L/iCGAinP9mLGFWtDTH\n" + + "Z+NXL+uhB66XcgXgovFEy8WkPu7GJoxBf7ZgYKEodAWv+Etcdp6Zzr/yivzpQDrzZr6SgS\n" + + "U1lKaBP8mrEwX/TU0rrvyIx04/WVxtmA1vmSWweEyMiQxbLmWngWwrQVXTa1N5AZorzHSs\n" + + "7NalafAFnf+Sg12wVD6f0ujP/ozQ24Arzc5rmE/AV+XJ7vqnjS1CeHSxTHPYrpKtC6mFQy\n" + + "S+iAb4yzfmFnAAAADm1hcmtAYmFybmFjbGVzAQIDBA==\n" + + "-----END OPENSSH PRIVATE KEY-----\n"; + private static readonly string ecdsa256Key = + "-----BEGIN OPENSSH PRIVATE KEY-----\n" + + "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNlY2RzYS\n" + + "1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQS9VjynnoLGUcT2hXXPkFwGfbleI4Ln\n" + + "1kkgt2UgibKXw9NtesSqpKdEBDW5Kh2nmqLCIk+fdbsTGkxlfaYBtUrkAAAAqBQCER8UAh\n" + + "EfAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBL1WPKeegsZRxPaF\n" + + "dc+QXAZ9uV4jgufWSSC3ZSCJspfD0216xKqkp0QENbkqHaeaosIiT591uxMaTGV9pgG1Su\n" + + "QAAAAgbAJJUVcjwwU/olgrxgINJ1DViX6GcCBhgeH8wAXiNKoAAAAObWFya0BiYXJuYWNs\n" + + "ZXMBAg==\n" + + "-----END OPENSSH PRIVATE KEY-----\n"; + private static readonly string ecdsa384Key = + "-----BEGIN OPENSSH PRIVATE KEY-----\n" + + "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAiAAAABNlY2RzYS\n" + + "1zaGEyLW5pc3RwMzg0AAAACG5pc3RwMzg0AAAAYQS0yKimt2kBeyNKUqNivPfSPBVyU4jH\n" + + "9+6hNsRIJG4NKRgKdIOIiOOLm6pGLUmwN4yDS+0ssdPxwRthQzL879HRtwbqAAb1ShK0CT\n" + + "rljAhk9+SUgrOqWnKL2Ngo1uU5KZgAAADYJC2IQSQtiEEAAAATZWNkc2Etc2hhMi1uaXN0\n" + + "cDM4NAAAAAhuaXN0cDM4NAAAAGEEtMioprdpAXsjSlKjYrz30jwVclOIx/fuoTbESCRuDS\n" + + "kYCnSDiIjji5uqRi1JsDeMg0vtLLHT8cEbYUMy/O/R0bcG6gAG9UoStAk65YwIZPfklIKz\n" + + "qlpyi9jYKNblOSmYAAAAMQChvecXe7PGUVG0Pz2IgM9f80YLXdarf98sRptbGSIPwu8KlW\n" + + "OlGv0Any5ue51/I5wAAAAObWFya0BiYXJuYWNsZXMB\n" + + "-----END OPENSSH PRIVATE KEY-----\n"; + private static readonly string ecdsa521Key = + "-----BEGIN OPENSSH PRIVATE KEY-----\n" + + "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAArAAAABNlY2RzYS\n" + + "1zaGEyLW5pc3RwNTIxAAAACG5pc3RwNTIxAAAAhQQA90An5exsl3UEU0d8fhqV8rgmoyzJ\n" + + "21sZYrjFV+bs583tbSIMYAapk8jSKtk+r1z48KQdsR9czydmy2yYbdXruXMBPdQrf+11BB\n" + + "dCs1E9iFet1UB8OruVeduD5dm0In7yJK1Qo18xe0NpOjOHeZ1ixAxdOt9zuolAlBTwZYth\n" + + "FMESME8AAAEQApLNRAKSzUQAAAATZWNkc2Etc2hhMi1uaXN0cDUyMQAAAAhuaXN0cDUyMQ\n" + + "AAAIUEAPdAJ+XsbJd1BFNHfH4alfK4JqMsydtbGWK4xVfm7OfN7W0iDGAGqZPI0irZPq9c\n" + + "+PCkHbEfXM8nZstsmG3V67lzAT3UK3/tdQQXQrNRPYhXrdVAfDq7lXnbg+XZtCJ+8iStUK\n" + + "NfMXtDaTozh3mdYsQMXTrfc7qJQJQU8GWLYRTBEjBPAAAAQgFHl5a1JDqcCeaAx84z3u/v\n" + + "z7dyVl4uohlQPaiZ+hhtbbUg6oLMnVGGjjmviR0C0aDzx0xDEsK8TseFd16mBWpOnAAAAA\n" + + "5tYXJrQGJhcm5hY2xlcwECAwQ=\n" + + "-----END OPENSSH PRIVATE KEY-----\n"; + + [Test] + public void TestDsa() + { + var pubSpec = OpenSshPublicKeyUtilities.ParsePublicKey(Base64.Decode("AAAAB3NzaC1kc3MAAACBAJBB5+S4kZZYZLswaQ/zm3GM7YWmHsumwo/Xxu+z6Cg2l5PUoiBBZ4ET9EhhQuL2ja/zrCMCi0ZwiSRuSp36ayPrHLbNJb3VdOuJg8xExRa6F3YfVZfcTPUEKh6FU72fI31HrQmi4rpyHnWxL/iDX496ZG2Hdq6UkPISQpQwj4TtAAAAFQCP9TXcVahR/2rpfEhvdXR0PfhbRwAAAIBdXzAVqoOtb9zog6lNF1cGS1S06W9W/clvuwq2xF1s3bkoI/xUbFSc0IAPsGl2kcB61PAZqcop50lgpvYzt8cq/tbqz3ypq1dCQ0xdmJHj975QsRFax+w6xQ0kgpBhwcS2EOizKb+C+tRzndGpcDSoSMuVXp9i4wn5pJSTZxAYFQAAAIEAhQZc687zYxrEDR/1q6m4hw5GFxuVvLsC+bSHtMF0c11Qy4IPg7mBeP7K5Kq4WyJPtmZhuc5Bb12bJQR6qgd1uLn692fe1UK2kM6eWXBzhlzZ54BslfSKHGNN4qH+ln3Zaf/4rpKE7fvoinkrgkOZmj0PMx9D6wlpHKkXMUxeXtc=")); + + var privSpec = ParsePrivateKeyData("-----BEGIN DSA PRIVATE KEY-----\n" + + "MIIBuwIBAAKBgQCQQefkuJGWWGS7MGkP85txjO2Fph7LpsKP18bvs+goNpeT1KIg\n" + + "QWeBE/RIYULi9o2v86wjAotGcIkkbkqd+msj6xy2zSW91XTriYPMRMUWuhd2H1WX\n" + + "3Ez1BCoehVO9nyN9R60JouK6ch51sS/4g1+PemRth3aulJDyEkKUMI+E7QIVAI/1\n" + + "NdxVqFH/aul8SG91dHQ9+FtHAoGAXV8wFaqDrW/c6IOpTRdXBktUtOlvVv3Jb7sK\n" + + "tsRdbN25KCP8VGxUnNCAD7BpdpHAetTwGanKKedJYKb2M7fHKv7W6s98qatXQkNM\n" + + "XZiR4/e+ULERWsfsOsUNJIKQYcHEthDosym/gvrUc53RqXA0qEjLlV6fYuMJ+aSU\n" + + "k2cQGBUCgYEAhQZc687zYxrEDR/1q6m4hw5GFxuVvLsC+bSHtMF0c11Qy4IPg7mB\n" + + "eP7K5Kq4WyJPtmZhuc5Bb12bJQR6qgd1uLn692fe1UK2kM6eWXBzhlzZ54BslfSK\n" + + "HGNN4qH+ln3Zaf/4rpKE7fvoinkrgkOZmj0PMx9D6wlpHKkXMUxeXtcCFELnLOJ8\n" + + "D0akSCUFY/iDLo/KnOIH\n" + + "-----END DSA PRIVATE KEY-----\n"); + + byte[] originalMessage = SecureRandom.GetNextBytes(secureRandom, 10); + + var signer = new DsaSigner(); + signer.Init(true, privSpec); + BigInteger[] rs = signer.GenerateSignature(originalMessage); + + signer.Init(false, pubSpec); + Assert.IsTrue(signer.VerifySignature(originalMessage, rs[0], rs[1]), "DSA test"); + } + + [Test] + public void TestECDsa_CurvesFromSshKeyGen() + { + var pairs = new Tuple<string,string> []{ + Tuple.Create( + "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBBbxKE+/DXstQZmwH7Wso8SUt8LvYoMQpxN/7INC0lMn7mNCbxJcSOCfucBuWOrdoFyFZUkGli2mzKj3hJlcPiI=", + "-----BEGIN OPENSSH PRIVATE KEY-----\n" + + "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNlY2RzYS\n" + + "1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQQW8ShPvw17LUGZsB+1rKPElLfC72KD\n" + + "EKcTf+yDQtJTJ+5jQm8SXEjgn7nAbljq3aBchWVJBpYtpsyo94SZXD4iAAAAuKFclDShXJ\n" + + "Q0AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBBbxKE+/DXstQZmw\n" + + "H7Wso8SUt8LvYoMQpxN/7INC0lMn7mNCbxJcSOCfucBuWOrdoFyFZUkGli2mzKj3hJlcPi\n" + + "IAAAAhAP4L/ciGBDF4HoQSvMaKM8svW4Ss0uYi7HkZ1sn/zCe0AAAAHW1lZ2Fud29vZHNA\n" + + "dHljaGUtMzI2NS5nYXRld2F5AQI=\n" + + "-----END OPENSSH PRIVATE KEY-----\n" + ), + Tuple.Create( + "AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBOT0Cc/zauJsOWo/0P0sMNeyFI5Enz3+lKJtjWXQD7DpFgZmG5Ise8IXR5/ot7fo0kWlYQrye/uSmNmWBuDvOpBCHOnyR6Kaej36qoOO/gwbH+mezSYXSxCTA9Qb8VzxLA==", + "-----BEGIN OPENSSH PRIVATE KEY-----\n" + + "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAiAAAABNlY2RzYS\n" + + "1zaGEyLW5pc3RwMzg0AAAACG5pc3RwMzg0AAAAYQTk9AnP82ribDlqP9D9LDDXshSORJ89\n" + + "/pSibY1l0A+w6RYGZhuSLHvCF0ef6Le36NJFpWEK8nv7kpjZlgbg7zqQQhzp8keimno9+q\n" + + "qDjv4MGx/pns0mF0sQkwPUG/Fc8SwAAADorZ3naK2d52gAAAATZWNkc2Etc2hhMi1uaXN0\n" + + "cDM4NAAAAAhuaXN0cDM4NAAAAGEE5PQJz/Nq4mw5aj/Q/Sww17IUjkSfPf6Uom2NZdAPsO\n" + + "kWBmYbkix7whdHn+i3t+jSRaVhCvJ7+5KY2ZYG4O86kEIc6fJHopp6Pfqqg47+DBsf6Z7N\n" + + "JhdLEJMD1BvxXPEsAAAAMQDLno+rINnY7/Ht1WmSGZYJ3EMPtysbxuBnQFEL4USa3kyAb1\n" + + "QMR6+jtqraKtE7kLwAAAAdbWVnYW53b29kc0B0eWNoZS0zMjY1LmdhdGV3YXkBAg==\n" + + "-----END OPENSSH PRIVATE KEY-----\n" + ), + Tuple.Create( + "AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBADXE/q1WSR002vRI+tiPLpdRjzeymSk+RjD7ZIC9CndqLmI0rhTMh5xReAzved12BH9lQJIGIw4YoIQDudsMbRUsQEjFvbFzSXLJBYWdZf8Voa/97/R9w/i8bKUMUPP0disypZlGdQn5+XvzHG6bhX2Qr9aJacGFZoVHugF/M8QyC+GyA==", + "-----BEGIN OPENSSH PRIVATE KEY-----\n" + + "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAArAAAABNlY2RzYS\n" + + "1zaGEyLW5pc3RwNTIxAAAACG5pc3RwNTIxAAAAhQQA1xP6tVkkdNNr0SPrYjy6XUY83spk\n" + + "pPkYw+2SAvQp3ai5iNK4UzIecUXgM73nddgR/ZUCSBiMOGKCEA7nbDG0VLEBIxb2xc0lyy\n" + + "QWFnWX/FaGv/e/0fcP4vGylDFDz9HYrMqWZRnUJ+fl78xxum4V9kK/WiWnBhWaFR7oBfzP\n" + + "EMgvhsgAAAEgs+rbdbPq23UAAAATZWNkc2Etc2hhMi1uaXN0cDUyMQAAAAhuaXN0cDUyMQ\n" + + "AAAIUEANcT+rVZJHTTa9Ej62I8ul1GPN7KZKT5GMPtkgL0Kd2ouYjSuFMyHnFF4DO953XY\n" + + "Ef2VAkgYjDhighAO52wxtFSxASMW9sXNJcskFhZ1l/xWhr/3v9H3D+LxspQxQ8/R2KzKlm\n" + + "UZ1Cfn5e/McbpuFfZCv1olpwYVmhUe6AX8zxDIL4bIAAAAQgCM8ojULpNk3UhBZhPfK+Tw\n" + + "QjT9MHU0OTi4twvKPAE0vOLQ/C1g9AMlspyKxS2NKx2gxxXISowFGNL6Jkx9198ElQAAAB\n" + + "1tZWdhbndvb2RzQHR5Y2hlLTMyNjUuZ2F0ZXdheQECAwQF\n" + + "-----END OPENSSH PRIVATE KEY-----\n" + ) + }; + + string[] ecPriv = { ecdsa256Key, ecdsa384Key, ecdsa521Key }; + for (int i = 0; i != ecPriv.Length; i++) + { + var privKey = (ECPrivateKeyParameters)ParsePrivateKeyData(ecPriv[i]); + + var q = privKey.Parameters.G.Multiply(privKey.D); + + DoECSigTest(new ECPublicKeyParameters(q, privKey.Parameters), privKey); + } + + for (int i = 0; i != pairs.Length; i++) + { + var pair = pairs[i]; + + var pubSpec = OpenSshPublicKeyUtilities.ParsePublicKey(Base64.Decode(pair.Item1)); + var privSpec = ParsePrivateKeyData(pair.Item2); + + DoECSigTest(pubSpec, privSpec); + + // + // Test encode + // + var recoveredPubKey = OpenSshPublicKeyUtilities.ParsePublicKey( + OpenSshPublicKeyUtilities.EncodePublicKey((AsymmetricKeyParameter)pubSpec)); + var recoveredPrivateKey = OpenSshPrivateKeyUtilities.ParsePrivateKeyBlob( + OpenSshPrivateKeyUtilities.EncodePrivateKey((AsymmetricKeyParameter)privSpec)); + + byte[] originalMessage = SecureRandom.GetNextBytes(secureRandom, 10); + + var signer = new ECDsaSigner(); + signer.Init(true, privSpec); + BigInteger[] rs = signer.GenerateSignature(originalMessage); + + signer.Init(false, pubSpec); + Assert.IsTrue(signer.VerifySignature(originalMessage, rs[0], rs[1]), + "ECDSA test post encoded / Decode"); + } + + } + + private void DoECSigTest(AsymmetricKeyParameter pubSpec, AsymmetricKeyParameter privSpec) + { + byte[] originalMessage = SecureRandom.GetNextBytes(secureRandom, 10); + + var signer = new ECDsaSigner(); + signer.Init(true, privSpec); + BigInteger[] rs = signer.GenerateSignature(originalMessage); + + signer.Init(false, pubSpec); + Assert.IsTrue(signer.VerifySignature(originalMessage, rs[0], rs[1]), "ECDSA test"); + } + + [Test] + public void TestECDsa() + { + var pubSpec = OpenSshPublicKeyUtilities.ParsePublicKey( + Base64.Decode("AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBHq5qxGqnh93Gpbj2w1Avx1UwBl6z5bZC3Viog1yNHDZYcV6Da4YQ3i0/hN7xY7sUy9dNF6g16tJSYXQQ4tvO3g=")); + + var privSpec = ParsePrivateKeyData("-----BEGIN EC PRIVATE KEY-----\n" + + "MHcCAQEEIHeg/+m02j6nr4bO8ubfbzhs0fqOjiuIoWbvGnVg+FmpoAoGCCqGSM49\n" + + "AwEHoUQDQgAEermrEaqeH3caluPbDUC/HVTAGXrPltkLdWKiDXI0cNlhxXoNrhhD\n" + + "eLT+E3vFjuxTL100XqDXq0lJhdBDi287eA==\n" + + "-----END EC PRIVATE KEY-----\n"); + + DoECSigTest(pubSpec, privSpec); + } + + [Test] + public void TestEd25519() + { + var pubSpec = OpenSshPublicKeyUtilities.ParsePublicKey( + Base64.Decode("AAAAC3NzaC1lZDI1NTE5AAAAIM4CaV7WQcy0lht0hclgXf4Olyvzvv2fnUvQ3J8IYsWF")); + + var privSpec = ParsePrivateKeyData("-----BEGIN OPENSSH PRIVATE KEY-----\n" + + "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\n" + + "QyNTUxOQAAACDOAmle1kHMtJYbdIXJYF3+Dpcr8779n51L0NyfCGLFhQAAAKBTr4PvU6+D\n" + + "7wAAAAtzc2gtZWQyNTUxOQAAACDOAmle1kHMtJYbdIXJYF3+Dpcr8779n51L0NyfCGLFhQ\n" + + "AAAED4BTHeR3YD7CFQqusztfL5K+YSD4mRGLBwb7jHiXxIJM4CaV7WQcy0lht0hclgXf4O\n" + + "lyvzvv2fnUvQ3J8IYsWFAAAAG21lZ2Fud29vZHNAdHljaGUtMzI2NS5sb2NhbAEC\n" + + "-----END OPENSSH PRIVATE KEY-----\n"); + + byte[] originalMessage = SecureRandom.GetNextBytes(secureRandom, 10); + + Ed25519Signer signer = new Ed25519Signer(); + signer.Init(true, privSpec); + signer.BlockUpdate(originalMessage, 0, originalMessage.Length); + byte[] sig = signer.GenerateSignature(); + + signer.Init(false, pubSpec); + signer.BlockUpdate(originalMessage, 0, originalMessage.Length); + Assert.IsTrue(signer.VerifySignature(sig), "ED25519Signer test"); + } + + [Test] + public void TestFailures() + { + var data = "-----BEGIN OPENSSH PRIVATE KEY-----\n" + + "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\n" + + "QyNTUxOQAAACDOAmle1kHMtJYbdIXJYF3+Dpcr8779n51L0NyfCGLFhQAAAKBTr4PvU6+D\n" + + "7wAAAAtzc2gtZWQyNTUxOQAAACDOAmle1kHMtJYbdIXJYF3+Dpcr8779n51L0NyfCGLFhQ\n" + + "AAAED4BTHeR3YD7CFQqusztfL5K+YSD4mRGLBwb7jHiXxIJM4CaV7WQcy0lht0hclgXf4O\n" + + "lyvzvv2fnUvQ3J8IYsWFAAAAG21lZ2Fud29vZHNAdHljaGUtMzI2NS5sb2NhbAEC\n" + + "-----END OPENSSH PRIVATE KEY-----\n"; + + byte[] blob; + using (var pemReader = new PemReader(new StringReader(data))) + { + blob = pemReader.ReadPemObject().Content; + } + + // + // Altering the check value. + // + blob[98] ^= 1; + + try + { + var privSpec = OpenSshPrivateKeyUtilities.ParsePrivateKeyBlob(blob); + Assert.Fail("Change should trigger failure."); + } + catch (InvalidOperationException iles) + { + Assert.AreEqual("private key check values are not the same", iles.Message, "Check value mismatch"); + } + + // + // Altering the cipher name. + // + + data = "-----BEGIN OPENSSH PRIVATE KEY-----\n" + + "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\n" + + "QyNTUxOQAAACDOAmle1kHMtJYbdIXJYF3+Dpcr8779n51L0NyfCGLFhQAAAKBTr4PvU6+D\n" + + "7wAAAAtzc2gtZWQyNTUxOQAAACDOAmle1kHMtJYbdIXJYF3+Dpcr8779n51L0NyfCGLFhQ\n" + + "AAAED4BTHeR3YD7CFQqusztfL5K+YSD4mRGLBwb7jHiXxIJM4CaV7WQcy0lht0hclgXf4O\n" + + "lyvzvv2fnUvQ3J8IYsWFAAAAG21lZ2Fud29vZHNAdHljaGUtMzI2NS5sb2NhbAEC\n" + + "-----END OPENSSH PRIVATE KEY-----\n"; + + using (var pemReader = new PemReader(new StringReader(data))) + { + blob = pemReader.ReadPemObject().Content; + } + + blob[19] = (byte)'C'; + + try + { + var privSpec = OpenSshPrivateKeyUtilities.ParsePrivateKeyBlob(blob); + Assert.Fail("Change should trigger failure."); + } + catch (InvalidOperationException iles) + { + Assert.AreEqual("encrypted keys not supported", iles.Message, "enc keys not supported"); + } + } + + [Test] + public void TestRSA() + { + var pubSpec = OpenSshPublicKeyUtilities.ParsePublicKey( + Base64.Decode("AAAAB3NzaC1yc2EAAAADAQABAAAAgQDvh2BophdIp8ojwGZQR0FQ/awowXnV24nAPm+/na8MOUrdySNhOnlek4LAZl82/+Eu2t21XD6hQUiHKAj6XaNFBthTuss7Cz/tA348DLEMHD9wUtT0FXVmsxqN4BfusunbcULxxVWG2z8FvqeaGgc/Unkp9y7/kyf54pPUCBcClw==")); + + var privSpec = ParsePrivateKeyData("-----BEGIN RSA PRIVATE KEY-----\n" + + "MIICXgIBAAKBgQDvh2BophdIp8ojwGZQR0FQ/awowXnV24nAPm+/na8MOUrdySNh\n" + + "Onlek4LAZl82/+Eu2t21XD6hQUiHKAj6XaNFBthTuss7Cz/tA348DLEMHD9wUtT0\n" + + "FXVmsxqN4BfusunbcULxxVWG2z8FvqeaGgc/Unkp9y7/kyf54pPUCBcClwIDAQAB\n" + + "AoGBAOMXYEoXHgAeREE9CkOWKtDUkEJbnF0rNSB0kZIDt5BJSTeYmNh3jdYi2FX9\n" + + "OMx2MFIx4v0tJZvQvyiUxl5IJJ9ZJsYUWF+6VbcTVwYYfdVzZzP2TNyGmF9/ADZW\n" + + "wBehqP04uRlYjt94kqb4HoOKF3gJ3LC4uW9xcEltTBeHWCfhAkEA/2biF5St9/Ya\n" + + "540E4zu/FKPsxLSaT8LWCo9+X7IqIzlBQCB4GjM+nZeTm7eZOkfAFZoxwfiNde/9\n" + + "qleXXf6B2QJBAPAW+jDBC3QF4/g8n9cDxm/A3ICmcOFSychLSrydk9ZyRPbTRyQC\n" + + "YlC2mf/pCrO/yO7h189BXyQ3PXOEhnujce8CQQD7gDy0K90EiH0F94AQpA0OLj5B\n" + + "lfc/BAXycEtpwPBtrzvqAg9C/aNzXIgmly10jqNAoo7NDA2BTcrlq0uLa8xBAkBl\n" + + "7Hs+I1XnZXDIO4Rn1VRysN9rRj15ipnbDAuoUwUl7tDUMBFteg2e0kZCW/6NHIgC\n" + + "0aG6fLgVOdY+qi4lYtfFAkEAqqiBgEgSrDmnJLTm6j/Pv1mBA6b9bJbjOqomrDtr\n" + + "AWTXe+/kSCv/jYYdpNA/tDgAwEmtkWWEie6+SwJB5cXXqg==\n" + + "-----END RSA PRIVATE KEY-----\n"); + + DoRSATest(pubSpec, privSpec); + + privSpec = ParsePrivateKeyData(rsa1024Key); + pubSpec = new RsaKeyParameters(false, ((RsaKeyParameters)privSpec).Modulus, ((RsaPrivateCrtKeyParameters)privSpec).PublicExponent); + + DoRSATest(pubSpec, privSpec); + + privSpec = ParsePrivateKeyData(rsa2048Key); + pubSpec = new RsaKeyParameters(false, ((RsaKeyParameters)privSpec).Modulus, ((RsaPrivateCrtKeyParameters)privSpec).PublicExponent); + + DoRSATest(pubSpec, privSpec); + + privSpec = ParsePrivateKeyData(rsa3072Key); + pubSpec = new RsaKeyParameters(false, ((RsaKeyParameters)privSpec).Modulus, ((RsaPrivateCrtKeyParameters)privSpec).PublicExponent); + + DoRSATest(pubSpec, privSpec); + + privSpec = ParsePrivateKeyData(rsa4096Key); + pubSpec = new RsaKeyParameters(false, ((RsaKeyParameters)privSpec).Modulus, ((RsaPrivateCrtKeyParameters)privSpec).PublicExponent); + + DoRSATest(pubSpec, privSpec); + } + + private void DoRSATest(AsymmetricKeyParameter pubSpec, AsymmetricKeyParameter privSpec) + { + byte[] originalMessage = SecureRandom.GetNextBytes(secureRandom, 10); + originalMessage[0] |= 1; + + var rsaEngine = new RsaEngine(); + rsaEngine.Init(true, privSpec); + + byte[] ct = rsaEngine.ProcessBlock(originalMessage, 0, originalMessage.Length); + + rsaEngine.Init(false, pubSpec); + byte[] result = rsaEngine.ProcessBlock(ct, 0, ct.Length); + + Assert.IsTrue(Arrays.AreEqual(originalMessage, result), "Result did not match original message"); + } + + private static AsymmetricKeyParameter ParsePrivateKeyData(string data) + { + using (var pemReader = new PemReader(new StringReader(data))) + { + return OpenSshPrivateKeyUtilities.ParsePrivateKeyBlob(pemReader.ReadPemObject().Content); + } + } + } +} |