Como criar um certificado X509 usando Java?
quero criar um certificado X509 usando a linguagem Java e depois extrair a chave pública dela.
procurei na internet e encontrei muitos exemplos de código, mas todos eles têm erros (variável desconhecida ou tipo desconhecido) ou têm muitos avisos que dizem algo como : "o método ... do tipo ... é obsoleto " etc.
por exemplo, porque é que o seguinte código não funciona:
PublicKey pk;
CertificateFactory cf = CertificateFactory.getInstance("X.509");
String PKstr = pk.toString();
InputStream PKstream = new ByteArrayInputStream(PKstr.getBytes());
X509Certificate pkcert = (X509Certificate)cf.generateCertificate(PKstream);
Alguém me pode mostrar como criar um certificado usando Java puro ou insuflável Castle e depois obter uma chave pública disso?
2 answers
Você também pode gerar um certificado usando apenas as classes JDK. A desvantagem é que você tem que usar duas classes do sol.seguranca.pacote x509. O código seria:
KeyStore keyStore = ... // your keystore
// generate the certificate
// first parameter = Algorithm
// second parameter = signrature algorithm
// third parameter = the provider to use to generate the keys (may be null or
// use the constructor without provider)
CertAndKeyGen certGen = new CertAndKeyGen("RSA", "SHA256WithRSA", null);
// generate it with 2048 bits
certGen.generate(2048);
// prepare the validity of the certificate
long validSecs = (long) 365 * 24 * 60 * 60; // valid for one year
// add the certificate information, currently only valid for one year.
X509Certificate cert = certGen.getSelfCertificate(
// enter your details according to your application
new X500Name("CN=My Application,O=My Organisation,L=My City,C=DE"), validSecs);
// set the certificate and the key in the keystore
keyStore.setKeyEntry(certAlias, certGen.getPrivateKey(), null,
new X509Certificate[] { cert });
Obtém a chave privada do armazém de chaves para cifrar ou descodificar os dados. Baseado no código é de http://www.pixelstech.net/article/1408524957-Generate-cetrificate-in-Java----3