Search in sources :

Example 51 with Extensions

use of org.bouncycastle.asn1.x509.Extensions in project keystore-explorer by kaikramer.

the class ExtensionsTableModel method load.

/**
 * Load the ExtensionsTableModel with X.509 extensions.
 *
 * @param extensions
 *            The X.509 extensions
 */
public void load(X509Extension extensions) {
    Set<String> critExts = extensions.getCriticalExtensionOIDs();
    Set<String> nonCritExts = extensions.getNonCriticalExtensionOIDs();
    // Rows will be sorted by extension name
    List<X509Ext> sortedExts = new ArrayList<X509Ext>();
    for (Iterator<String> itr = critExts.iterator(); itr.hasNext(); ) {
        String extOid = itr.next();
        byte[] value = extensions.getExtensionValue(extOid);
        X509Ext ext = new X509Ext(new ASN1ObjectIdentifier(extOid), value, true);
        sortedExts.add(ext);
    }
    for (Iterator<String> itr = nonCritExts.iterator(); itr.hasNext(); ) {
        String extOid = itr.next();
        byte[] value = extensions.getExtensionValue(extOid);
        X509Ext ext = new X509Ext(new ASN1ObjectIdentifier(extOid), value, false);
        sortedExts.add(ext);
    }
    Collections.sort(sortedExts, new ExtensionNameComparator());
    data = new Object[sortedExts.size()][3];
    int i = 0;
    for (Iterator<X509Ext> itrSortedExts = sortedExts.iterator(); itrSortedExts.hasNext(); ) {
        X509Ext ext = itrSortedExts.next();
        loadRow(ext, i);
        i++;
    }
    fireTableDataChanged();
}
Also used : ArrayList(java.util.ArrayList) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) X509Ext(org.kse.crypto.x509.X509Ext)

Example 52 with Extensions

use of org.bouncycastle.asn1.x509.Extensions in project keystore-explorer by kaikramer.

the class DGenerateKeyPairCert method addExtensionsPressed.

private void addExtensionsPressed() {
    PublicKey subjectPublicKey = keyPair.getPublic();
    PublicKey caPublicKey = null;
    X500Name caIssuerName = null;
    BigInteger caSerialNumber = null;
    if (issuerCert != null) {
        caIssuerName = X500NameUtils.x500PrincipalToX500Name(issuerCert.getIssuerX500Principal());
        caPublicKey = issuerCert.getPublicKey();
        caSerialNumber = issuerCert.getSerialNumber();
    } else {
        // May be null
        caIssuerName = jdnName.getDistinguishedName();
        caPublicKey = keyPair.getPublic();
        String serialNumberStr = jtfSerialNumber.getText().trim();
        if (serialNumberStr.length() != 0) {
            try {
                caSerialNumber = new BigInteger(serialNumberStr);
            } catch (NumberFormatException ex) {
            // Don't set serial number
            }
        }
    }
    DAddExtensions dAddExtensions = new DAddExtensions(this, extensions, caPublicKey, caIssuerName, caSerialNumber, subjectPublicKey);
    dAddExtensions.setLocationRelativeTo(this);
    dAddExtensions.setVisible(true);
    if (dAddExtensions.getExtensions() != null) {
        extensions = dAddExtensions.getExtensions();
    }
}
Also used : DAddExtensions(org.kse.gui.dialogs.extensions.DAddExtensions) PublicKey(java.security.PublicKey) BigInteger(java.math.BigInteger) X500Name(org.bouncycastle.asn1.x500.X500Name)

Example 53 with Extensions

use of org.bouncycastle.asn1.x509.Extensions in project keystore-explorer by kaikramer.

the class DGenerateKeyPairCert method generateCertificate.

