feat: create user's ssh key

This commit is contained in:
Levi Yan
2024-10-28 14:58:10 +08:00
parent 4b3868ced2
commit 126f800346
3 changed files with 13 additions and 7 deletions

View File

@@ -98,7 +98,8 @@
}, },
"dependencies": { "dependencies": {
"fs-plus": "~3.1.1", "fs-plus": "~3.1.1",
"node-ssh": "^13.2.0" "node-ssh": "^13.2.0",
"sshpk": "^1.18.0"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "~7.21.3", "@babel/core": "~7.21.3",

View File

@@ -96,7 +96,7 @@ export default class DSHome {
break; break;
} }
case 'createUserPublicKey': case 'createUserPublicKey':
this.user.createUserSSHKey(); await this.user.createUserSSHKey();
if (this.user.existUserPublicKey()) { if (this.user.existUserPublicKey()) {
panel.webview.postMessage({command: 'createUserPublicKey', data: {ok: true}}) panel.webview.postMessage({command: 'createUserPublicKey', data: {ok: true}})
break; break;

View File

@@ -4,7 +4,9 @@ import * as os from 'os';
import * as fs from 'fs'; import * as fs from 'fs';
const { const {
generateKeyPairSync, generateKeyPairSync,
} = require('node:crypto') createHash
} = require('node:crypto');
const sshpk = require('sshpk');
export default class User { export default class User {
private context:vscode.ExtensionContext; private context:vscode.ExtensionContext;
@@ -93,7 +95,7 @@ export default class User {
return fs.readFileSync(userPrivateKey, 'utf-8'); return fs.readFileSync(userPrivateKey, 'utf-8');
} }
public createUserSSHKey() { public async createUserSSHKey() {
if (this.existUserPublicKey() && this.existUserPrivateKey()) { if (this.existUserPublicKey() && this.existUserPrivateKey()) {
// if both public and private key exists, stop // if both public and private key exists, stop
return; return;
@@ -102,7 +104,7 @@ export default class User {
const { const {
publicKey, publicKey,
privateKey, privateKey,
} = generateKeyPairSync('rsa', { } = await generateKeyPairSync('rsa', {
modulusLength: 4096, modulusLength: 4096,
publicKeyEncoding: { publicKeyEncoding: {
type: 'spki', type: 'spki',
@@ -115,10 +117,13 @@ export default class User {
passphrase: 'devstar' passphrase: 'devstar'
}, },
}); });
const publicKeyFingerprint = sshpk.parseKey(publicKey, 'pem').toString('ssh');
const publicKeyStr = publicKeyFingerprint; // public key is public key fingerprint
const privateKeyStr = privateKey;
try { try {
fs.writeFileSync(this.getUserPublicKeyPath(), publicKey); fs.writeFileSync(this.getUserPublicKeyPath(), publicKeyStr);
fs.writeFileSync(this.getUserPrivateKeyPath(), privateKey); fs.writeFileSync(this.getUserPrivateKeyPath(), privateKeyStr);
} catch(error) { } catch(error) {
console.error("Failed to write public/private key into the default ssh public/key file: ", error); console.error("Failed to write public/private key into the default ssh public/key file: ", error);
} }