- Сохраните pfx сертификат в файл с кодом Java (ejbca)
- 1 ответ
- extract and save to file certificate and key from pkcs12 file programmatically
- extract and save to file certificate and key from pkcs12 file programmatically
- Working with Certificates and SSL
- To change the location of certificate files
- Using Java Secure Socket Extension (JSSE) Tools
- Using the keytool Utility
- To generate a certificate using the keytool utility
- To sign a digital certificate using the keytool utility
- Deleting a Certificate Using the keytool Utility
Сохраните pfx сертификат в файл с кодом Java (ejbca)
Я использую EJBCA для генерации сертификата из CommonName. В коде Java я сгенерировал закрытый ключ и открытый ключ, а затем CSR для генерации сертификата. Теперь я сохраняю сертификат в формате PEM (.cer), но мне также нужен закрытый ключ, поэтому я хочу сохранить с расширением.pfx или p12. Как я могу сделать? Это мой фактический код для генерации сертификата:
KeyPair keys; try < keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA); //SAVE PRIVKEY //PrivateKey privKey = keys.getPrivate(); //byte[] privateKeyBytes = privKey.getEncoded(); PKCS10CertificationRequest pkcs10 = new PKCS10CertificationRequest("SHA256WithRSA", CertTools.stringToBcX509Name("CN=NOUSED"), keys.getPublic(), null, keys.getPrivate()); //Print Privatekey //System.out.println(keys.getPrivate().toString()); CertificateResponse certenv = ws.certificateRequest(user1, new String(Base64.encode(pkcs10.getEncoded())), CertificateHelper.CERT_REQ_TYPE_PKCS10, null, CertificateHelper.RESPONSETYPE_CERTIFICATE); //Certificate certenv = ejbcaraws.pkcs10Req("WSTESTUSER1","foo123",new //String(Base64.encode(pkcs10.getEncoded())),null); return certenv.getCertificate (); >catch (Exception e) <>
и с этим я сохраняю сертификат:
File file = new File(path+"/"+ x509Cert.getSubjectDN().toString().replace("CN=", "") +".cer"); FileOutputStream os = new FileOutputStream(file); //os.write("-----BEGIN CERTIFICATE-----\n".getBytes("US-ASCII")); //os.write(Base64.encode(x509Cert.getEncoded(), true)); //os.write("-----END CERTIFICATE-----".getBytes("US-ASCII")); //os.close(); PEMWriter pemWriter = new PEMWriter(new PrintWriter(os)); pemWriter.writeObject(x509Cert); pemWriter.flush(); pemWriter.close();
1 ответ
Я никогда не пользуюсь EJBCA Однако, если у вас есть сертификат и закрытый ключ, и вы хотите создать PKCS12 ты можешь использовать setKeyEntry(String alias,byte[] key,Certificate[] chain) метод из java.security.KeyStore добавить запись, а затем store(OutputStream stream, char[] password) способ сохранить PKCS12 на файл (смотрите API для более подробной информации). Ваш код может быть что-то вроде:
import java.io.FileOutputStream; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.Certificate; public class SamplePKCS12 < public static void main(String args[]) throws Exception < String alias = // the alias for your key. PrivateKey key = // your private key Certificate[] chain = // an array with your EE certificate to your CA issuer // create keystore KeyStore keystore = KeyStore.getInstance("PKCS12"); // add your key and cert keystore.setKeyEntry(alias, key.getEncoded(), chain); // save the keystore to file keystore.store(new FileOutputStream("/tmp/keystore.p12"), "yourPin".toCharArray()); >>
Обратите внимание, я полагаю, что у вас есть сертификат и закрытый ключ, как вы сказали в своем вопросе. Работать с PKCS12 тебе нужно SunJSSE провайдер (который обычно загружается по умолчанию), или вы можете использовать BouncyCastle поставщик.
extract and save to file certificate and key from pkcs12 file programmatically
posted 15 years ago
I have a PKCS12 file that i would like to extract a certificate and private key from. Is it possible to extract the key and certificate using java and saving it as a jks file?
The reason i want to use java (programmatically is because) the password for the pkcs12 keystore is in characters than can not really be typed on the command prompt.
posted 15 years ago
Is it possible to extract the key and certificate using java and saving it as a jks file?
I would definitely imagine so. I don’t know enough about what you’re actually trying to do to give you any advice, but tell us more and I’m sure we can help you further if needed.
It sounds like you need to open the file, parse through it to extract the key you’re looking for, and then save it in your .jks file. What are you having trouble with exactly?
posted 15 years ago
The keystore i have is in PKCS format. I cant use keytool or openssl to view its contents because its password is not the actual password to use.
I am supposed to use the password string to get the MD5 has of this string. The actual password becomes the string from the MD5 bytes of the original string. For example for the string «Baltimore1,» the password is ���_>y’?s�3����^
I have been able to use the above password programmatically to view the contents of the p12 keystore.
The problem i have with the above approach is that the libraries i want to use the keystore on (Apache Rampart or WSS4J) expects the password to be stored as plain text. I cant really store the string ���_>y’?s�3����^ in a properties file.
So what i want to do is to extract the key/certificate from the p12 file and save it on a jks keystore with a password that is readable and that can be stored in a properties/configuration file.
extract and save to file certificate and key from pkcs12 file programmatically
posted 15 years ago
I have a PKCS12 file that i would like to extract a certificate and private key from. Is it possible to extract the key and certificate using java and saving it as a jks file?
The reason i want to use java (programmatically is because) the password for the pkcs12 keystore is in characters than can not really be typed on the command prompt.
posted 15 years ago
Is it possible to extract the key and certificate using java and saving it as a jks file?
I would definitely imagine so. I don’t know enough about what you’re actually trying to do to give you any advice, but tell us more and I’m sure we can help you further if needed.
It sounds like you need to open the file, parse through it to extract the key you’re looking for, and then save it in your .jks file. What are you having trouble with exactly?
posted 15 years ago
The keystore i have is in PKCS format. I cant use keytool or openssl to view its contents because its password is not the actual password to use.
I am supposed to use the password string to get the MD5 has of this string. The actual password becomes the string from the MD5 bytes of the original string. For example for the string «Baltimore1,» the password is ���_>y’?s�3����^
I have been able to use the above password programmatically to view the contents of the p12 keystore.
The problem i have with the above approach is that the libraries i want to use the keystore on (Apache Rampart or WSS4J) expects the password to be stored as plain text. I cant really store the string ���_>y’?s�3����^ in a properties file.
So what i want to do is to extract the key/certificate from the p12 file and save it on a jks keystore with a password that is readable and that can be stored in a properties/configuration file.
Working with Certificates and SSL
Installation of the Application Server generates a digital certificate in JSSE (Java Secure Socket Extension) format suitable for internal testing. By default, the Application Server stores its certificate information in two files in the domain-dir /config directory:
- Keystore file, keystore.jks, contains the Application Server’s certificate, including its private key. The keystore file is protected with a password, initially changeit. Change the password using keytool . For more information about keytool , read Using the keytool Utility. Each keystore entry has a unique alias. After installation, the Application Server keystore has a single entry with alias s1as.
- Truststore file, cacerts.jks, contains the Application Server’s trusted certificates, including public keys for other entities. For a trusted certificate, the server has confirmed that the public key in the certificate belongs to the certificate’s owner. Trusted certificates generally include those of certification authorities (CAs). In the Platform Edition, on the server side, the Application Server uses the JSSE format, which uses keytool to manage certificates and key stores. In the Enterprise Edition, on the server side, the Application Server uses NSS, which uses certutil to manage the NSS database which stores private keys and certificates. In both editions, the client side (appclient or stand-alone), uses the JSSE format. By default, the Application Server is configured with a keystore and truststore that will work with the example applications and for development purposes. For production purposes, you may wish to change the certificate alias, add other certificates to the truststore, or change the name and/or location of the keystore and truststore files.
To change the location of certificate files
The keystore and truststore files provided for development are stored in the domain-dir /config directory.
-Djavax.net.ssl.keyStore=$/path/ks-name -Djavax.net.ssl.trustStore=$/path/ts-name
Using Java Secure Socket Extension (JSSE) Tools
Use keytool to set up and work with JSSE (Java Secure Socket Extension) digital certificates. In the Platform Edition, the Application Server uses the JSSE format on the server side to manage certificates and key stores. In both the Platform Edition and Enterprise Edition, the client side (appclient or stand-alone) uses the JSSE format.
The J2SE SDK ships with keytool, which enables the administrator to administer public/private key pairs and associated certificates. It also enables users to cache the public keys (in the form of certificates) of their communicating peers.
To run keytool , the shell environment must be configured so that the J2SE /bin directory is in the path, or the full path to the tool must be present on the command line. For more information on keytool , see the keytool documentation at http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/keytool.html.
Using the keytool Utility
The following examples demonstrate usage related to certificate handling using JSSE tools:
keytool -genkey -noprompt -trustcacerts -keyalg RSA -alias $ -dname $ -keypass $ -keystore $ -storepass $
keytool -genkey -noprompt -trustcacerts -alias $ -dname $ -keypass $ -keystore $ -storepass $
keytool -list -v -keystore $ -storepass $
keytool -list -v -alias $ -keystore $ -storepass $
keytool -import -noprompt -trustcacerts -alias $ -file $ -keystore $ -storepass $
keytool -export -noprompt -alias $ -file $ -keystore $ -storepass $
keytool -export -noprompt -rfc -alias $ -file $ -keystore $ -storepass $
keytool -delete -noprompt -alias $ -keystore $ -storepass $
To generate a certificate using the keytool utility
Use keytool to generate, import, and export certificates. By default, keytool creates a keystore file in the directory where it is run.
keytool -genkey -alias keyAlias-keyalg RSA -keypass changeit -storepass changeit -keystore keystore.jks
keytool -export -alias keyAlias-storepass changeit -file server.cer -keystore keystore.jks
keytool -import -v -trustcacerts -alias keyAlias -file server.cer -keystore cacerts.jks -keypass changeit
Certificate was added to keystore [Saving cacerts.jks]
To sign a digital certificate using the keytool utility
After creating a digital certificate, the owner must sign it to prevent forgery. E-commerce sites, or those for which authentication of identity is important can purchase a certificate from a well-known Certificate Authority (CA). If authentication is not a concern, for example if private secure communications is all that is required, save the time and expense involved in obtaining a CA certificate and use a self-signed certificate.
keytool -import -v -trustcacerts -alias keyAlias -file server.cer -keystore cacerts.jks -keypass changeit -storepass changeit
Deleting a Certificate Using the keytool Utility
To delete an existing certificate, use the keytool -delete command, for example:
keytool -delete -alias keyAlias -keystore keystore-name -storepass password
For a complete list of possible options for the -delete command, refer to the keytool documentation at http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/keytool.html.