use of org.openecard.bouncycastle.asn1.x509.Certificate in project pac4j by pac4j.
the class SAML2ClientConfiguration method createSelfSignedCert.
/**
* Generate a self-signed certificate for dn using the provided signature algorithm and key pair.
*
* @param dn X.500 name to associate with certificate issuer/subject.
* @param sigName name of the signature algorithm to use.
* @param sigAlgID algorithm ID associated with the signature algorithm name.
* @param keyPair the key pair to associate with the certificate.
* @return an X509Certificate containing the public key in keyPair.
* @throws Exception
*/
private X509Certificate createSelfSignedCert(X500Name dn, String sigName, AlgorithmIdentifier sigAlgID, KeyPair keyPair) throws Exception {
V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
certGen.setSerialNumber(new ASN1Integer(BigInteger.valueOf(1)));
certGen.setIssuer(dn);
certGen.setSubject(dn);
certGen.setStartDate(new Time(new Date(System.currentTimeMillis() - 1000L)));
final Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.YEAR, 1);
certGen.setEndDate(new Time(c.getTime()));
certGen.setSignature(sigAlgID);
certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));
Signature sig = Signature.getInstance(sigName);
sig.initSign(keyPair.getPrivate());
sig.update(certGen.generateTBSCertificate().getEncoded(ASN1Encoding.DER));
TBSCertificate tbsCert = certGen.generateTBSCertificate();
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(tbsCert);
v.add(sigAlgID);
v.add(new DERBitString(sig.sign()));
X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER)));
// check the certificate - this will confirm the encoded sig algorithm ID is correct.
cert.verify(keyPair.getPublic());
return cert;
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project BiglyBT by BiglySoftware.
the class SESecurityManagerBC method createSelfSignedCertificate.
public static Certificate createSelfSignedCertificate(SESecurityManagerImpl manager, String alias, String cert_dn, int strength) throws Exception {
KeyPairGenerator kg = KeyPairGenerator.getInstance("RSA");
kg.initialize(strength, RandomUtils.SECURE_RANDOM);
KeyPair pair = kg.generateKeyPair();
X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
certificateGenerator.setSignatureAlgorithm("MD5WithRSAEncryption");
certificateGenerator.setSerialNumber(new BigInteger("" + SystemTime.getCurrentTime()));
X509Name issuer_dn = new X509Name(true, cert_dn);
certificateGenerator.setIssuerDN(issuer_dn);
X509Name subject_dn = new X509Name(true, cert_dn);
certificateGenerator.setSubjectDN(subject_dn);
Calendar not_after = Calendar.getInstance();
not_after.add(Calendar.YEAR, 1);
certificateGenerator.setNotAfter(not_after.getTime());
certificateGenerator.setNotBefore(Calendar.getInstance().getTime());
certificateGenerator.setPublicKey(pair.getPublic());
X509Certificate certificate = certificateGenerator.generateX509Certificate(pair.getPrivate());
java.security.cert.Certificate[] certChain = { (java.security.cert.Certificate) certificate };
manager.addCertToKeyStore(alias, pair.getPrivate(), certChain);
return (certificate);
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project keystore-explorer by kaikramer.
the class X509Ext method getMsCaVersionStringValue.
private String getMsCaVersionStringValue(byte[] octets) {
/*
"The extension data is a DWORD value (encoded as X509_INTEGER in the extension);
the low 16 bits are the certificate index, and the high 16 bits are the key index."
*/
ASN1Integer asn1Integer = ASN1Integer.getInstance(octets);
int version = asn1Integer.getValue().intValue();
String certIndex = String.valueOf(version & 0xffff);
String keyIndex = String.valueOf(version >> 16);
StringBuilder sb = new StringBuilder();
sb.append(MessageFormat.format(res.getString("MSCaVersion.CertIndex"), certIndex));
sb.append(NEWLINE);
sb.append(MessageFormat.format(res.getString("MSCaVersion.KeyIndex"), keyIndex));
sb.append(NEWLINE);
return sb.toString();
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project keystore-explorer by kaikramer.
the class Pkcs10Util method generateCsr.
/**
* Create a PKCS #10 certificate signing request (CSR) using the supplied
* certificate, private key and signature algorithm.
*
* @param cert
* The certificate
* @param privateKey
* The private key
* @param signatureType
* Signature
* @param challenge
* Challenge, optional, pass null if not required
* @param unstructuredName
* An optional company name, pass null if not required
* @param useExtensions
* Use extensions from cert for extensionRequest attribute?
* @throws CryptoException
* If there was a problem generating the CSR
* @return The CSR
*/
public static PKCS10CertificationRequest generateCsr(X509Certificate cert, PrivateKey privateKey, SignatureType signatureType, String challenge, String unstructuredName, boolean useExtensions, Provider provider) throws CryptoException {
try {
JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(cert.getSubjectX500Principal(), cert.getPublicKey());
// add challenge attribute
if (challenge != null) {
// PKCS#9 2.0: SHOULD use UTF8String encoding
csrBuilder.addAttribute(pkcs_9_at_challengePassword, new DERUTF8String(challenge));
}
if (unstructuredName != null) {
csrBuilder.addAttribute(pkcs_9_at_unstructuredName, new DERUTF8String(unstructuredName));
}
if (useExtensions) {
// add extensionRequest attribute with all extensions from the certificate
Certificate certificate = Certificate.getInstance(cert.getEncoded());
Extensions extensions = certificate.getTBSCertificate().getExtensions();
if (extensions != null) {
csrBuilder.addAttribute(pkcs_9_at_extensionRequest, extensions.toASN1Primitive());
}
}
// fall back to bouncy castle provider if given provider does not support the requested algorithm
if (provider != null && provider.getService("Signature", signatureType.jce()) == null) {
provider = new BouncyCastleProvider();
}
ContentSigner contentSigner = null;
if (provider == null) {
contentSigner = new JcaContentSignerBuilder(signatureType.jce()).build(privateKey);
} else {
contentSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider(provider).build(privateKey);
}
PKCS10CertificationRequest csr = csrBuilder.build(contentSigner);
if (!verifyCsr(csr)) {
throw new CryptoException(res.getString("NoVerifyGenPkcs10Csr.exception.message"));
}
return csr;
} catch (CertificateEncodingException e) {
throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
} catch (OperatorCreationException e) {
throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
}
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project Spark by igniterealtime.
the class SparkTrustManager method validatePath.
/**
* Validate certificate path
*
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws InvalidAlgorithmParameterException
* @throws CertPathValidatorException
* @throws CertPathBuilderException
* @throws CertificateException
*/
private void validatePath(X509Certificate[] chain) throws NoSuchAlgorithmException, KeyStoreException, InvalidAlgorithmParameterException, CertPathValidatorException, CertPathBuilderException, CertificateException {
// PKIX algorithm is defined in rfc3280
CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX");
CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX");
X509CertSelector certSelector = new X509CertSelector();
// set last certificate (often root CA) from chain for CertSelector so trust store must contain it
certSelector.setCertificate(chain[chain.length - 1]);
// checks against time validity aren't done here as are already done in checkDateValidity (X509Certificate[]
// chain)
certSelector.setCertificateValid(null);
// create parameters using trustStore as source of Trust Anchors and using X509CertSelector
PKIXBuilderParameters parameters = new PKIXBuilderParameters(allStore, certSelector);
// will use PKIXRevocationChecker (or nothing if revocation mechanisms are
// disabled) instead of the default revocation checker
parameters.setRevocationEnabled(false);
// certificates from blacklist will be rejected
if (acceptRevoked == false) {
// OCSP checking is done according to Java PKI Programmer's Guide, PKIXRevocationChecker was added in Java 8:
// https://docs.oracle.com/javase/8/docs/technotes/guides/security/certpath/CertPathProgGuide.html#PKIXRevocationChecker
PKIXRevocationChecker checker = (PKIXRevocationChecker) certPathBuilder.getRevocationChecker();
EnumSet<PKIXRevocationChecker.Option> checkerOptions = EnumSet.noneOf(PKIXRevocationChecker.Option.class);
// is enabled then in case of network issues revocation checking is omitted
if (allowSoftFail) {
checkerOptions.add(PKIXRevocationChecker.Option.SOFT_FAIL);
}
// check OCSP, CRL serve as backup
if (checkOCSP && checkCRL) {
checker.setOptions(checkerOptions);
parameters.addCertPathChecker(checker);
} else if (!checkOCSP && checkCRL) {
// check only CRL, if CRL fail then there is no fallback to OCSP
checkerOptions.add(PKIXRevocationChecker.Option.PREFER_CRLS);
checkerOptions.add(PKIXRevocationChecker.Option.NO_FALLBACK);
checker.setOptions(checkerOptions);
parameters.addCertPathChecker(checker);
}
}
try {
CertPathBuilderResult pathResult = certPathBuilder.build(parameters);
CertPath certPath = pathResult.getCertPath();
PKIXCertPathValidatorResult validationResult = (PKIXCertPathValidatorResult) certPathValidator.validate(certPath, parameters);
X509Certificate trustedCert = validationResult.getTrustAnchor().getTrustedCert();
if (trustedCert == null) {
throw new CertificateException("certificate path failed: Trusted CA is NULL");
}
// this extension is last certificate: root CA
for (int i = 0; i < chain.length - 1; i++) {
checkBasicConstraints(chain[i]);
}
} catch (CertificateRevokedException e) {
Log.warning("Certificate was revoked", e);
for (X509Certificate cert : chain) {
for (X509CRL crl : crlCollection) {
if (crl.isRevoked(cert)) {
try {
addToBlackList(cert);
} catch (IOException | HeadlessException | InvalidNameException e1) {
Log.error("Couldn't move to the blacklist", e1);
}
break;
}
}
}
throw new CertificateException("Certificate was revoked");
}
}
Aggregations