@@ -2,7 +2,44 @@ const jwt = require("jsonwebtoken")
2
2
const fs = require ( "fs" )
3
3
const path = require ( "path" )
4
4
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
+ }
6
43
7
44
function SignToken ( payload ) {
8
45
const options = {
@@ -17,5 +54,8 @@ function DecodeToken(idToken) {
17
54
return jwt . decode ( idToken )
18
55
}
19
56
57
+ CheckForKey ( )
58
+
20
59
exports . SignToken = SignToken
21
60
exports . DecodeToken = DecodeToken
61
+ exports . CheckForKey = CheckForKey
0 commit comments