我只有一个私钥作为.key文件,没有其他.crt或ca内容。我需要创建一个Java密钥库。如何转换?
我到目前为止尝试过的:我将.key文件重命名为.pem。我使用openssl在.pem中创建了.p12文件。
最后,我使用此命令来创建Java密钥库:
keytool -importkeystore -srckeystore [MY_FILE.p12] -srcstoretype pkcs12
-srcalias [ALIAS_SRC] -destkeystore [MY_KEYSTORE.jks]
-deststoretype jks -deststorepass [PASSWORD_JKS] -destalias [ALIAS_DEST]
我被要求输入密码,然后输入错误:
PEM_read_bio:no start line: ...... Expecting: TRUSTED CERTIFICATE
我已经检查了缺失的空格,并且该文件以“ -----”开头,也以它结尾。
有人知道这样做的方法吗?
您没有显示所使用的openssl命令,但这可能是错误的,因为您引用的错误来自openssl和not keytool,因此您的keytool命令可能无法工作。
但是,您的目标是不明智的。 JavaKeyStore
API旨在存储私钥具有证书(或证书)的私钥,对于没有证书的私钥,keytool和大多数其他程序都将无法正常工作或根本无法正常工作。当您没有用于私钥的真实证书时,在Java中(通常也是在OpenSSL中)通常的做法是创建“虚拟”自签名证书;这不会像真实证书那样扩展信任,但是它会填充证书状的漏洞,并允许程序至少运行到需要有效信任的程度。
有两种方法可以做到这一点。 OpenSSL比较容易,但是不能编程,因此不是真正的主题:
openssl req -new -x509 -inkey privkey.pem [-days N] [-subj name] -out dummy.pem
# -subj name has the form /attr=value/attr=value/...
# where commonly used attrs are C (Country), ST (State/Province),
# L (Locality), O (Organization), OU (Org Unit), CN (CommonName).
# if you omit -subj name you will be prompted for these (assuming normal config)
# -days defaults to 30
# if you modify the default config file or create and specify your own
# you can configure a variety of X.509 extensions, but for a dummy cert
# this is only rarely helpful, depending how you (will) use it
openssl pkcs12 -export -in dummy.pem -inkey privkey.pem -out keystore.p12 [-name alias]
# Java can use the PKCS12, but if you really want JKS for some reason
keytool -importkeystore -srckeystore keystore.p12 -destkeystore keystore.jks -deststoretype JKS \
[-srcstorepass p] [-deststorepass p] [-srcalias x [-destalias y]]
# most j8 can read PKCS12 without specifying it (due to a compatibility setting)
# and all j9 up autodetect the source type;
# j8 defaults dest type to JKS but j9 up do not
或者,您也可以用Java编程。 OOTB Java不会直接处理密钥的PEM格式,更重要的是仅处理OpenSSL所使用的八种格式之一,因此您应避免告诉我们您拥有哪种格式。同样,OOTB Java也没有记录证明的创建证书的方法。 keytool使用了内部类,但是在j8之后,使用内部类变得越来越困难。 BouncyCastle(bcpkix + bcprov)解决了这两个问题,该文件支持OpenSSL PEM密钥并生成X.509证书。
要阅读OpenSSL的“传统”格式未加密的私钥文件,请参见Read RSA private key of format PKCS1 in JAVAHow to Load RSA Private Key From FileGetting RSA private key from PEM BASE64 Encoded private key file
或传统加密Get a PrivateKey from a RSA .pem fileDecrypting an OpenSSL PEM Encoded RSA private key with Java?
对于PKCS8加密Reading PKCS8 in PEM format: Cannot find providerDecrypt PEM private (RSA) key with Bouncy Castle并且由于您实际上还需要公共密钥,因此哪种“传统”格式可以为您提供(如PEMKeyPair
-> KeyPair
),但PKCS8不需要Bouncy Castle - how to get Public Key Info from JceOpenSSLPKCS8DecryptorProviderBuilder(我的)
用于通过Bouncy生成自签名证书Self signed X509 Certificate with Bouncy Castle in JavaGenerating X509 Certificate using Bouncy Castle Java(但不要使用SHA1)也许Generating X509Certificate using bouncycastle X509v3CertificateBuilder