Search in sources :

Example 41 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project nessie by projectnessie.

the class TestHttpsClient method generateCertHolder.

private static X509CertificateHolder generateCertHolder(SecureRandom random, ZonedDateTime now, KeyPair keyPair) throws Exception {
    final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE).addRDN(BCStyle.CN, "localhost").addRDN(BCStyle.OU, "Dremio Corp. (auto-generated)").addRDN(BCStyle.O, "Dremio Corp. (auto-generated)").addRDN(BCStyle.L, "Mountain View").addRDN(BCStyle.ST, "California").addRDN(BCStyle.C, "US");
    final Date notBefore = Date.from(now.minusDays(1).toInstant());
    final Date notAfter = Date.from(now.plusYears(1).toInstant());
    final BigInteger serialNumber = new BigInteger(128, random);
    // create a certificate valid for 1 years from now
    // add the main hostname + the alternative hostnames to the SAN extension
    final GeneralName[] alternativeSubjectNames = new GeneralName[1];
    alternativeSubjectNames[0] = new GeneralName(GeneralName.dNSName, "localhost");
    final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic()).addExtension(Extension.subjectAlternativeName, false, new DERSequence(alternativeSubjectNames));
    // sign the certificate using the private key
    final ContentSigner contentSigner;
    try {
        contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());
    } catch (OperatorCreationException e) {
        throw new GeneralSecurityException(e);
    }
    return certificateBuilder.build(contentSigner);
}
Also used : X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) DERSequence(org.bouncycastle.asn1.DERSequence) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) GeneralSecurityException(java.security.GeneralSecurityException) ContentSigner(org.bouncycastle.operator.ContentSigner) BigInteger(java.math.BigInteger) GeneralName(org.bouncycastle.asn1.x509.GeneralName) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) Date(java.util.Date)

Example 42 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project aws-greengrass-nucleus by aws-greengrass.

the class EncryptionUtilsTest method generateCertificateFile.

public static Pair<Path, KeyPair> generateCertificateFile(int keySize, boolean pem, Path filepath, boolean ec) throws Exception {
    KeyPair keyPair;
    if (ec) {
        keyPair = generateECKeyPair(keySize);
    } else {
        keyPair = generateRSAKeyPair(keySize);
    }
    X500Name name = new X500Name("CN=ROOT");
    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    Date start = new Date();
    Date until = Date.from(LocalDate.now().plus(365, ChronoUnit.DAYS).atStartOfDay().toInstant(ZoneOffset.UTC));
    X509v3CertificateBuilder builder = new X509v3CertificateBuilder(name, new BigInteger(10, new SecureRandom()), start, until, name, subjectPublicKeyInfo);
    String signingAlgo = "SHA256WithRSA";
    if (ec) {
        signingAlgo = "SHA256WITHECDSA";
    }
    ContentSigner signer = new JcaContentSignerBuilder(signingAlgo).setProvider(new BouncyCastleProvider()).build(keyPair.getPrivate());
    X509CertificateHolder holder = builder.build(signer);
    X509Certificate certificate = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(holder);
    if (pem) {
        try (PrintWriter out = new PrintWriter(filepath.toFile())) {
            out.println("-----BEGIN CERTIFICATE-----");
            out.println(new String(Base64.encodeBase64(certificate.getEncoded())));
            out.println("-----END CERTIFICATE-----");
        }
    } else {
        try (OutputStream outputStream = Files.newOutputStream(filepath)) {
            outputStream.write(certificate.getEncoded());
        }
    }
    return new Pair<>(filepath, keyPair);
}
Also used : KeyPair(java.security.KeyPair) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) OutputStream(java.io.OutputStream) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) LocalDate(java.time.LocalDate) X509Certificate(java.security.cert.X509Certificate) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) PrintWriter(java.io.PrintWriter) KeyPair(java.security.KeyPair)

Example 43 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project PCNGateway-Java-SDK by BSNDA.

the class R1Algorithm method getUserCertInfo.

/**
 * Get certificate CSR
 *
 * @param DN
 * @return
 */
