使用openssl 工具生成 rsa及ecdsa证书链,公钥,私钥,签名,验证,root CA,证书链,中间证书验证

#!/bin/sh

USE_RSA=0
SIGNATURE_HASH=0
ECDSA_CURVE=secp384r1
DIGEST_ALGORITHM=sha384

if [ "$1" == "rsa" ];then
    USE_RSA=1
    DIGEST_ALGORITHM=sha256
elif [ "$1" == "256" ];then
    ECDSA_CURVE=prime256v1
    DIGEST_ALGORITHM=sha256
elif [ "$1" == "384" ];then
    ECDSA_CURVE=secp384r1
    DIGEST_ALGORITHM=sha384
elif [ "$1" == "512" ];then
    ECDSA_CURVE=secp521r1
    DIGEST_ALGORITHM=sha512
fi

if [ $USE_RSA == 1 ];then
    echo "Generate RSA certificate"
	echo ""
else
    echo "Generate ECDSA certificate"
	echo "Curve: $ECDSA_CURVE"
	echo "Digest: $DIGEST_ALGORITHM"
fi

CONFIG_FILE=opensslroot.cfg

function prepare()
{
echo "authorityKeyIdentifier=keyid,issuer
subjectKeyIdentifier=hash
basicConstraints = CA:true,pathlen:0
keyUsage = cRLSign, keyCertSign" > v3.ext

echo "authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:false,pathlen:0
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment" > v3_attest.ext
}

prepare

#--------------------------------------------------------------------------------------------------------------
# Generate rootCA key
#
if [ ${USE_RSA} == 1 ];then
    openssl genrsa -out qpsa_rootca.key 2048
else
    openssl ecparam -out qpsa_rootca.key -name ${ECDSA_CURVE} -genkey
fi

# use below command to query the supported parameter for ecdsa,
# usally use: prime256v1(NIST P-256),secp384r1(NIST P-384),secp521r1(NIST P-521)
# openssl ecparam -list_curves

#Generate certificate for rootCA
openssl req -new -key qpsa_rootca.key -x509 -out qpsa_rootca.crt \
-subj "/C=US/ST=California/L=San Diego/OU=General Use Test Key (for testing only)/OU=CDMA Technologies/O=None/CN=Generated Root CA 1" \
-days 7300 -set_serial 1 -config ${CONFIG_FILE} -${DIGEST_ALGORITHM}

#Convert crt format to der
openssl x509 -inform PEM -in qpsa_rootca.crt -outform DER -out qpsa_rootca.der

#--------------------------------------------------------------------------------------------------------------
#Generate attestCA key
if [ ${USE_RSA} == 1 ];then
    openssl genrsa -out qpsa_attestca.key 2048
else
    openssl ecparam -out qpsa_attestca.key -name ${ECDSA_CURVE} -genkey
fi

#Generate csr for attestCA
openssl req -new -key qpsa_attestca.key -out qpsa_attestca.csr \
-subj "/C=US/ST=CA/L=San Diego/OU=CDMA Technologies/O=None/CN=Generated Attestation CA" \
 -config ${CONFIG_FILE}

#Generate certificate for attestCA and signed by rootCA
openssl x509 -req -in qpsa_attestca.csr -CA qpsa_rootca.crt -CAkey qpsa_rootca.key -out qpsa_attestca.crt -set_serial 5 -days 7300 -extfile v3.ext -${DIGEST_ALGORITHM}

#Convert crt format to der
openssl x509 -inform PEM -in qpsa_attestca.crt -outform DER -out qpsa_attestca.der

#--------------------------------------------------------------------------------------------------------------
#//Generate attest key
if [ ${USE_RSA} == 1 ];then
    openssl genrsa -out qpsa_attest.key 2048
else
    openssl ecparam -out qpsa_attest.key -name ${ECDSA_CURVE} -genkey
fi

#Generate csr for attest
openssl req -new -key qpsa_attest.key -out qpsa_attest.csr \
  -subj  "/C=US/CN=QPSA User/L=San Diego/O=ASIC/ST=California/OU=Test key only" \
  -config ${CONFIG_FILE}

