如何在Node.js中使用openssl生成公钥/私钥对?

时间:2019-01-10 19:17:59

标签: node.js openssl digital-signature

我是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中读取公钥?

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码: 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
    }

希望对此有所帮助。

祝你好运。