Recommend way to encrypt the USERID for my SFTP login.

0 votes
asked Jun 1, 2018 by tom.abcd (320 points)

I am using the SFTP client to login and like to know the recommend way to store off my USer ids in some encrypted file.

loginKey = New SshPrivateKey("privatekey.pri")
_client.Login("test", loginKey)

so in my example above I can load in the private key from a file but I do not want to hard code my user id in my .net code.
I was thinking of maybe having the userids in a external file or database that is encrypted.
Do you have any suggestions or examples for this?
I have the Rebex SSH Pack and am using the SFTP client part to connect to external SFTP server.

Thanks
Tom

Applies to: Rebex SFTP

1 Answer

+1 vote
answered Jun 4, 2018 by Lukas Matyska (48,430 points)
selected Jun 4, 2018 by tom.abcd
 
Best answer

Since you use SshPrivateKey for client authentication, you can use it to encrypt the USERID.

Encrypt like this:

// load SSH private key
var pk = new SshPrivateKey("privatekey.pri", "my-password");

string userId = "my-user-id";
using (var alg = new Rebex.Security.Cryptography.AsymmetricKeyAlgorithm())
{
    // import public key
    alg.ImportKey(pk.GetPublicKeyInfo());
    // encrypt data
    byte[] encrypted = alg.Encrypt(Encoding.UTF8.GetBytes(userId));
    // save encrypted data
    File.WriteAllBytes("c:/data/user.id", encrypted);
}

Decrypt like this:

// load SSH private key
var pk = new SshPrivateKey("privatekey.pri", "my-password");

// get private key info
var pki = new PrivateKeyInfo();
pki.Load(new MemoryStream(pk.GetPrivateKey()), null);

string userId;
using (var alg = new Rebex.Security.Cryptography.AsymmetricKeyAlgorithm())
{
    // import private key
    alg.ImportKey(pki);
    // decypt data
    byte[] decrypted = alg.Decrypt(File.ReadAllBytes("c:/data/user.id"));
    // get string representation
    userId = Encoding.UTF8.GetString(decrypted);
}
commented Jun 4, 2018 by tom.abcd (320 points)
Yes this is just what I was looking for.    I had seen the various functions but had not put together using my private key to encrypt other things...

Thanks a lot
Tom
...