@Override
public UserCertInfo getUserCertInfo(String DN) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    int algSize = 256;
    String sigAlg = "SHA256withECDSA";
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECDSA");
    kpg.initialize(algSize, new SecureRandom());
    KeyPair kp = kpg.generateKeyPair();
    PrivateKey privateKey = kp.getPrivate();
    Signature signature = Signature.getInstance(sigAlg);
    signature.initSign(privateKey);
    X500Name x500Name = new X500Name(DN);
    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(kp.getPublic().getEncoded());
    PKCS10CertificationRequestBuilder builder = new PKCS10CertificationRequestBuilder(x500Name, subjectPublicKeyInfo);
    JcaContentSignerBuilder jcaContentSignerBuilder = new JcaContentSignerBuilder(sigAlg);
    Provider BC = new BouncyCastleProvider();
    jcaContentSignerBuilder.setProvider(BC);
    ContentSigner contentSigner = jcaContentSignerBuilder.build(kp.getPrivate());
    PKCS10CertificationRequest csr = builder.build(contentSigner);
    byte[] der = csr.getEncoded();
    String strPEMCSR = "-----BEGIN CERTIFICATE REQUEST-----\n";
    strPEMCSR += new String(org.bouncycastle.util.encoders.Base64.encode(der));
    strPEMCSR += "\n-----END CERTIFICATE REQUEST-----\n";
    UserCertInfo user = new UserCertInfo();
    user.setCSRPem(strPEMCSR);
    user.setKey(privateKey);
    return user;
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) UserCertInfo(com.bsnbase.sdk.util.common.UserCertInfo) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 44 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project pdf-sign-check by spapas.

the class CRLVerifier method getCrlDistributionPoints.

/**
 * Extracts all CRL distribution point URLs from the "CRL Distribution
 * Point" extension in a X.509 certificate. If CRL distribution point
 * extension is unavailable, returns an empty list.
 * @param cert
 * @return List of CRL distribution point URLs.
 * @throws java.io.IOException
 */
public static List<String> getCrlDistributionPoints(X509Certificate cert) throws IOException {
    byte[] crldpExt = cert.getExtensionValue(Extension.cRLDistributionPoints.getId());
    if (crldpExt == null) {
        return new ArrayList<>();
    }
    ASN1Primitive derObjCrlDP;
    try (ASN1InputStream oAsnInStream = new ASN1InputStream(crldpExt)) {
        derObjCrlDP = oAsnInStream.readObject();
    }
    if (!(derObjCrlDP instanceof ASN1OctetString)) {
        LOG.warn("CRL distribution points for certificate subject " + cert.getSubjectX500Principal().getName() + " should be an octet string, but is " + derObjCrlDP);
        return new ArrayList<>();
    }
    ASN1OctetString dosCrlDP = (ASN1OctetString) derObjCrlDP;
    byte[] crldpExtOctets = dosCrlDP.getOctets();
    ASN1Primitive derObj2;
    try (ASN1InputStream oAsnInStream2 = new ASN1InputStream(crldpExtOctets)) {
        derObj2 = oAsnInStream2.readObject();
    }
    CRLDistPoint distPoint = CRLDistPoint.getInstance(derObj2);
    List<String> crlUrls = new ArrayList<>();
    for (DistributionPoint dp : distPoint.getDistributionPoints()) {
        DistributionPointName dpn = dp.getDistributionPoint();
        // Look for URIs in fullName
        if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) {
            // Look for an URI
            for (GeneralName genName : GeneralNames.getInstance(dpn.getName()).getNames()) {
                if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) {
                    String url = ASN1IA5String.getInstance(genName.getName()).getString();
                    crlUrls.add(url);
                }
            }
        }
    }
    return crlUrls;
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ArrayList(java.util.ArrayList) DistributionPointName(org.bouncycastle.asn1.x509.DistributionPointName) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1IA5String(org.bouncycastle.asn1.ASN1IA5String) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint)

Example 45 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project Falcon-File-Transfer-Optimizer by arif-zaman.

the class X509ProxyCertPathValidator method validate.

/**
 * Validates the certificate path and does the following for each certificate in the chain: method
 * checkCertificate() In addition: a) Validates if the issuer type of each certificate is correct b) CA path
 * constraints c) Proxy path constraints
 * <p>
 * If it is of type proxy, check following: a) proxy constraints b) restricted proxy else if certificate, check the
 * following: a) keyisage
 *
 * @param certPath The CertPath to validate.
 * @return The results of the validation.
 * @throws CertPathValidatorException If the CertPath is invalid.
 */
