Search in sources :

Example 11 with X500Name

use of android.sun.security.x509.X500Name in project dcache by dCache.

the class ServerGsiEngineDssContextFactoryTest method generateSelfSignedCert.

private void generateSelfSignedCert() throws GeneralSecurityException, OperatorCreationException, IOException {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
    keyPairGenerator.initialize(2048, new SecureRandom());
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    long notBefore = System.currentTimeMillis();
    long notAfter = notBefore + TimeUnit.DAYS.toMillis(1);
    X500Name subjectDN = new X500Name("CN=localhost, O=dCache.org");
    X500Name issuerDN = subjectDN;
    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(issuerDN, BigInteger.ONE, new Date(notBefore), new Date(notAfter), subjectDN, subjectPublicKeyInfo);
    String signatureAlgorithm = "SHA256WithRSA";
    // sign with own key
    ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate());
    X509CertificateHolder certificateHolder = certificateBuilder.build(contentSigner);
    var cert = new JcaX509CertificateConverter().getCertificate(certificateHolder);
    try (OutputStream certOut = Files.newOutputStream(certFile.toPath(), CREATE, TRUNCATE_EXISTING, WRITE);
        OutputStream keyOut = Files.newOutputStream(keyFile.toPath(), CREATE, TRUNCATE_EXISTING, WRITE)) {
        CertificateUtils.saveCertificate(certOut, cert, Encoding.PEM);
        CertificateUtils.savePrivateKey(keyOut, keyPair.getPrivate(), Encoding.PEM, null, null);
    }
}
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) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder)

Example 12 with X500Name

use of android.sun.security.x509.X500Name in project powerauth-webflow by wultra.

the class ICACertificateParser method parse.

/**
 * Parse certificate in PEM format and return structured information about organization.
 *
 * @param certificatePem Certificate in PEM format.
 * @return Structured certificate information.
 * @throws CertificateException In case certificate cannot be parsed (or in rare case X.509 is not supported).
 */
