Skip to content

Commit 50dc93d

Browse files
committed
create RSA keys in runtime
1 parent 296944f commit 50dc93d

File tree

3 files changed

+45
-3
lines changed

3 files changed

+45
-3
lines changed

.dockerignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,5 @@
55
docker-compose.yaml
66
LICENSE
77
*.md
8-
node_modules
8+
node_modules
9+
*.pem

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
.env
22
node_modules
33
**/*.html
4-
!examples
4+
!examples
5+
*.pem

src/token.js

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,44 @@ const jwt = require("jsonwebtoken")
22
const fs = require("fs")
33
const path = require("path")
44

5-
const privateKey = fs.readFileSync(path.join(__dirname, "./keys/private.key"))
5+
const logger = require("./logger")
6+
7+
const { generateKeyPairSync } = require("crypto")
8+
9+
const keyPath = path.join(__dirname, "../secrets/private_key.pem")
10+
11+
let privateKey
12+
13+
function CheckForKey() {
14+
if (fs.existsSync(keyPath)) {
15+
privateKey = fs.readFileSync(keyPath, "utf8")
16+
17+
logger.log("Loaded existing RSA private key")
18+
} else {
19+
const { privateKey: genPrivKey, publicKey: genPubKey } =
20+
generateKeyPairSync("rsa", {
21+
modulusLength: 2048,
22+
publicKeyEncoding: {
23+
type: "spki",
24+
format: "pem",
25+
},
26+
privateKeyEncoding: {
27+
type: "pkcs8",
28+
format: "pem",
29+
},
30+
})
31+
32+
fs.mkdirSync(path.dirname(keyPath), { recursive: true })
33+
fs.writeFileSync(keyPath, genPrivKey)
34+
fs.writeFileSync(
35+
path.join(__dirname, "../secrets/public_key.pem"),
36+
genPubKey
37+
)
38+
privateKey = genPrivKey
39+
40+
logger.log("Generated new RSA key pair")
41+
}
42+
}
643

744
function SignToken(payload) {
845
const options = {
@@ -17,5 +54,8 @@ function DecodeToken(idToken) {
1754
return jwt.decode(idToken)
1855
}
1956

57+
CheckForKey()
58+
2059
exports.SignToken = SignToken
2160
exports.DecodeToken = DecodeToken
61+
exports.CheckForKey = CheckForKey

0 commit comments

Comments
 (0)