在C#中为Rency SSH.NET创建带有BouncyCastle的SSH ED25519密钥



我必须在ED25519版本(非RSA(中使用BouncyCastle生成公钥和私钥,但我无法正确生成。我尝试过:

var gen = new Ed25519KeyPairGenerator();
var param = new Ed25519KeyGenerationParameters(new SecureRandom());
gen.Init(param);
AsymmetricCipherKeyPair pair = gen.GenerateKeyPair();
string publicKey = string.Empty;
string privateKey = string.Empty;
using (TextWriter textWriter = new StringWriter())
{
var wr = new Org.BouncyCastle.OpenSsl.PemWriter(textWriter);
wr.WriteObject(pair.Private);
wr.Writer.Flush();
privateKey = textWriter.ToString().Replace("PRIVATE", "OPENSSH PRIVATE");
}
using (var textWriter = new StringWriter())
{
var wr = new Org.BouncyCastle.OpenSsl.PemWriter(textWriter);
wr.WriteObject(pair.Public);
wr.Writer.Flush();
publicKey = textWriter.ToString().Replace("PUBLIC", "OPENSSH PUBLIC");
}

但是当我在中添加私钥时

var buf = new MemoryStream(Encoding.UTF8.GetBytes(privateKey));
var privateKeyFile = new PrivateKeyFile(buf, string.Empty);

但是,当我尝试在ssh方法中添加私钥时,会抛出一个异常(格式错误的key.ecc(。特别是如果我生成这个密钥:

-----开始打开私钥-----MFECAQEwBQYDK2VwBCIEICJ/5KrMI49gUFvVIvjpquDDaCrRf+VkrBqmyjjYCXKdgSEAk0u1yhkqEWCIwOoGJCtJBV3Ai/uA9B8cRiXQvq6DmEc=-----结束OPENSSH私钥-----

错误为'此openssh密钥不包含'openssh-key-v1'格式的魔术头

有人能帮我吗?

感谢

此问题已在中解决https://github.com/sshnet/SSH.NET/pull/496

using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Utilities;
using Org.BouncyCastle.Security;
using Renci.SshNet;
public string GenerateEd25519PrivateKey()
{
var generator = new Ed25519KeyPairGenerator();
var parameters = new Ed25519KeyGenerationParameters(new SecureRandom());
generator.Init(parameters);
var keyPair = generator.GenerateKeyPair();
var keyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);
var pubKey = Convert.ToBase64String(keyInfo.GetDerEncoded());
// Add this to ~/.ssh/authorized_keys
var authorizedKey = $"ssh-ed25519 {pubKey} generated-{DateTime.Today:yyyy-MM-dd}";
var ppk = new StringBuilder();
ppk.AppendLine("-----BEGIN OPENSSH PRIVATE KEY-----");
var bytes = OpenSshPrivateKeyUtilities.EncodePrivateKey(keyPair.Private);
ppk.AppendLine(Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks));
ppk.AppendLine("-----END OPENSSH PRIVATE KEY-----");
return ppk.ToString();
}
public PrivateKeyFile ToPrivateKeyFile(string privateKey)
{
using var memory = new MemoryStream(Encoding.UTF8.GetBytes(privateKey));
return new PrivateKeyFile(memory);
}

相关内容

  • 没有找到相关文章

最新更新