天天看點

esp8266與mosquitto的mqtt的ssl通訊實作(二)-證書生成

好久沒更新了,有網友催着後續部落格,最近比較忙,先把記得的部分,和一些代碼貼出來,供大家參考,若有問題請大家留言,

後面自己再重新弄一遍,再修改整理。

esp8266上證書以*.h格式編譯寫到flash中,而伺服器端格式為*.crt格式,

采用腳本一次生成,代碼如下,

makefile.sh

#

# Generate the certificates and keys for testing.

#

PROJECT_NAME="TLS Project"

# Generate the openssl configuration files.

cat > ca_cert.conf << EOF  

[ req ]

distinguished_name     = req_distinguished_name

prompt                 = no

[ req_distinguished_name ]

 O                      = $PROJECT_NAME Dodgy Certificate Authority

EOF

cat > certs.conf << EOF  

[ req ]

distinguished_name     = req_distinguished_name

prompt                 = no

[ req_distinguished_name ]

 O                      = $PROJECT_NAME

 CN                     = www.***.com

EOF

cat > device_cert.conf << EOF  

[ req ]

distinguished_name     = req_distinguished_name

prompt                 = no

[ req_distinguished_name ]

 O                      = $PROJECT_NAME Device Certificate

EOF

# private key generation

openssl genrsa -out TLS.ca_key.pem 1024

openssl genrsa -out TLS.key_1024.pem 1024

openssl genrsa -out TLS.key_DEVICE.pem 1024

# convert private keys into DER format

openssl rsa -in TLS.key_1024.pem -out TLS.key_1024 -outform DER

openssl rsa -in TLS.key_DEVICE.pem -out TLS.key_DEVICE -outform DER

# cert requests

openssl req -out TLS.ca_x509.req -key TLS.ca_key.pem -new \

            -config ./ca_cert.conf

openssl req -out TLS.x509_1024.req -key TLS.key_1024.pem -new \

            -config ./certs.conf 

openssl req -out TLS.x509_DEVICE.req -key TLS.key_DEVICE.pem -new \

            -config ./device_cert.conf 

# generate the actual certs.

openssl x509 -req -in TLS.ca_x509.req -out TLS.ca_x509.pem \

            -sha1 -days 5000 -signkey TLS.ca_key.pem

openssl x509 -req -in TLS.x509_1024.req -out TLS.x509_1024.pem \

            -sha1 -CAcreateserial -days 5000 \

            -CA TLS.ca_x509.pem -CAkey TLS.ca_key.pem

openssl x509 -req -in TLS.x509_DEVICE.req -out TLS.x509_DEVICE.pem \

            -sha1 -CAcreateserial -days 5000 \

            -CA TLS.ca_x509.pem -CAkey TLS.ca_key.pem

# some cleanup

rm TLS*.req

rm *.conf

openssl x509 -in TLS.ca_x509.pem -outform DER -out TLS.ca_x509.cer

openssl x509 -in TLS.x509_1024.pem -outform DER -out TLS.x509_1024.cer

openssl x509 -in TLS.x509_DEVICE.pem -outform DER -out TLS.x509_DEVICE.cer

# Generate the certificates and keys for encrypt.

#

# set default cert for use in the client

xxd -i  TLS.x509_1024.cer | sed -e \

        "s/TLS_x509_DEVICE_cer/default_certificate/" > cert.h

# set default key for use in the DEVICE

xxd -i TLS.key_1024 | sed -e \

        "s/TLS_key_DEVICE/default_private_key/" > private_key.h

以上是我修改測試後的腳本makefile.sh内容,在linux下生成證書。

一些細節參照下面部落格:

http://blog.csdn.net/houjixin/article/details/24305613