protected CertPathValidatorResult validate(CertPath certPath) throws CertPathValidatorException {
    List<? extends Certificate> certificates = certPath.getCertificates();
    if (certificates.size() == 0) {
        return null;
    }
    X509Certificate cert;
    TBSCertificateStructure tbsCert;
    GSIConstants.CertificateType certType;
    X509Certificate issuerCert;
    TBSCertificateStructure issuerTbsCert;
    GSIConstants.CertificateType issuerCertType;
    int proxyDepth = 0;
    cert = (X509Certificate) certificates.get(0);
    try {
        tbsCert = getTBSCertificateStructure(cert);
        certType = getCertificateType(tbsCert);
        // validate the first certificate in chain
        checkCertificate(cert, certType);
        boolean isProxy = ProxyCertificateUtil.isProxy(certType);
        if (isProxy) {
            proxyDepth++;
        }
    } catch (CertPathValidatorException e) {
        throw new CertPathValidatorException("Path validation failed for " + cert.getSubjectDN() + ": " + e.getMessage(), e, certPath, 0);
    }
    for (int i = 1; i < certificates.size(); i++) {
        boolean certIsProxy = ProxyCertificateUtil.isProxy(certType);
        issuerCert = (X509Certificate) certificates.get(i);
        issuerTbsCert = getTBSCertificateStructure(issuerCert);
        issuerCertType = getCertificateType(issuerTbsCert);
        proxyDepth = validateCert(cert, certType, issuerCert, issuerTbsCert, issuerCertType, proxyDepth, i, certIsProxy);
        if (certIsProxy) {
            try {
                checkProxyConstraints(certPath, cert, tbsCert, certType, issuerTbsCert, i);
            } catch (CertPathValidatorException e) {
                throw new CertPathValidatorException("Path validation failed for " + cert.getSubjectDN() + ": " + e.getMessage(), e, certPath, i - 1);
            }
        } else {
            try {
                checkKeyUsage(issuerTbsCert);
            } catch (IOException e) {
                throw new CertPathValidatorException("Key usage check failed on " + issuerCert.getSubjectDN() + ": " + e.getMessage(), e, certPath, i);
            } catch (CertPathValidatorException e) {
                throw new CertPathValidatorException("Path validation failed for " + issuerCert.getSubjectDN() + ": " + e.getMessage(), e, certPath, i);
            }
        }
        try {
            checkCertificate(issuerCert, issuerCertType);
        } catch (CertPathValidatorException e) {
            throw new CertPathValidatorException("Path validation failed for " + issuerCert.getSubjectDN() + ": " + e.getMessage(), e, certPath, i);
        }
        cert = issuerCert;
        certType = issuerCertType;
        tbsCert = issuerTbsCert;
    }
    return new X509ProxyCertPathValidatorResult(this.identityCert, this.limited);
}
Also used : GSIConstants(org.globus.gsi.GSIConstants) CertPathValidatorException(java.security.cert.CertPathValidatorException) TBSCertificateStructure(org.bouncycastle.asn1.x509.TBSCertificateStructure) IOException(java.io.IOException) X509ProxyCertPathValidatorResult(org.globus.gsi.X509ProxyCertPathValidatorResult) X509Certificate(java.security.cert.X509Certificate)

Aggregations

IOException (java.io.IOException)242 X509Certificate (java.security.cert.X509Certificate)216 Date (java.util.Date)133 X500Name (org.bouncycastle.asn1.x500.X500Name)133 BigInteger (java.math.BigInteger)120 ContentSigner (org.bouncycastle.operator.ContentSigner)102 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)101 GeneralName (org.bouncycastle.asn1.x509.GeneralName)100 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)96 CertificateException (java.security.cert.CertificateException)95 ArrayList (java.util.ArrayList)90 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)85 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)82 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)78 GeneralSecurityException (java.security.GeneralSecurityException)69 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)62 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)62 Extension (org.bouncycastle.asn1.x509.Extension)61 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)60 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)59