【问题标题】:How to generate Public/Private key pairs using openssl in nodejs?如何在nodejs中使用openssl生成公钥/私钥对?
【发布时间】:2019-06-05 17:28:02
【问题描述】:

我是 nodejs 的初学者。由于我在 nodejs 中实现数字签名,所以我想在 node.js 中使用 openssl 生成公钥/私钥对。我已经看过这篇帖子Can't verify signature witn Node.js Crypto, using key pairs,使用密钥对。它使用以下命令来生成密钥对。

$ openssl genrsa -out rsa_1024_priv.pem 1024

$ openssl rsa -in rsa_1024_priv.pem -out rsa_1024_pub.pem -outform PEM -pubout

现在我有以下关于此的问题。

  1. 我们如何使用 node.js 执行这些命令?
  2. 与命令一样,私钥存储在本地计算机上的 rsa_1024_priv.pem 文件中。那么如何在签署一些数据时从这个文件中读取公钥,即 rsa_1024_priv.pem?

【问题讨论】:

    标签: node.js openssl digital-signature


    【解决方案1】:

    您可以使用以下代码: openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem open_code 填写完所需数据后,您可以使用以下代码来使用新生成的密钥并管理请求:

        /*
        *primary file for the api
        *
        * * */
    
        //dependencies    
        const https = require('https')
        const url =require('url')
        const StringDecoder = require('string_decoder').StringDecoder
        const config = require('./config')
        const fs = require('fs')
    
        //a.2. Instantiating the HTTPS server
        const httpsServerOptions = {
        'key':fs.readFileSync('./https/key.pem'),//this is the location of the newly 
                                                 //generated key(point to your file 
                                                 //location)
        'cert':fs.readFileSync('./https/cert.pem')//this is the location of the newly 
                                                 //generated cert file(point to your 
                                                 //file location)
        }
        const httpsServer = https.createServer(httpsServerOptions,(req,res)=>{
        unifiedServer(req,res)
        })
    
        //start the HTTPS server
        httpsServer.listen(config.httpsPort,()=>{
        console.log(`The server is listening on port ${config.httpsPort}`)
        })
    
    ///////////////////////////////////////////////////////////////////////////////
    ////////////////////////HANDLE THE REQUESTS////////////////////////////////////
    
        //All the server logic for for both the http and the https server
        const unifiedServer = (req,res)=>{
        //Get the url and parse it
        const parsedUrl = url.parse(req.url,true)//true:indicates to parse the query 
       string 
        //which means to set the parsedUrl.query value at the equivalent as if we had
        //sent this data to the query string module, so really we are using two 
        modules
        //in one
        //Get the path
        const path = parsedUrl.pathname//the path of the user request
        //http://localhost:3000/foo...
        const trimedPath = path.replace(/^\/+|\/+$/g,'')
    
        //Get the query string as an object:
        const queryStringObject = parsedUrl.query //?mnp=abd
    
        //Get the http method:
        const method = req.method.toLowerCase() //get, post
    
        //Get the headers as an object
        const headers = req.headers //{foo:bar,fizz:buzz,...}
    
        //Get the payload, if any is the text: 'fdsfasdfsadfsd'
    
        const decoder = new StringDecoder('utf-8')//utf-8 is what kind of 
        //charset or encoding it can expect
        //payloads, as part of the http request, come in to the http server as a 
        string
        //so we need to collect that string as it comes in and then when the string 
        tells
        //us what are the end cover last that into one covering thing before we can
        //figure out what the payload is
        let buffer = ''//string where we are going to append the incoming palyload as 
        it comes
    
        req.on('data',data=>{
        buffer += decoder.write(data)
        })//when the request emit the event called 'data' (so, ON the event 
        //called data)
        req.on('end',()=>{//called regardless if it has a payload or not
        buffer += decoder.end()
        //choose the handler this request should go to. If one is not found use
        //not found handler
        const chosenHandler = typeof(router[trimedPath]) !== 'undefined' ? 
        router[trimedPath] : handlers.notFound
        //contruct the data Object to send to the handler:
        const data = {
        'trimedPath':trimedPath,
        'queryStringObject':queryStringObject,
        'method':method,
        'headers':headers,
        'payload':buffer
        }
    
        //route the request to the handler specified in the router
    
        chosenHandler(data,(statusCode,payload)=>{
        console.log(statusCode,payload)//es la data que esta en la 
        //funcion sample del objeto handler
        //use the status code CALLED BACK by the handler or default
        //to 200
        statusCode = typeof(statusCode) == 'number' ? statusCode:200
        //use the payload called back by the handler or default to and
        //empty object
        payload = typeof(payload)=='object' ? payload:{}
    
        //convert the payload to a string
        const palyloadString = JSON.stringify(payload)
    
        //return the response
        res.setHeader('content-Type','application/json')//telling ...
        //that we are going to return an object:
        //content-Type is the key ; application/json is the value
        res.writeHead(statusCode)//usin the buil in function that comes on every
        //response object received by the http server to write the status code
    
        //now that the request has finished
        //Send the response
        res.end(palyloadString)
        //Log the request path
        console.log(`Returning this response` , statusCode , palyloadString)
        })
        })
        //console.log(`Request received with these headers: ` , headers )
        //console.log(`Request received on path: ${trimedPath} with method ${method}
        //and with this query string parameters `, queryStringObject)
        }
    
        //define the handlers
        const handlers = {}
        //sample handler
        handlers.sample = (data,callback)=>{
        //callback a http status code and a payload object
        callback(406,{'name':'sample handler'})
        }
    
        //Not found handler
        handlers.notFound = (data,callback)=>{
        callback(404)//does not need a payload
        }
    
        //define a request router
        const router = {
        'sample':handlers.sample
        }
    

    希望对此有所帮助。

    祝你好运。

    【讨论】:

      猜你喜欢
      • 2012-04-05
      • 2018-10-07
      • 1970-01-01
      • 2016-09-15
      • 2011-11-16
      • 2021-07-18
      • 1970-01-01
      • 2011-08-21
      • 2011-07-19
      相关资源
      最近更新 更多