Trouble authenticating with SshUserKeyCredentials in libgit2sharp-SSH

2.1k views Asked by At

Having some trouble authenticating with SshUserKeyCredentials using libgit2sharp-SSH:

var co = new CloneOptions();
co.CredentialsProvider = (_url, _user, _cred) => new SshUserKeyCredentials { PrivateKey="C:\\path\\to\\private_key" };
Repository.Clone("git@... .repository.git", path, co);

I found the SshUserKeyCredentials object browsing through the source code so my first question would be if it is possible to use this object to do deploy key based checkout from gitlab?

The object seems to want any combination of PrivateKey, Username, PublicKey and Passphrase. I'm currently using a PrivateKey.

The error I end up with:

{"Failed to start SSH session: Unable to exchange encryption keys"}

If this way isn't supposed to work is there an alternative way of using deploy keys to programmatically manage git from an C# environment?

1

There are 1 answers

3
MikeJansen On BEST ANSWER

I was able to figure out the following through trial-and-error and scouring the web.

  1. You cannot have null for any field; use string.Empty.

  2. Public and private key must be provided and in the proper format.

  3. Private key had to be in PEM format (either use PuttyGen Conversion menu => Export OpenSSH or use openssl rsa -in id_rsa -out id_rsa.pem).

  4. Public key had to be single line, starting with type, followed by base64 key, no comment at the end (this is the format shown in the public key text box on PuttyGen, except you have to remove the comment), e.g.

    ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQEAoblahblahblahblahblah

I added username git because that's what Bitbucket requires. Not sure you need that, but it can't be null, do string.Empty.

Example:

CredentialsHandler handler = (_url, _user, _cred) => new SshUserKeyCredentials
                    {
                        PrivateKey = @"C:\Users\blah\.ssh\keys\bitbucket.pem",
                        Username = "git",
                        Passphrase = string.Empty,
                        PublicKey = @"C:\Users\blah\.ssh\keys\bitbucket.pub"
                    }

See also: PHP ssh2_auth_pubkey_file(): Authentication failed using public key: Invalid key data, not base64 encoded