Linux 7 下openssl 生成服务器证书

1.检查OPENSSL 版本

[root@xag129 src]# pwd
/usr/local/src
[root@xag129 src]# openssl version -a
OpenSSL 1.0.2k-fips  26 Jan 2017
built on: reproducible build, date unspecified
platform: linux-x86_64
options:  bn(64,64) md2(int) rc4(16x,int) des(idx,cisc,16,int) idea(int) blowfish(idx) 
...
OPENSSLDIR: "/etc/pki/tls"

1.0.1以上的版本支持 TLS1.2
1.1.1以上的版本支持 TLS1.3

2.查看openssl的配置文件openssl.cnf的存放位置(即openssl的安装位置

[root@xag129 src]# openssl version -a
OpenSSL 1.0.2k-fips  26 Jan 2017
...
OPENSSLDIR: "/etc/pki/tls"

3.查看openssl的配置文件openssl.cnf

[root@xag129 src]# vim /etc/pki/tls/openssl.cnf

4.创建为根证书CA所需的目录及文件

#根据配置文件信息,到CA根目录,若没有则自己创建
cd /etc/pki/CA

#创建配置文件信息中所需的目录及文件
mkdir -pv {certs,crl,newcerts,private}
touch {serial,index.txt}
  1. 指明证书的开始编号
[root@xag129 CA]# echo 01 >> serial

[root@xag129 CA]# cat serial 
01

6.生成根证书的私钥(注意:私钥的文件名与存放位置要与配置文件中的设置相匹配)--對外使用

[root@xag129 CA]# 
openssl genrsa -aes256 -out /etc/pki/CA/private/cakey.pem 2048

Enter pass phrase for /etc/pki/CA/private/cakey.pem:
输入:ca123456

7.生成自签证书,即根证书CA,自签证书的存放位置也要与配置文件中的设置相匹配,生成证书时需要填写相应的信息

[root@xag129 CA]# openssl req -new -x509 -key /etc/pki/CA/private/cakey.pem -out cacert.pem -days 3650
Enter pass phrase for /etc/pki/CA/private/cakey.pem:
输入:ca123456

Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:GuangDong
Locality Name (eg, city) [Default City]:zhuhai
Organization Name (eg, company) [Default Company Ltd]:XagCompany
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname) []:xagca    
Email Address []:xuaiguo@163.com

or (推建)
openssl req -new -x509 -key /etc/pki/CA/private/cakey.pem -out cacert.pem -days 3650 -subj "/C=CN/ST=GuangDong/L=zhuhai/O=XagCompany/OU=IT/CN=xagca/emailAddress=xuaiguo@163.com"

[root@xag129 CA]# ls ca*
  cacert.pem

-----------以上已完成根证书的处理--------------
-----------开始后续其他需求证书的颁发---------
8.颁发WEB服务器证书
8.1 在需要证书的服务器上,生成证书签署请求
--生成私钥,该私钥的位置可随意定

[root@xag129 server_cer]# pwd
/usr/local/src/server_cer

[root@xag129 server_cer]# openssl genrsa -out web129.key 2048

[root@xag129 server_cer]# ls
web129.key

8.2 生成证书签署请求

[root@xag129 server_cer]# openssl req -new -key web129.key -out web129.csr -days 3650

-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:GuangDong
Locality Name (eg, city) [Default City]:zhuhai
Organization Name (eg, company) [Default Company Ltd]:XagCompany
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname) []:192.168.40.129
Email Address []:xuaiguo@163.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:回车
An optional company name []:回车

8.3 在根证书服务器上,颁发证书

[root@xag129 server_cer]# mkdir /etc/pki/CA/req
[root@xag129 server_cer]# cp web129.csr /etc/pki/CA/req/
[root@xag129 server_cer]# ls /etc/pki/CA/req/
web129.csr

#颁发证书
[root@xag129 CA]# 
openssl ca -in /etc/pki/CA/req/web129.csr -out /etc/pki/CA/certs/web129.crt -days 3650

Using configuration from /etc/pki/tls/openssl.cnf
Enter pass phrase for /etc/pki/CA/private/cakey.pem:输入ca123456
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Jun 29 09:17:54 2021 GMT
            Not After : Jun 27 09:17:54 2031 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = GuangDong
            organizationName          = XagCompany
            organizationalUnitName    = IT
            commonName                = web129
            emailAddress              = xuaiguo@163.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                BF:DA:C2:43:FF:3C:AE:BA:D4:31:30:C7:00:90:FD:EF:44:A3:47:33
            X509v3 Authority Key Identifier: 
                keyid:E4:CD:7B:5E:FC:1C:3C:11:02:9D:38:66:ED:58:33:E1:52:12:09:20

Certificate is to be certified until Jun 27 09:17:54 2031 GMT (3650 days)
Sign the certificate? [y/n]:y

1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated


#查看证书信息
[root@xag129 CA]# 
openssl x509 -in /etc/pki/CA/certs/web129.crt -noout -serial -subject
-------------------------
serial=01
subject= /C=CN/ST=GuangDong/O=XagCompany/OU=IT/CN=web129/emailAddress=xuaiguo@163.com
-------------------------
[root@xag129 CA]# ls /etc/pki/CA/certs/
  web129.crt

8.123(取代8.1 到 8.3)

mkdir /etc/pki/CA/req
mkdir /etc/pki/CA/webprivate

#生成請求文件
[root@xag221 CA]# 
openssl req -out /etc/pki/CA/req/web129.csr -new -sha256 -newkey rsa:2048 -nodes -keyout /etc/pki/CA/webprivate/web129.key -subj "/C=CN/ST=GuangDong/L=zhuhai/O=XagCompany/OU=IT/CN=192.168.40.129/emailAddress=xuaiguo@163.com"

