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": {
"fs-plus": "~3.1.1",
"node-ssh": "^13.2.0"
"node-ssh": "^13.2.0",
"sshpk": "^1.18.0"
},
"devDependencies": {
"@babel/core": "~7.21.3",

View File

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

View File

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