#Generate certificate for attest and signed by attestCA
#openssl x509 -req -in qpsa_attest.csr -CA qpsa_attestca.crt -CAkey qpsa_attestca.key -out qpsa_attest.crt -days 7300 -set_serial 38758 -extfile v3_attest.ext -${DIGEST_ALGORITHM}
openssl x509 -req -in qpsa_attest.csr -CA qpsa_attestca.crt -CAkey qpsa_attestca.key -outform DER -out qpsa_attest.der -days 7300 -set_serial 38758 -extfile v3_attest.ext -${DIGEST_ALGORITHM}
#Convert crt format to der
#openssl x509 -inform PEM -in qpsa_attest.crt -outform DER -out qpsa_attest.der
#--------------------------------------------------------------------------------------------------------------

#Get public key from crt
openssl x509 -in qpsa_rootca.crt -pubkey -noout > qpsa_rootca_pubkey.key
openssl x509 -in qpsa_attestca.crt -pubkey -noout > qpsa_attestca_pubkey.key
#openssl x509 -in qpsa_attest.crt -pubkey -noout > qpsa_attest_pubkey.key

#Get the public key from private key -modulus
if [ ${USE_RSA} == 1 ];then
#   openssl rsa -in qpsa_attest.key -noout -modulus  > qpsa_attest_pubkey_from_pri.key
    openssl rsa -in qpsa_attest.key -pubout > qpsa_attest_pubkey_from_pri.key
    openssl rsa -in qpsa_attest.key -pubout -outform DER > qpsa_attest_pubkey_from_pri.der
else
    openssl pkey -in qpsa_attest.key -pubout > qpsa_attest_pubkey_from_pri.key
    openssl pkey -in qpsa_attest.key -pubout -outform DER > qpsa_attest_pubkey_from_pri.der
fi

echo "verify the certificate train: qpsa_rootca.crt -> qpsa_attestca.crt -> qpsa_attest.crt"
echo ""
openssl verify -CAfile qpsa_rootca.crt qpsa_attestca.crt
#openssl verify -CAfile qpsa_attestca.crt qpsa_attest.der
#openssl verify -CAfile qpsa_rootca.crt -untrusted qpsa_attestca.crt qpsa_attest.crt

echo "signature data.txt"
echo "adkjdkfjskjfksjtestdata, this is the test data" > data.txt
if [ ${SIGNATURE_HASH} == 1 ];then
    openssl dgst -${DIGEST_ALGORITHM} -binary -out data.${DIGEST_ALGORITHM} data.txt
    if [ ${USE_RSA} == 1 ];then
#now not support, need padding
        openssl rsautl -sign -inkey  qpsa_attest.key -raw  -in data.${DIGEST_ALGORITHM} -out data.sig
    else
        openssl pkeyutl -sign -inkey qpsa_attest.key -in data.${DIGEST_ALGORITHM} -out data.sig
    fi
else
    openssl dgst -${DIGEST_ALGORITHM} -sign qpsa_attest.key -out data.sig data.txt
fi

echo "verify the signature of data.txt"
openssl dgst -${DIGEST_ALGORITHM} -verify qpsa_attest_pubkey_from_pri.key -signature data.sig data.txt

其中USE_RSA=1 为使用RSA算法,0为使用ECDSA算法, 以下为配置文件opensslroot.cfg内容:

HOME            = .
RANDFILE        = $ENV::HOME/.rnd

oid_section     = new_oids

[ new_oids ]

####################################################################
[ ca ]
default_ca  = CA_default        # The default ca section

####################################################################
[ CA_default ]

dir     = ./demoCA      # Where everything is kept
certs       = $dir/certs        # Where the issued certs are kept
crl_dir     = $dir/crl      # Where the issued crl are kept
database    = $dir/index.txt    # database index file.

new_certs_dir   = $dir/newcerts     # default place for new certs.

certificate = $dir/cacert.pem   # The CA certificate
serial      = $dir/serial       # The current serial number
crlnumber   = $dir/crlnumber    # the current crl number
                    # must be commented out to leave a V1 CRL
crl     = $dir/crl.pem      # The current CRL
private_key = $dir/private/cakey.pem# The private key
RANDFILE    = $dir/private/.rand    # private random number file

x509_extensions = usr_cert      # The extentions to add to the cert