private boolean generateCertificate() {
    Date validityStart = jdtValidityStart.getDateTime();
    Date validityEnd = jdtValidityEnd.getDateTime();
    String serialNumberStr = jtfSerialNumber.getText().trim();
    if (serialNumberStr.length() == 0) {
        JOptionPane.showMessageDialog(this, res.getString("DGenerateKeyPairCert.ValReqSerialNumber.message"), getTitle(), JOptionPane.WARNING_MESSAGE);
        return false;
    }
    BigInteger serialNumber;
    try {
        serialNumber = new BigInteger(serialNumberStr);
        if (serialNumber.compareTo(BigInteger.ONE) < 0) {
            JOptionPane.showMessageDialog(this, res.getString("DGenerateKeyPairCert.SerialNumberNonZero.message"), getTitle(), JOptionPane.WARNING_MESSAGE);
            return false;
        }
    } catch (NumberFormatException ex) {
        JOptionPane.showMessageDialog(this, res.getString("DGenerateKeyPairCert.SerialNumberNotInteger.message"), getTitle(), JOptionPane.WARNING_MESSAGE);
        return false;
    }
    X500Name x500Name = jdnName.getDistinguishedName();
    if (x500Name == null || x500Name.toString().isEmpty()) {
        JOptionPane.showMessageDialog(this, res.getString("DGenerateKeyPairCert.NameValueReq.message"), getTitle(), JOptionPane.WARNING_MESSAGE);
        return false;
    }
    try {
        SignatureType signatureType = ((SignatureType) jcbSignatureAlgorithm.getSelectedItem());
        X509CertificateGenerator generator;
        if (jrbVersion1.isSelected()) {
            generator = new X509CertificateGenerator(VERSION1);
        } else {
            generator = new X509CertificateGenerator(VERSION3);
        }
        // self-signed or signed by other key pair?
        if (issuerPrivateKey == null) {
            certificate = generator.generateSelfSigned(x500Name, validityStart, validityEnd, keyPair.getPublic(), keyPair.getPrivate(), signatureType, serialNumber, extensions, provider);
        } else {
            certificate = generator.generate(x500Name, X500NameUtils.x500PrincipalToX500Name(issuerCert.getSubjectX500Principal()), validityStart, validityEnd, keyPair.getPublic(), issuerPrivateKey, signatureType, serialNumber, extensions, provider);
        }
    } catch (CryptoException ex) {
        DError dError = new DError(this, ex);
        dError.setLocationRelativeTo(getParent());
        dError.setVisible(true);
        closeDialog();
    }
    return true;
}
Also used : BigInteger(java.math.BigInteger) X500Name(org.bouncycastle.asn1.x500.X500Name) SignatureType(org.kse.crypto.signing.SignatureType) CryptoException(org.kse.crypto.CryptoException) Date(java.util.Date) X509CertificateGenerator(org.kse.crypto.x509.X509CertificateGenerator) DError(org.kse.gui.error.DError)

Example 54 with Extensions

use of org.bouncycastle.asn1.x509.Extensions in project candlepin by candlepin.

the class X509CRLStreamWriter method write.

/**
 * Write a modified CRL to the given output stream.  This method will add each entry provided
 * via the add() method.
 *
 * @param out OutputStream to write to
 * @throws IOException if something goes wrong
 */
public void write(OutputStream out) throws IOException {
    if (!locked || !preScanned) {
        throw new IllegalStateException("The instance must be preScanned and locked before writing.");
    }
    if (emptyCrl) {
        /* An empty CRL is going to be missing the revokedCertificates sequence
             * and would require a lot of special casing during the streaming process.
             * Instead, it is easier to construct the CRL in the normal fashion using
             * BouncyCastle.  Performance should be acceptable as long as the number of
             * CRL entries being added are reasonable in number.  Something less than a
             * thousand or so should yield adequate performance.
             */
        writeToEmptyCrl(out);
        return;
    }
    originalLength = handleHeader(out);
    int tag;
    int tagNo;
    int length;
    while (originalLength > count.get()) {
        tag = readTag(crlIn, count);
        tagNo = readTagNumber(crlIn, tag, count);
        length = readLength(crlIn, count);
        byte[] entryBytes = new byte[length];
        readFullyAndTrack(crlIn, entryBytes, count);
        // We only need the serial number and not the rest of the stuff in the entry
        ASN1Integer serial = (ASN1Integer) new ASN1InputStream(entryBytes).readObject();
        if (deletedEntriesLength == 0 || !deletedEntries.contains(serial.getValue())) {
            writeTag(out, tag, tagNo, signer);
            writeLength(out, length, signer);
            writeValue(out, entryBytes, signer);
        }
    }
    // Write the new entries into the new CRL
    for (ASN1Sequence entry : newEntries) {
        writeBytes(out, entry.getEncoded(), signer);
    }
    // Copy the old extensions over
    if (newExtensions != null) {
        out.write(newExtensions);
        signer.getOutputStream().write(newExtensions, 0, newExtensions.length);
    }
    out.write(signingAlg.getEncoded());
    try {
        byte[] signature = signer.getSignature();
        ASN1BitString signatureBits = new DERBitString(signature);
        out.write(signatureBits.getEncoded());
    } catch (DataLengthException e) {
        throw new IOException("Could not sign", e);
    }
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DataLengthException(org.bouncycastle.crypto.DataLengthException) DERBitString(org.bouncycastle.asn1.DERBitString) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) IOException(java.io.IOException) ASN1BitString(org.bouncycastle.asn1.ASN1BitString)

Example 55 with Extensions

use of org.bouncycastle.asn1.x509.Extensions in project candlepin by candlepin.

the class BouncyCastlePKIUtility method createX509Certificate.

