Criação de um Certificado X509 em Java sem BouncyCastle?
-
06-07-2019 - |
Pergunta
É possível sadia e criar um Certificado X509 em código Java sem usar o Bouncy Castle X509V*CertificateGenerator
classes?
Solução
A capacidade para assinar certificados não é parte de um padrão de Java ou biblioteca de extensão.
Um monte de código que é necessário para fazê-lo sozinho é parte do núcleo.Há aulas para codificar e decodificar X. 500 nomes, X. 509 certificado de extensões de chaves públicas para os vários algoritmos, e, claro, para realmente realizar a assinatura digital.
A implementação deste si mesmo não é trivial, mas é definitivamente possível—provavelmente passei 4 ou 5 dias a primeira vez que fiz um protótipo funcional para assinatura de certificado.Ele foi um fantástico exercício de aprendizagem para mim, mas é difícil justificar a despesa, quando não são utilizáveis bibliotecas disponíveis gratuitamente.
Outras dicas
Sim, mas não com classes documentadas publicamente. Eu documentei o processo neste artigo.
import sun.security.x509.*;
import java.security.cert.*;
import java.security.*;
import java.math.BigInteger;
import java.util.Date;
import java.io.IOException
/**
* Create a self-signed X.509 Certificate
* @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
* @param pair the KeyPair
* @param days how many days from now the Certificate is valid for
* @param algorithm the signing algorithm, eg "SHA1withRSA"
*/
X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm)
throws GeneralSecurityException, IOException
{
PrivateKey privkey = pair.getPrivate();
X509CertInfo info = new X509CertInfo();
Date from = new Date();
Date to = new Date(from.getTime() + days * 86400000l);
CertificateValidity interval = new CertificateValidity(from, to);
BigInteger sn = new BigInteger(64, new SecureRandom());
X500Name owner = new X500Name(dn);
info.set(X509CertInfo.VALIDITY, interval);
info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));
// Sign the cert to identify the algorithm that's used.
X509CertImpl cert = new X509CertImpl(info);
cert.sign(privkey, algorithm);
// Update the algorith, and resign.
algo = (AlgorithmId)cert.get(X509CertImpl.SIG_ALG);
info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo);
cert = new X509CertImpl(info);
cert.sign(privkey, algorithm);
return cert;
}
import sun.security.x509.*;
import java.security.cert.*;
import java.security.*;
import java.math.BigInteger;
import java.security.cert.Certificate;
import java.util.Date;
import java.io.IOException;
public class Example {
/**
* Create a self-signed X.509 Example
*
* @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
* @param pair the KeyPair
* @param days how many days from now the Example is valid for
* @param algorithm the signing algorithm, eg "SHA1withRSA"
*/
public X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm)
throws GeneralSecurityException, IOException {
PrivateKey privkey = pair.getPrivate();
X509CertInfo info = new X509CertInfo();
Date from = new Date();
Date to = new Date(from.getTime() + days * 86400000l);
CertificateValidity interval = new CertificateValidity(from, to);
BigInteger sn = new BigInteger(64, new SecureRandom());
X500Name owner = new X500Name(dn);
info.set(X509CertInfo.VALIDITY, interval);
info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
info.set(X509CertInfo.SUBJECT, owner);
info.set(X509CertInfo.ISSUER, owner);
info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));
// Sign the cert to identify the algorithm that's used.
X509CertImpl cert = new X509CertImpl(info);
cert.sign(privkey, algorithm);
// Update the algorith, and resign.
algo = (AlgorithmId) cert.get(X509CertImpl.SIG_ALG);
info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo);
cert = new X509CertImpl(info);
cert.sign(privkey, algorithm);
return cert;
}
public static void main (String[] argv) throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = keyPairGenerator.generateKeyPair();
Example example = new Example();
String distinguishedName = "CN=Test, L=London, C=GB";
Certificate certificate = example.generateCertificateOriginal(distinguishedName, keyPair, 365, "SHA256withRSA");
System.out.println("it worked!");
}
}
Gostei da resposta de VBence, mas continuei recebendo a seguinte exceção:
Java.Security.Cert.CertificateException: Tipo de classe de assunto inválido.
Depois de muitas tentativas de descobrir foi Uma classe de assunto válida descobri que o x509Cerinfo queria uma instância do x500Name.
1 info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
2 info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
3 info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
4 info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
Então, as linhas 2 e 3 precisavam mudar para
2 info.set(X509CertInfo.SUBJECT, owner);
3 info.set(X509CertInfo.ISSUER, owner);
Todos os componentes básicos para fazer um certificado autoassinado (assinatura, codificação x509 etc.) estão disponíveis no JRE. Ao contrário do BC, o Sun's JCE não fornece chamadas públicas para assinar um certificado. No entanto, todas as funções estão disponíveis no Keytool. Você pode simplesmente copiar o código do KeyTool para fazer isso. O método que você precisa copiar é doSelfCert()
.
Depende do que exatamente você deseja fazer (e provavelmente da sua definição de "Surely"). Como o ZZ Coder apontou, você pode criar um certificado autoassinado diretamente copiando ferramenta-chave. Mas não acredito que você possa criar um objeto Solicitação de certificado PKCS10 com o JCE padrão, o que você provavelmente precisa fazer se deseja criar EECs assinados por CA padrão.