#颁 发自 签 域名 129 证书, 面向 用户 端 的 域名 证书
openssl x509 -req -in /etc/pki/CA/req/web129.csr -out /etc/pki/CA/certs/web129.crt -CA /etc/pki/CA/cacert.pem -CAkey /etc/pki/CA/private/cakey.pem -CAcreateserial -days 3650

8.4 格式转换为pfx格式的私钥

[root@xag129 CA]# 
openssl pkcs12 -export -out /etc/pki/CA/certs/web129.pfx -inkey /usr/local/src/server_cer/web129.key -in /etc/pki/CA/certs/web129.crt

Enter Export Password:123456

[root@xag129 CA]# ls /etc/pki/CA/certs/
web129.crt  web129.pfx

8.5 格式转换为cer格式的公钥

[root@xag129 certs]# pwd
/etc/pki/CA/certs

#格式转换为cer格式的公钥
[root@xag129 certs]# openssl x509 -inform pem -in web129.crt -outform der -out web129.cer

[root@xag129 certs]# ls
web129.cer  web129.crt  web129.pfx

[root@xag129 certs]# openssl x509 -in web129.cer -text -noout
unable to load certificate
139740962715536:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:707:Expecting: TRUSTED CERTIFICATE

#若上面报unable to load certificate 错误,则说明你打开的证书编码是der格式,需要用以下命令
[root@xag129 certs]# openssl x509 -in web129.cer -inform der -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 1 (0x1)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=CN, ST=GuangDong, L=zhuhai, O=XagCompany, OU=IT, CN=xagca/emailAddress=xuaiguo@163.com
        Validity
            Not Before: Jun 29 09:17:54 2021 GMT
            Not After : Jun 27 09:17:54 2031 GMT
        Subject: C=CN, ST=GuangDong, O=XagCompany, OU=IT, CN=web129/emailAddress=xuaiguo@163.com
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:

                    00:c3:2a:01: ......... :f5:1b:96:09

                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                BF:DA:C2:43:FF:3C:AE:BA:D4:31:30:C7:00:90:FD:EF:44:A3:47:33
            X509v3 Authority Key Identifier: 
                keyid:E4:CD:7B:5E:FC:1C:3C:11:02:9D:38:66:ED:58:33:E1:52:12:09:20

    Signature Algorithm: sha256WithRSAEncryption

         45:40:e3:98:1a:............:48:ee

9.1 测试 java 读取 web129.pfx

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.util.Enumeration;
 
public class ReadPFX {
 
    public static void main(String[] args) throws Exception {
        String strPfx = "C:\\Users\\新建文件夹\\web129.pfx";
        String strPassword = "123456";
        KeyStore ks = KeyStore.getInstance("PKCS12");
        
        FileInputStream fis = new FileInputStream(strPfx);
        // If the keystore password is empty(""), then we have to set
        // to null, otherwise it won't work!!!
        char[] nPassword = null;
        if ((strPassword == null) || strPassword.trim().equals("")) {
            nPassword = null;
        } else {
            nPassword = strPassword.toCharArray();
        }
        ks.load(fis, nPassword);
        fis.close();
        
        System.out.println("keystore type=" + ks.getType());
        // Now we loop all the aliases, we need the alias to get keys.
        // It seems that this value is the "Friendly name" field in the
        // detals tab <-- Certificate window <-- view <-- Certificate
        // Button <-- Content tab <-- Internet Options <-- Tools menu
        // In MS IE 6.
        Enumeration enumas = ks.aliases();
        String keyAlias = null;
        if (enumas.hasMoreElements())// we are readin just one certificate.
        {
            keyAlias = (String) enumas.nextElement();
            System.out.println("alias=[" + keyAlias + "]");
        }
        
        // Now once we know the alias, we could get the keys.
        System.out.println();
        System.out.println("is key entry=" + ks.isKeyEntry(keyAlias));
        PrivateKey prikey = (PrivateKey) ks.getKey(keyAlias, nPassword);
        Certificate cert = ks.getCertificate(keyAlias);
        PublicKey pubkey = cert.getPublicKey();
        System.out.println("cert class = " + cert.getClass().getName());
        System.out.println("cert = " + cert);
        System.out.println("public key = " + pubkey);
        System.out.println("private key = " + prikey);
    }
 
}

9.2 读取web129.cer文件

import java.io.FileInputStream;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
 
public class ReadCER {
 
    public static void main(String[] args) {
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            FileInputStream fileInputStream = new FileInputStream("C:\\Users\\admin\\Desktop\\新建文件夹\\test.cer");
            X509Certificate cer = (X509Certificate)certificateFactory.generateCertificate(fileInputStream);
            fileInputStream.close();
            
            System.out.println("读取Cer证书信息...");
            System.out.println("cer_序列号___:"+cer.getSerialNumber());
            System.out.println("cer_发布方标识名___:"+cer.getIssuerDN().getName()); 
            System.out.println("cer_主体标识___:"+cer.getSubjectDN());
            System.out.println("cer_证书算法OID字符串___:"+cer.getSigAlgOID());
            System.out.println("cer_证书有效期___:" + cer.getNotBefore() + "~" + cer.getNotAfter());
            System.out.println("cer_签名算法___:"+cer.getSigAlgName());
            System.out.println("cer_版本号___:"+cer.getVersion());
            System.out.println("cer_公钥___:"+cer.getPublicKey());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,185评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,445评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,684评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,564评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,681评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,874评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,025评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,761评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,217评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,545评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,694评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,351评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,988评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,778评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,007评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,427评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,580评论 2 349

推荐阅读更多精彩内容