0 votes
by (350 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
by (73.5k points)
selected by
 
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);
}
by (350 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
...