@Override
public X509Certificate createX509Certificate(String dn, Set<X509ExtensionWrapper> extensions, Set<X509ByteExtensionWrapper> byteExtensions, Date startDate, Date endDate, KeyPair clientKeyPair, BigInteger serialNumber, String alternateName) throws GeneralSecurityException, IOException {
    X509Certificate caCert = reader.getCACert();
    byte[] publicKeyEncoded = clientKeyPair.getPublic().getEncoded();
    X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(X500Name.getInstance(caCert.getSubjectX500Principal().getEncoded()), serialNumber, startDate, endDate, new X500Name(dn), SubjectPublicKeyInfo.getInstance(publicKeyEncoded));
    // set key usage - required for proper x509 function
    KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment);
    // add SSL extensions - required for proper x509 function
    NetscapeCertType certType = new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime);
    certGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false, certType);
    certGen.addExtension(Extension.keyUsage, false, keyUsage);
    JcaX509ExtensionUtils extensionUtil = new JcaX509ExtensionUtils();
    AuthorityKeyIdentifier aki = extensionUtil.createAuthorityKeyIdentifier(caCert);
    certGen.addExtension(Extension.authorityKeyIdentifier, false, aki.getEncoded());
    certGen.addExtension(Extension.subjectKeyIdentifier, false, subjectKeyWriter.getSubjectKeyIdentifier(clientKeyPair, extensions));
    certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
    // Add an additional alternative name if provided.
    if (alternateName != null) {
        /*
             Why add the certificate subject again as an alternative name?  RFC 6125 Section 6.4.4
             stipulates that if SANs are provided, a validator MUST use them instead of the certificate
             subject.  If no SANs are present, the RFC allows the validator to use the subject field.  So,
             if we do have an SAN to add, we need to add the subject field again as an SAN.

             See http://stackoverflow.com/questions/5935369 and
             https://tools.ietf.org/html/rfc6125#section-6.4.4 and

             NB: These extensions should *not* be marked critical since the subject field is not empty.
            */
        GeneralName subject = new GeneralName(GeneralName.directoryName, dn);
        GeneralName name = new GeneralName(GeneralName.directoryName, "CN=" + alternateName);
        ASN1Encodable[] altNameArray = { subject, name };
        GeneralNames altNames = GeneralNames.getInstance(new DERSequence(altNameArray));
        certGen.addExtension(Extension.subjectAlternativeName, false, altNames);
    }
    if (extensions != null) {
        for (X509ExtensionWrapper wrapper : extensions) {
            // Bouncycastle hates null values. So, set them to blank
            // if they are null
            String value = wrapper.getValue() == null ? "" : wrapper.getValue();
            certGen.addExtension(wrapper.toASN1Primitive(), wrapper.isCritical(), new DERUTF8String(value));
        }
    }
    if (byteExtensions != null) {
        for (X509ByteExtensionWrapper wrapper : byteExtensions) {
            // Bouncycastle hates null values. So, set them to blank
            // if they are null
            byte[] value = wrapper.getValue() == null ? new byte[0] : wrapper.getValue();
            certGen.addExtension(wrapper.toASN1Primitive(), wrapper.isCritical(), new DEROctetString(value));
        }
    }
    JcaContentSignerBuilder builder = new JcaContentSignerBuilder(SIGNATURE_ALGO).setProvider(BC_PROVIDER);
    ContentSigner signer;
    try {
        signer = builder.build(reader.getCaKey());
    } catch (OperatorCreationException e) {
        throw new IOException(e);
    }
    // Generate the certificate
    return new JcaX509CertificateConverter().getCertificate(certGen.build(signer));
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) X500Name(org.bouncycastle.asn1.x500.X500Name) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERSequence(org.bouncycastle.asn1.DERSequence) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) NetscapeCertType(org.bouncycastle.asn1.misc.NetscapeCertType) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509ByteExtensionWrapper(org.candlepin.pki.X509ByteExtensionWrapper) X509ExtensionWrapper(org.candlepin.pki.X509ExtensionWrapper) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage)

Aggregations

ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)67 Extensions (org.bouncycastle.asn1.x509.Extensions)62 Extension (org.bouncycastle.asn1.x509.Extension)58 IOException (java.io.IOException)45 DEROctetString (org.bouncycastle.asn1.DEROctetString)39 HashSet (java.util.HashSet)35 Enumeration (java.util.Enumeration)34 X500Name (org.bouncycastle.asn1.x500.X500Name)32 BigInteger (java.math.BigInteger)30 Date (java.util.Date)30 DERIA5String (org.bouncycastle.asn1.DERIA5String)26 X509Certificate (java.security.cert.X509Certificate)25 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)25 ContentSigner (org.bouncycastle.operator.ContentSigner)24 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)23 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)23 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)23 GeneralName (org.bouncycastle.asn1.x509.GeneralName)23 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)22 ArrayList (java.util.ArrayList)21