openssl采用sm2进行自签名的方法

自签名有两种方法:

1 用自己会话生成的私钥,来签发自己的csr生成证书,也可以直接生成私钥和证书

2 自己做一个CA.

1,2的差别在于私钥的生成和存活的时间.

以1的方法如下:

生成私钥

./openssl ecparam -genkey -name SM2 -out priv.key

生成证书

./openssl req -new -x509 -sha256 -key priv.key -out cer.crt -days 10000 -subj '/C=CN/ST=Beijing/L=Haidian/O=Datang/OU=SDT/CN=Shixun/[email protected]'

这里ecdsa with sha256可能需要换成sm3,不过在RFC 5349中规定为ecdsa SHA做digest,所以需要做二次开发,这次暂时用这个.

此时的cer.crt作为自签名的证书已经生成了,证书中包括公钥和基本的信息,公钥可以由私钥生成,所以用私钥输入.

查看证书的方法:

./openssl x509 -in cer.crt -noout -text

可见如下输出

Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            71:d4:be:b6:9e:6a:3b:52:7e:f4:3c:73:27:44:d8:71:df:02:d3:2e
        Signature Algorithm: ecdsa-with-SHA256
        Issuer: C = CN, ST = Beijing, L = Haidian, O = Datang, OU = SDT, CN = Shixun, emailAddress = [email protected]
        Validity
            Not Before: Aug  4 16:22:50 2018 GMT
            Not After : Dec 20 16:22:50 2045 GMT
        Subject: C = CN, ST = Beijing, L = Haidian, O = Datang, OU = SDT, CN = Shixun, emailAddress = [email protected]
        Subject Public Key Info:
            Public Key Algorithm: id-ecPublicKey
                Public-Key: (256 bit)
                pub:
                    04:e8:4a:d6:a6:55:e0:c6:60:65:9e:60:bd:12:b8:
                    0e:90:bd:ae:76:f7:d7:f2:05:d2:bb:f8:e8:76:6d:
                    1f:79:64:18:3d:c9:4d:db:07:fd:8b:99:dc:6f:6f:
                    32:39:53:c5:f7:7c:8d:bb:94:1c:f2:a4:fc:f9:0c:
                    9f:0f:e2:c3:13
                ASN1 OID: SM2
        X509v3 extensions:
            X509v3 Subject Key Identifier: 
                33:22:BA:1B:9E:57:F2:06:61:66:99:A5:EC:FF:F7:44:19:CD:B8:2D
            X509v3 Authority Key Identifier: 
                keyid:33:22:BA:1B:9E:57:F2:06:61:66:99:A5:EC:FF:F7:44:19:CD:B8:2D

            X509v3 Basic Constraints: critical
                CA:TRUE
    Signature Algorithm: ecdsa-with-SHA256
         30:44:02:20:07:14:07:18:54:4f:50:78:0c:05:64:75:25:60:
         f3:db:c5:9d:04:22:3f:ef:83:74:46:d7:41:ee:3f:db:06:f6:
         02:20:67:ca:21:0e:69:05:9a:b6:67:b3:63:74:27:93:5b:26:
         8e:4c:67:65:b1:eb:8b:16:18:1a:90:39:1b:4a:88:84

看看公钥是否是与私钥相一致

./openssl ec -in priv.key -pubout -noout -text

如下输出:

Private-Key: (256 bit)
priv:
    3e:6e:45:f5:ab:3e:2f:80:9b:ec:93:2e:aa:9c:78:
    38:2f:72:19:96:c5:44:06:c1:6b:66:75:41:0e:5d:
    a4:0f
pub:
    04:e8:4a:d6:a6:55:e0:c6:60:65:9e:60:bd:12:b8:
    0e:90:bd:ae:76:f7:d7:f2:05:d2:bb:f8:e8:76:6d:
    1f:79:64:18:3d:c9:4d:db:07:fd:8b:99:dc:6f:6f:
    32:39:53:c5:f7:7c:8d:bb:94:1c:f2:a4:fc:f9:0c:
    9f:0f:e2:c3:13
ASN1 OID: SM2

可见证书中的pub与priv.key是一致的,这样输出的cer.crt中,包含了会话的公钥,用于分发加密.而最后的ecdsa SHA256的数字签名,用于通过上面的公钥来验证证书的完整性,但不能验证证书的来源.

如果自己做CA的话,多了一步CA秘钥的生成+生成签名请求req+证书签发x509的过程.

你可能感兴趣的:(c++)