我正在为嵌入式Linux设备添加HTTPS支持。我已尝试使用以下步骤生成自签名证书:

openssl req -new > cert.csr
openssl rsa -in privkey.pem -out key.pem
openssl x509 -in cert.csr -out cert.pem -req -signkey key.pem -days 1001
cat key.pem>>cert.pem

这是可行的,但我在Google Chrome上遇到了一些错误:

这可能不是你要找的网站!站点的安全证书不受信任!

我错过了什么吗?这是构建自签名证书的正确方法吗?


当前回答

在经历了大量的尝试和各种解决方案之后,我仍然面临这样一个问题:为localhost颁发自签名证书会给我带来错误

错误证书无效

在扩展细节时,chrome表示:

您现在无法访问localhost,因为网站已发送加密凭据。。。

唯一难看的方式是键入(直接在这个屏幕上,没有看到文本的任何光标):

(在键盘上键入)这是安全的

这让我继续。

直到我找到extendedKeyUsage=serverAuth,clientAuth

TL;博士

openssl genrsa-out localhost.key 2048openssl req-key localhost.key-new-out localhost.csr(单击输入所有内容,然后用localhost或其他FQDN填写通用名称(CN)。将以下内容放入名为v3.ext的文件中(根据需要进行编辑):

subjectKeyIdentifier   = hash
authorityKeyIdentifier = keyid:always,issuer:always
basicConstraints       = CA:TRUE
keyUsage               = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyAgreement, keyCertSign
extendedKeyUsage       = serverAuth, clientAuth
subjectAltName         = DNS:localhost, DNS:localhost.localdomain
issuerAltName          = issuer:copy

openssl x509-req-in localhost.csr-signkey localhost.key-out localhost.pem-days 3650-sha256-extfile v3.ext

瞧!您可以访问网站,展开“高级”,然后单击“转到本地主机(不安全)”。

其他回答

从2023年起,OpenSSL≥1.1.1,以下命令可满足您的所有需求,包括主题备用名称(SAN):

openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes \
  -keyout example.key -out example.crt -subj "/CN=example.com" \
  -addext "subjectAltName=DNS:example.com,DNS:www.example.net,IP:10.0.0.1"

在OpenSSL≤1.1.0的旧系统上,如Debian≤9或CentOS≤7,需要使用此命令的更长版本:

openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes \
  -keyout example.key -out example.crt -extensions san -config \
  <(echo "[req]"; 
    echo distinguished_name=req; 
    echo "[san]"; 
    echo subjectAltName=DNS:example.com,DNS:www.example.net,IP:10.0.0.1
    ) \
  -subj "/CN=example.com"

任一命令都创建一个证书

对于(子)域example.com和www.example.net(SAN)有效,对于IP地址10.0.0.1(SAN)也是有效的,相对强劲(截至2023年)有效期为3650天(约10年)。

将生成以下文件:

私钥:example.key证书:example.crt

所有信息都在命令行中提供。没有让你烦恼的互动输入。没有你必须处理的配置文件。所有必要的步骤都由单个OpenSSL调用执行:从私钥生成到自签名证书。


备注#1:加密参数

由于证书是自签名的,需要用户手动接受,因此使用短到期或弱加密是没有意义的。

未来,您可能希望使用超过4096位的RSA密钥和比sha256更强的哈希算法,但截至2023年,这些都是正常的值。它们足够强大,同时受到所有现代浏览器的支持。

备注#2:参数“-nodes”

理论上,您可以省略-nodes参数(这意味着“没有DES加密”),在这种情况下,example.key将使用密码进行加密。然而,这对于服务器安装几乎从来都没有用处,因为您要么必须将密码也存储在服务器上,要么必须在每次重新启动时手动输入密码。

备注#3:另请参见

直接在命令行上向openssl提供subjectAltName如何通过命令行向SSL证书添加多个电子邮件地址?有关MSYS_NO_PATHCONV的更多信息

您可以在一个命令中完成此操作:

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -sha256 -days 365

如果您不想用密码保护您的私钥,也可以添加-node(“no DES”的缩写)。否则,它将提示您输入“至少4个字符”的密码。

天数参数(365)可以替换为任何数字以影响到期日期。然后它会提示您输入“国家名称”之类的信息,但您只需按Enter键并接受默认值即可。

添加-sbj'/CN=localhost'以抑制有关证书内容的问题(用所需域替换localhost)。

自签名证书不会通过任何第三方进行验证,除非您以前将其导入浏览器。如果需要更多的安全性,则应使用由证书颁发机构(CA)签名的证书。

在经历了大量的尝试和各种解决方案之后,我仍然面临这样一个问题:为localhost颁发自签名证书会给我带来错误

错误证书无效

在扩展细节时,chrome表示:

您现在无法访问localhost,因为网站已发送加密凭据。。。

唯一难看的方式是键入(直接在这个屏幕上,没有看到文本的任何光标):

(在键盘上键入)这是安全的

这让我继续。

直到我找到extendedKeyUsage=serverAuth,clientAuth

TL;博士

openssl genrsa-out localhost.key 2048openssl req-key localhost.key-new-out localhost.csr(单击输入所有内容,然后用localhost或其他FQDN填写通用名称(CN)。将以下内容放入名为v3.ext的文件中(根据需要进行编辑):

subjectKeyIdentifier   = hash
authorityKeyIdentifier = keyid:always,issuer:always
basicConstraints       = CA:TRUE
keyUsage               = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyAgreement, keyCertSign
extendedKeyUsage       = serverAuth, clientAuth
subjectAltName         = DNS:localhost, DNS:localhost.localdomain
issuerAltName          = issuer:copy

openssl x509-req-in localhost.csr-signkey localhost.key-out localhost.pem-days 3650-sha256-extfile v3.ext

瞧!您可以访问网站,展开“高级”,然后单击“转到本地主机(不安全)”。

这对我有用

openssl req -x509 -nodes -subj '/CN=localhost'  -newkey rsa:4096 -keyout ./sslcert/key.pem -out ./sslcert/cert.pem -days 365

服务器.js

var fs = require('fs');
var path = require('path');
var http = require('http');
var https = require('https');
var compression = require('compression');
var express = require('express');
var app = express();

app.use(compression());
app.use(express.static(__dirname + '/www'));    

app.get('/*', function(req,res) {
  res.sendFile(path.join(__dirname+'/www/index.html'));
});

// your express configuration here

var httpServer = http.createServer(app);
var credentials = {
    key: fs.readFileSync('./sslcert/key.pem', 'utf8'),
    cert: fs.readFileSync('./sslcert/cert.pem', 'utf8')
};
var httpsServer = https.createServer(credentials, app);

httpServer.listen(8080);
httpsServer.listen(8443);

console.log(`RUNNING ON  http://127.0.0.1:8080`);
console.log(`RUNNING ON  http://127.0.0.1:8443`);

这个非常简单的Python应用程序创建了一个自签名证书。代码:

from OpenSSL import crypto, SSL
from secrets import randbelow
print("Please know, if you make a mistake, you must restart the program.")
def cert_gen(
    emailAddress=input("Enter Email Address: "),
    commonName=input("Enter Common Name: "),
    countryName=input("Enter Country Name (2 characters): "),
    localityName=input("Enter Locality Name: "),
    stateOrProvinceName=input("Enter State of Province Name: "),
    organizationName=input("Enter Organization Name: "),
    organizationUnitName=input("Enter Organization Unit Name: "),
    serialNumber=randbelow(1000000),
    validityStartInSeconds=0,
    validityEndInSeconds=10*365*24*60*60,
    KEY_FILE = "private.key",
    CERT_FILE="selfsigned.crt"):
    #can look at generated file using openssl:
    #openssl x509 -inform pem -in selfsigned.crt -noout -text
    # create a key pair
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 4096)
    # create a self-signed cert
    cert = crypto.X509()
    cert.get_subject().C = countryName
    cert.get_subject().ST = stateOrProvinceName
    cert.get_subject().L = localityName
    cert.get_subject().O = organizationName
    cert.get_subject().OU = organizationUnitName
    cert.get_subject().CN = commonName
    cert.get_subject().emailAddress = emailAddress
    cert.set_serial_number(serialNumber)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(validityEndInSeconds)
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(k)
    cert.sign(k, 'sha512')
    with open(CERT_FILE, "wt") as f:
        f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode("utf-8"))
    with open(KEY_FILE, "wt") as f:
        f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k).decode("utf-8"))
    print("GENERATED")
    input("Press enter to close program.")
cert_gen()

但是,您仍然会收到“证书不受信任”错误。这是因为以下几个原因:

它是自签名/未验证的(验证的证书需要CA(证书颁发机构),如Let's Encrypt,以便在所有设备上都受信任)。您的计算机上不信任它。(此答案显示了如何使Windows信任您的证书)。