public CertInfo parse(String certificatePem) throws CertificateException {
    // Check for null certificate value
    if (certificatePem == null) {
        throw new CertificateException("Certificate in PEM format not found.");
    }
    // Handle the URL encoded certificates
    if (certificatePem.startsWith("-----BEGIN%20CERTIFICATE-----")) {
        // certificate is URL encoded by nginx.
        try {
            certificatePem = URLDecoder.decode(certificatePem, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException e) {
            throw new CertificateException("Unable to extract certificate in PEM format (nginx).");
        }
    }
    // Replace spaces in Apache forwarded certificate by newlines correctly
    certificatePem = certificatePem.replaceAll(" ", "\n").replace("-----BEGIN\nCERTIFICATE-----", "-----BEGIN CERTIFICATE-----").replace("-----END\nCERTIFICATE-----", "-----END CERTIFICATE-----");
    final CertificateFactory cf = CertificateFactory.getInstance("X.509");
    final ByteArrayInputStream bais = new ByteArrayInputStream(certificatePem.getBytes(StandardCharsets.UTF_8));
    X509Certificate cert = (X509Certificate) cf.generateCertificate(bais);
    try {
        final byte[] qcStatement = cert.getExtensionValue("1.3.6.1.5.5.7.1.3");
        if (qcStatement == null) {
            throw new CertificateException("Unable to extract PSD2 mandates.");
        }
        final ASN1Primitive qcStatementAsn1Primitive = JcaX509ExtensionUtils.parseExtensionValue(qcStatement);
        if (qcStatementAsn1Primitive == null) {
            throw new CertificateException("Unable to extract PSD2 mandates from extension value.");
        }
        final DLSequence it = ((DLSequence) qcStatementAsn1Primitive);
        Set<CertInfo.PSD2> psd2Mandates = new HashSet<>();
        for (ASN1Encodable asn1Primitive : it) {
            if (asn1Primitive instanceof DLSequence) {
                DLSequence sequence = (DLSequence) asn1Primitive;
                if (sequence.size() == 2) {
                    ASN1ObjectIdentifier id = (ASN1ObjectIdentifier) sequence.getObjectAt(0);
                    DLSequence mandates = (DLSequence) sequence.getObjectAt(1);
                    if (psd2.equals(id.getId())) {
                        for (ASN1Encodable mandate : mandates) {
                            if (mandate instanceof DLSequence) {
                                for (ASN1Encodable seq : (DLSequence) mandate) {
                                    DLSequence a = (DLSequence) seq;
                                    final ASN1ObjectIdentifier identifier = (ASN1ObjectIdentifier) ((DLSequence) seq).getObjectAt(0);
                                    if (psp_as.equals(identifier.getId())) {
                                        psd2Mandates.add(CertInfo.PSD2.PSP_AS);
                                    }
                                    if (psp_ai.equals(identifier.getId())) {
                                        psd2Mandates.add(CertInfo.PSD2.PSP_AI);
                                    }
                                    if (psp_pi.equals(identifier.getId())) {
                                        psd2Mandates.add(CertInfo.PSD2.PSP_PI);
                                    }
                                    if (psp_ic.equals(identifier.getId())) {
                                        psd2Mandates.add(CertInfo.PSD2.PSP_IC);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        final List<AVA> avaList = ((X500Name) cert.getSubjectDN()).allAvas();
        String country = null;
        String serialNumber = null;
        String commonName = null;
        String psd2License = null;
        String organization = null;
        String street = null;
        String city = null;
        String zipCode = null;
        String region = null;
        String website = null;
        for (AVA ava : avaList) {
            final String oid = ava.getObjectIdentifier().toString();
            final String val = ava.getValueString();
            switch(oid) {
                case "2.5.4.6":
                    {
                        // C=CZ => 2.5.4.6
                        country = val;
                        break;
                    }
                case "2.5.4.3":
                    {
                        // CN=cnb.cz => 2.5.4.3
                        commonName = val;
                        website = "https://" + val;
                        break;
                    }
                case "2.5.4.10":
                    {
                        // O=ČESKÁ NÁRODNÍ BANKA => 2.5.4.10
                        organization = val;
                        break;
                    }
                case "2.5.4.9":
                    {
                        // STREET=Na příkopě 864/28 => 2.5.4.9
                        street = val;
                        break;
                    }
                case "2.5.4.7":
                    {
                        // L=Praha 1 => 2.5.4.7
                        city = val;
                        break;
                    }
                case "2.5.4.17":
                    {
                        // OID.2.5.4.17=11000 => 2.5.4.17
                        zipCode = val;
                        break;
                    }
                case "2.5.4.5":
                    {
                        // SERIALNUMBER=48136450 => 2.5.4.5
                        serialNumber = val;
                        break;
                    }
                case "2.5.4.8":
                    {
                        // ST=Hlavní město Praha => 2.5.4.8
                        region = val;
                        break;
                    }
                case "2.5.4.97":
                    {
                        // OID.2.5.4.97=PSDCZ-CNB-48136450 => 2.5.4.97
                        psd2License = val;
                        break;
                    }
            }
        }
        return new CertInfo(serialNumber, commonName, psd2License, organization, street, city, zipCode, region, country, website, psd2Mandates);
    } catch (Throwable e) {
        // catch all errors that can occur
        throw new CertificateException("Unable to extract PSD2 mandates.");
    }
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) CertificateException(java.security.cert.CertificateException) X500Name(sun.security.x509.X500Name) AVA(sun.security.x509.AVA) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) DLSequence(org.bouncycastle.asn1.DLSequence) ByteArrayInputStream(java.io.ByteArrayInputStream) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) HashSet(java.util.HashSet)

Example 13 with X500Name

use of android.sun.security.x509.X500Name in project interlok by adaptris.

the class X509Builder method build.

private X509Certificate build() throws NoSuchAlgorithmException, CertificateException, OperatorCreationException {
    X509Certificate result = null;
    if (privateKey == null) {
        createKeyPair();
    }
    // The certificate is self-signed, so use the current
    // subject as the issuer
    X500Name name = certificateParm.getSubjectInfo();
    // The certificate is self-signed, do we exactly care what
    // the serial number that uniquely identifies is
    BigInteger serial = BigInteger.valueOf(Integer.valueOf(SecurityUtil.getSecureRandom().nextInt(10000)).longValue());
    GregorianCalendar valid = new GregorianCalendar();
    Date notBefore = valid.getTime();
    valid.add(Calendar.MONTH, 12);
    Date notAfter = valid.getTime();
    SubjectPublicKeyInfo pubKeyInfo = SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(publicKey.getEncoded()));
    X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(name, serial, notBefore, notAfter, name, pubKeyInfo);
    String alg = certificateParm.getSignatureAlgorithm();
    JcaContentSignerBuilder builder = new JcaContentSignerBuilder(alg);
    // build and sign the certificate
    X509CertificateHolder certHolder = certGen.build(builder.build(privateKey));
    result = new JcaX509CertificateConverter().getCertificate(certHolder);
    return result;
}
Also used : X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) GregorianCalendar(java.util.GregorianCalendar) BigInteger(java.math.BigInteger) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date)

Example 14 with X500Name

use of android.sun.security.x509.X500Name in project AppManager by MuntashirAkon.

the class KeyStoreUtils method generateCert.

@NonNull
private static X509Certificate generateCert(PrivateKey privateKey, PublicKey publicKey, @NonNull String formattedSubject, long expiryDate) throws CertificateException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException, InvalidKeyException, IOException {
    String algorithmName = "SHA512withRSA";
    CertificateExtensions certificateExtensions = new CertificateExtensions();
    certificateExtensions.set("SubjectKeyIdentifier", new SubjectKeyIdentifierExtension(new KeyIdentifier(publicKey).getIdentifier()));
    X500Name x500Name = new X500Name(formattedSubject);
    Date notBefore = new Date();
    Date notAfter = new Date(expiryDate);
    certificateExtensions.set("PrivateKeyUsage", new PrivateKeyUsageExtension(notBefore, notAfter));
    CertificateValidity certificateValidity = new CertificateValidity(notBefore, notAfter);
    X509CertInfo x509CertInfo = new X509CertInfo();
    x509CertInfo.set("version", new CertificateVersion(2));
    x509CertInfo.set("serialNumber", new CertificateSerialNumber(new Random().nextInt() & Integer.MAX_VALUE));
    x509CertInfo.set("algorithmID", new CertificateAlgorithmId(AlgorithmId.get(algorithmName)));
    x509CertInfo.set("subject", new CertificateSubjectName(x500Name));
    x509CertInfo.set("key", new CertificateX509Key(publicKey));
    x509CertInfo.set("validity", certificateValidity);
    x509CertInfo.set("issuer", new CertificateIssuerName(x500Name));
    x509CertInfo.set("extensions", certificateExtensions);
    X509CertImpl x509CertImpl = new X509CertImpl(x509CertInfo);
    x509CertImpl.sign(privateKey, algorithmName);
    return x509CertImpl;
}
Also used : CertificateSubjectName(android.sun.security.x509.CertificateSubjectName) KeyIdentifier(android.sun.security.x509.KeyIdentifier) X509CertInfo(android.sun.security.x509.X509CertInfo) CertificateIssuerName(android.sun.security.x509.CertificateIssuerName) CertificateVersion(android.sun.security.x509.CertificateVersion) CertificateExtensions(android.sun.security.x509.CertificateExtensions) CertificateValidity(android.sun.security.x509.CertificateValidity) X500Name(android.sun.security.x509.X500Name) CertificateX509Key(android.sun.security.x509.CertificateX509Key) Date(java.util.Date) SubjectKeyIdentifierExtension(android.sun.security.x509.SubjectKeyIdentifierExtension) CertificateSerialNumber(android.sun.security.x509.CertificateSerialNumber) Random(java.util.Random) SecureRandom(java.security.SecureRandom) X509CertImpl(android.sun.security.x509.X509CertImpl) CertificateAlgorithmId(android.sun.security.x509.CertificateAlgorithmId) PrivateKeyUsageExtension(android.sun.security.x509.PrivateKeyUsageExtension) NonNull(androidx.annotation.NonNull)

Example 15 with X500Name

use of android.sun.security.x509.X500Name in project remoting by jenkinsci.

the class X509CertificateRule method apply.

@Override
public Statement apply(final Statement base, final Description description) {
    Skip skip = description.getAnnotation(Skip.class);
    if (skip != null && (skip.value().length == 0 || Arrays.asList(skip.value()).contains(id))) {
        return base;
    }
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            Date now = new Date();
            Date firstDate = new Date(now.getTime() + startDateOffsetMillis);
            Date lastDate = new Date(now.getTime() + endDateOffsetMillis);
            SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(subjectKey.getPublic().getEncoded());
            X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
            if (id != null) {
                nameBuilder.addRDN(BCStyle.CN, id);
            }
            X500Name subject = nameBuilder.addRDN(BCStyle.CN, description.getDisplayName()).addRDN(BCStyle.C, "US").build();
            X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(subject, BigInteger.ONE, firstDate, lastDate, subject, subjectPublicKeyInfo);
            JcaX509ExtensionUtils instance = new JcaX509ExtensionUtils();
            certGen.addExtension(Extension.subjectKeyIdentifier, false, instance.createSubjectKeyIdentifier(subjectPublicKeyInfo));
            ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BOUNCY_CASTLE_PROVIDER).build(X509CertificateRule.this.signerKey.getPrivate());
            certificate = new JcaX509CertificateConverter().setProvider(BOUNCY_CASTLE_PROVIDER).getCertificate(certGen.build(signer));
            try {
                base.evaluate();
            } finally {
                certificate = null;
            }
        }
    };
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) Statement(org.junit.runners.model.Statement) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) ContentSigner(org.bouncycastle.operator.ContentSigner) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date)

Aggregations

X500Name (org.bouncycastle.asn1.x500.X500Name)510 X509Certificate (java.security.cert.X509Certificate)182 BigInteger (java.math.BigInteger)175 Date (java.util.Date)168 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)158 ContentSigner (org.bouncycastle.operator.ContentSigner)149 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)145 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)127 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)127 IOException (java.io.IOException)104 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)100 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)93 KeyPair (java.security.KeyPair)79 RDN (org.bouncycastle.asn1.x500.RDN)75 X500Name (sun.security.x509.X500Name)68 PrivateKey (java.security.PrivateKey)64 CertificateException (java.security.cert.CertificateException)64 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)55 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)55 SecureRandom (java.security.SecureRandom)54