@@ -2,7 +2,44 @@ const jwt = require("jsonwebtoken")
22const fs = require ( "fs" )
33const 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
744function SignToken ( payload ) {
845 const options = {
@@ -17,5 +54,8 @@ function DecodeToken(idToken) {
1754 return jwt . decode ( idToken )
1855}
1956
57+ CheckForKey ( )
58+
2059exports . SignToken = SignToken
2160exports . DecodeToken = DecodeToken
61+ exports . CheckForKey = CheckForKey
0 commit comments