name_opt    = ca_default        # Subject Name options
cert_opt    = ca_default        # Certificate field options

default_days    = 365           # how long to certify for
default_crl_days= 30            # how long before next CRL
default_md  = sha1          # which md to use.
preserve    = no            # keep passed DN ordering

policy      = policy_match

# For the CA policy
[ policy_match ]
countryName     = match
stateOrProvinceName = match
organizationName    = match
organizationalUnitName  = optional
commonName      = supplied
emailAddress        = optional

# For the 'anything' policy
# At this point in time, you must list all acceptable 'object'
# types.
[ policy_anything ]
countryName     = optional
stateOrProvinceName = optional
localityName        = optional
organizationName    = optional
organizationalUnitName  = optional
commonName      = supplied
emailAddress        = optional

####################################################################
[ req ]
default_bits        = 1024
default_keyfile     = privkey.pem
distinguished_name  = req_distinguished_name
attributes      = req_attributes
x509_extensions = v3_ca # The extentions to add to the self signed cert

string_mask = nombstr

req_extensions = v3_req # The extensions to add to a certificate request

[ req_distinguished_name ]
countryName         = Country Name (2 letter code)
countryName_default     = AU
countryName_min         = 2
countryName_max         = 2

stateOrProvinceName     = State or Province Name (full name)
stateOrProvinceName_default = Some-State

localityName            = Locality Name (eg, city)

0.organizationName      = Organization Name (eg, company)
0.organizationName_default  = Internet Widgits Pty Ltd

organizationalUnitName      = Organizational Unit Name (eg, section)

commonName          = Common Name (eg, YOUR name)
commonName_max          = 64

emailAddress            = Email Address
emailAddress_max        = 64

[ req_attributes ]
challengePassword       = A challenge password
challengePassword_min       = 4
challengePassword_max       = 20

unstructuredName        = An optional company name

[ usr_cert ]

basicConstraints=CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment

nsComment           = "OpenSSL Generated Certificate"

# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer

[ v3_req ]

# Extensions to add to a certificate request
subjectKeyIdentifier=hash

#authorityKeyIdentifier=keyid:always,issuer:always
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment

[ v3_ca ]

subjectKeyIdentifier=hash

basicConstraints = CA:true

keyUsage = cRLSign, keyCertSign

[ crl_ext ]

authorityKeyIdentifier=keyid:always,issuer:always

[ proxy_cert_ext ]
basicConstraints=CA:FALSE

nsComment           = "OpenSSL Generated Certificate"

# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer:always

proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
最简单的方法,直接用java里的keytool工具生成一个keystore文件,然后直接用这个文件启用https就可以了。 方法如下: 命令行执行%JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA 执行过程中会询问你一些信息,比如国家代码,省市等,其中需要填写两个密码,一次在开头,一次在最后,请保持两个密码相同。比如,我将密码都设成s3cret。 如果不同,启动会报错,大概是下面这样的 java.io.IOException: Cannot recover key 执行完成后会生成一个.keystore文件,将它复制到tomcat的bin目录下(并不一定,放哪里都可以) 打开conf目录下的server.xml文件,找到以下这一段 它被注释掉了,将注释去掉,并将这一段改成以下 maxThreads="150" scheme="https" secure="true" keystoreFile="bin/.keystore" keystorePass=" s3cret" clientAuth="false" sslProtocol="TLS" /> 之后启动tomcat就可以了,通过https方式访问8443端口,就能看到效果。如果用http访问之前的端口,那么还是普通的未加密连接。 到这里问题来了,我的目的是启用https,但现在http还能访问,那么就可以绕开https。https也就起不了什么作用了。因此要强制访问https。 打开你的web应用的web.xml文件,在最后加上这样一段 Protected Context /* CONFIDENTIAL 重启tomcat,现在你放问原来的地址,假设是http://localhost:8080/mywebapp/,可以看到,连接被重定向到了https的连接 https://localhost:8443/mywebapp/。这样,我们的目的达到了。 但似乎还有点小问题,keystorePass="s3cret",这个密码直接被明码方式卸载server.xml里。总觉得有还是有点不爽。 那么还有一种稍微复杂点的方式,我们使用openssl。 首先,需要下载openssl,为了方便,可以下载一个绿色版, 加压后除了openssl.exe以外,还有一个bat文件,这个可以帮助我们快速创建证书申请文件。 运行autocsr.bat,按照提示输入信息,之后按任意键确认。你会得到两个文件,一个server.key,这是私钥文件,还有一个名为certreq.csr的证书请求文件。 如果你要向证书颁发机构申请正式的安全证书,那么就把这个certreq.csr文件发给他们就行了。他们会给你发来两个cer文件,一个是服务器证书,一个是根证书 如果你只是要使用https,那么证书自己签署就可以了。 在命令行下进入刚才解压的目录,找到openssl.exe所在的目录,执行以下命令 openssl x509 -req -in certreq.csr -out cert.cer -signkey server.key -days 3650 现在你将得到一个名为cert.cer的证书文件。 修改server.xml将 maxThreads="150" scheme="https" secure="true" keystoreFile="bin/.keystore" keystorePass=" s3cret" clientAuth="false" sslProtocol="TLS" /> 修改为以下内容(假设cert.cer和server.key文件都放在tomcat的conf目录下) maxThreads="150" scheme="https" secure="true" SSLCertificateFile="conf/cert.cer" SSLCertificateKeyFile="conf/server.key" sslProtocol="TLS" /> PS.如果真的向证书颁发机构申请到了正式的安全证书,那么配置还有点不同,如下 maxThreads="150" scheme="https" secure="true" SSLCertificateFile="conf/server.cer" SSLCertificateKeyFile="conf/server.key" SSLCertificateChainFile="conf/intermediate.cer" sslProtocol="TLS" /> 因为证书颁发机构会给两个整数,一个是签署后的服务器证书,还有一个中级CA证书,所以要多一行配置。 可能证书颁发机构只会给你服务器证书也就是server.cer, 中级的CA证书即 intermediate.cer 需要到 证书颁发机构提供的网站中去下载,具体的操作会为证书颁发机构给发的邮箱中会有相关的提示 好了,到这里都配置完了,重启tomcat,就可以看到效果。不过,看到的通常会是一个exception,大概是说APR not available 如果遇到这个异常,说明你的tomcat没有安装apr支持 apr安装详见:http://www.blogjava.net/yongboy/archive/2009/08/31/293343.html 之后启动tomcat,问题应该解决了,看起来效果和第一种方式没什么不同。
首先,需要使用 OpenSSL 工具生成一个证书文件,包括公钥私钥: ``` openssl req -x509 -newkey rsa:2048 -keyout example.key -out example.crt -days 365 ``` 这个命令将生成一个 2048 位 RSA 密钥对,并将其用于创建自签名的 X.509 证书,有效期为一年。生成私钥将保存在 `example.key` 文件中,证书将保存在 `example.crt` 文件中。 接下来,我们可以使用 OpenSSL 的命令行工具来提取证书文件中的公钥: ``` openssl x509 -in example.crt -pubkey -noout > example.pub ``` 这个命令将从 `example.crt` 中提取公钥,并将其保存到 `example.pub` 文件中。 现在,我们可以使用 Python 的 Cryptography 模块来加密数据。以下是一个示例脚本: ```python from cryptography.hazmat.primitives.asymmetric import rsa, padding from cryptography.hazmat.primitives import serialization # 读取公钥 with open('example.pub', 'rb') as f: pubkey_bytes = f.read() pubkey = serialization.load_pem_public_key(pubkey_bytes) # 加密数据 message = b'Hello, world!' ciphertext = pubkey.encrypt(message, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) # 打印密文 print(ciphertext) ``` 这个脚本从 `example.pub` 中读取公钥,并使用 OAEP 填充方案加密了一条消息。密文将打印到控制台上。 最后,我们可以使用 OpenSSL 的命令行工具来解密数据: ``` openssl rsautl -decrypt -inkey example.key -in ciphertext.bin ``` 这个命令将使用 `example.key` 中的私钥来解密 `ciphertext.bin` 文件中的数据。请注意,`ciphertext.bin` 文件中的数据必须是二进制格式的密文,而不是 Base64 编码的字符串。 如果解密成功,您应该会看到原始的明文消息,即 `Hello, world!`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值