diff options
Diffstat (limited to 'LibGit2Sharp/SecureUsernamePasswordCredentials.cs')
-rw-r--r-- | LibGit2Sharp/SecureUsernamePasswordCredentials.cs | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/LibGit2Sharp/SecureUsernamePasswordCredentials.cs b/LibGit2Sharp/SecureUsernamePasswordCredentials.cs new file mode 100644 index 00000000..5e1d4931 --- /dev/null +++ b/LibGit2Sharp/SecureUsernamePasswordCredentials.cs @@ -0,0 +1,50 @@ +using System; +using LibGit2Sharp.Core; +using System.Security; +using System.Runtime.InteropServices; + +namespace LibGit2Sharp +{ + /// <summary> + /// Class that uses <see cref="SecureString"/> to hold username and password credentials for remote repository access. + /// </summary> + public sealed class SecureUsernamePasswordCredentials : Credentials + { + /// <summary> + /// Callback to acquire a credential object. + /// </summary> + /// <param name="cred">The newly created credential object.</param> + /// <returns>0 for success, < 0 to indicate an error, > 0 to indicate no credential was acquired.</returns> + protected internal override int GitCredentialHandler(out IntPtr cred) + { + if (Username == null || Password == null) + { + throw new InvalidOperationException("UsernamePasswordCredentials contains a null Username or Password."); + } + + IntPtr passwordPtr = IntPtr.Zero; + + try + { + passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(Password); + + return NativeMethods.git_cred_userpass_plaintext_new(out cred, Username, Marshal.PtrToStringUni(passwordPtr)); + } + finally + { + Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr); + } + + } + + /// <summary> + /// Username for username/password authentication (as in HTTP basic auth). + /// </summary> + public string Username { get; set; } + + /// <summary> + /// Password for username/password authentication (as in HTTP basic auth). + /// </summary> + public SecureString Password { get; set; } + } +} |