Search in sources :

Example 31 with ASN1Encodable

use of org.openecard.bouncycastle.asn1.ASN1Encodable in project xipki by xipki.

the class BaseX509Certprofile method checkPublicKey.

@Override
public SubjectPublicKeyInfo checkPublicKey(SubjectPublicKeyInfo publicKey) throws BadCertTemplateException {
    ParamUtil.requireNonNull("publicKey", publicKey);
    Map<ASN1ObjectIdentifier, KeyParametersOption> keyAlgorithms = getKeyAlgorithms();
    if (CollectionUtil.isEmpty(keyAlgorithms)) {
        return publicKey;
    }
    ASN1ObjectIdentifier keyType = publicKey.getAlgorithm().getAlgorithm();
    if (!keyAlgorithms.containsKey(keyType)) {
        throw new BadCertTemplateException("key type " + keyType.getId() + " is not permitted");
    }
    KeyParametersOption keyParamsOption = keyAlgorithms.get(keyType);
    if (keyParamsOption instanceof AllowAllParametersOption) {
        return publicKey;
    } else if (keyParamsOption instanceof ECParamatersOption) {
        ECParamatersOption ecOption = (ECParamatersOption) keyParamsOption;
        // parameters
        ASN1Encodable algParam = publicKey.getAlgorithm().getParameters();
        ASN1ObjectIdentifier curveOid;
        if (algParam instanceof ASN1ObjectIdentifier) {
            curveOid = (ASN1ObjectIdentifier) algParam;
            if (!ecOption.allowsCurve(curveOid)) {
                throw new BadCertTemplateException(String.format("EC curve %s (OID: %s) is not allowed", AlgorithmUtil.getCurveName(curveOid), curveOid.getId()));
            }
        } else {
            throw new BadCertTemplateException("only namedCurve EC public key is supported");
        }
        // point encoding
        if (ecOption.pointEncodings() != null) {
            byte[] keyData = publicKey.getPublicKeyData().getBytes();
            if (keyData.length < 1) {
                throw new BadCertTemplateException("invalid publicKeyData");
            }
            byte pointEncoding = keyData[0];
            if (!ecOption.pointEncodings().contains(pointEncoding)) {
                throw new BadCertTemplateException(String.format("not accepted EC point encoding '%s'", pointEncoding));
            }
        }
        byte[] keyData = publicKey.getPublicKeyData().getBytes();
        try {
            checkEcSubjectPublicKeyInfo(curveOid, keyData);
        } catch (BadCertTemplateException ex) {
            throw ex;
        } catch (Exception ex) {
            LogUtil.warn(LOG, ex, "checkEcSubjectPublicKeyInfo");
            throw new BadCertTemplateException(String.format("invalid public key: %s", ex.getMessage()));
        }
        return publicKey;
    } else if (keyParamsOption instanceof RSAParametersOption) {
        RSAParametersOption rsaOption = (RSAParametersOption) keyParamsOption;
        ASN1Integer modulus;
        try {
            ASN1Sequence seq = ASN1Sequence.getInstance(publicKey.getPublicKeyData().getBytes());
            modulus = ASN1Integer.getInstance(seq.getObjectAt(0));
        } catch (IllegalArgumentException ex) {
            throw new BadCertTemplateException("invalid publicKeyData");
        }
        int modulusLength = modulus.getPositiveValue().bitLength();
        if ((rsaOption.allowsModulusLength(modulusLength))) {
            return publicKey;
        }
    } else if (keyParamsOption instanceof DSAParametersOption) {
        DSAParametersOption dsaOption = (DSAParametersOption) keyParamsOption;
        ASN1Encodable params = publicKey.getAlgorithm().getParameters();
        if (params == null) {
            throw new BadCertTemplateException("null Dss-Parms is not permitted");
        }
        int plength;
        int qlength;
        try {
            ASN1Sequence seq = ASN1Sequence.getInstance(params);
            ASN1Integer rsaP = ASN1Integer.getInstance(seq.getObjectAt(0));
            ASN1Integer rsaQ = ASN1Integer.getInstance(seq.getObjectAt(1));
            plength = rsaP.getPositiveValue().bitLength();
            qlength = rsaQ.getPositiveValue().bitLength();
        } catch (IllegalArgumentException | ArrayIndexOutOfBoundsException ex) {
            throw new BadCertTemplateException("illegal Dss-Parms");
        }
        boolean match = dsaOption.allowsPlength(plength);
        if (match) {
            match = dsaOption.allowsQlength(qlength);
        }
        if (match) {
            return publicKey;
        }
    } else {
        throw new RuntimeException(String.format("should not reach here, unknown KeyParametersOption %s", keyParamsOption));
    }
    throw new BadCertTemplateException("the given publicKey is not permitted");
}
Also used : ECParamatersOption(org.xipki.ca.api.profile.KeyParametersOption.ECParamatersOption) DSAParametersOption(org.xipki.ca.api.profile.KeyParametersOption.DSAParametersOption) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) CertprofileException(org.xipki.ca.api.profile.CertprofileException) BadCertTemplateException(org.xipki.ca.api.BadCertTemplateException) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) KeyParametersOption(org.xipki.ca.api.profile.KeyParametersOption) RSAParametersOption(org.xipki.ca.api.profile.KeyParametersOption.RSAParametersOption) BadCertTemplateException(org.xipki.ca.api.BadCertTemplateException) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) AllowAllParametersOption(org.xipki.ca.api.profile.KeyParametersOption.AllowAllParametersOption) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 32 with ASN1Encodable

use of org.openecard.bouncycastle.asn1.ASN1Encodable in project xipki by xipki.

the class BaseX509Certprofile method getSubject.

@Override
public SubjectInfo getSubject(X500Name requestedSubject) throws CertprofileException, BadCertTemplateException {
    ParamUtil.requireNonNull("requestedSubject", requestedSubject);
    verifySubjectDnOccurence(requestedSubject);
    RDN[] requstedRdns = requestedSubject.getRDNs();
    SubjectControl scontrol = getSubjectControl();
    List<RDN> rdns = new LinkedList<>();
    for (ASN1ObjectIdentifier type : scontrol.getTypes()) {
        RdnControl control = scontrol.getControl(type);
        if (control == null) {
            continue;
        }
        RDN[] thisRdns = getRdns(requstedRdns, type);
        if (thisRdns == null) {
            continue;
        }
        int len = thisRdns.length;
        if (len == 0) {
            continue;
        }
        if (ObjectIdentifiers.DN_EmailAddress.equals(type)) {
            throw new BadCertTemplateException("emailAddress is not allowed");
        }
        if (len == 1) {
            ASN1Encodable rdnValue = thisRdns[0].getFirst().getValue();
            RDN rdn;
            if (ObjectIdentifiers.DN_DATE_OF_BIRTH.equals(type)) {
                rdn = createDateOfBirthRdn(type, rdnValue);
            } else if (ObjectIdentifiers.DN_POSTAL_ADDRESS.equals(type)) {
                rdn = createPostalAddressRdn(type, rdnValue, control, 0);
            } else {
                String value = X509Util.rdnValueToString(rdnValue);
                rdn = createSubjectRdn(value, type, control, 0);
            }
            if (rdn != null) {
                rdns.add(rdn);
            }
        } else {
            if (ObjectIdentifiers.DN_DATE_OF_BIRTH.equals(type)) {
                for (int i = 0; i < len; i++) {
                    RDN rdn = createDateOfBirthRdn(type, thisRdns[i].getFirst().getValue());
                    rdns.add(rdn);
                }
            } else if (ObjectIdentifiers.DN_POSTAL_ADDRESS.equals(type)) {
                for (int i = 0; i < len; i++) {
                    RDN rdn = createPostalAddressRdn(type, thisRdns[i].getFirst().getValue(), control, i);
                    rdns.add(rdn);
                }
            } else {
                String[] values = new String[len];
                for (int i = 0; i < len; i++) {
                    values[i] = X509Util.rdnValueToString(thisRdns[i].getFirst().getValue());
                }
                values = sortRdns(control, values);
                int idx = 0;
                for (String value : values) {
                    rdns.add(createSubjectRdn(value, type, control, idx++));
                }
            }
        // if
        }
    // if
    }
    // for
    Set<String> subjectDnGroups = scontrol.getGroups();
    if (CollectionUtil.isNonEmpty(subjectDnGroups)) {
        Set<String> consideredGroups = new HashSet<>();
        final int n = rdns.size();
        List<RDN> newRdns = new ArrayList<>(rdns.size());
        for (int i = 0; i < n; i++) {
            RDN rdn = rdns.get(i);
            ASN1ObjectIdentifier type = rdn.getFirst().getType();
            String group = scontrol.getGroup(type);
            if (group == null) {
                newRdns.add(rdn);
            } else if (!consideredGroups.contains(group)) {
                List<AttributeTypeAndValue> atvs = new LinkedList<>();
                atvs.add(rdn.getFirst());
                for (int j = i + 1; j < n; j++) {
                    RDN rdn2 = rdns.get(j);
                    ASN1ObjectIdentifier type2 = rdn2.getFirst().getType();
                    String group2 = scontrol.getGroup(type2);
                    if (group.equals(group2)) {
                        atvs.add(rdn2.getFirst());
                    }
                }
                newRdns.add(new RDN(atvs.toArray(new AttributeTypeAndValue[0])));
                consideredGroups.add(group);
            }
        }
        // for
        rdns = newRdns;
    }
    // if
    X500Name grantedSubject = new X500Name(rdns.toArray(new RDN[0]));
    return new SubjectInfo(grantedSubject, null);
}
Also used : ArrayList(java.util.ArrayList) ASN1String(org.bouncycastle.asn1.ASN1String) DERUniversalString(org.bouncycastle.asn1.DERUniversalString) X500Name(org.bouncycastle.asn1.x500.X500Name) LinkedList(java.util.LinkedList) AttributeTypeAndValue(org.bouncycastle.asn1.x500.AttributeTypeAndValue) RdnControl(org.xipki.ca.api.profile.RdnControl) BadCertTemplateException(org.xipki.ca.api.BadCertTemplateException) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) RDN(org.bouncycastle.asn1.x500.RDN) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) HashSet(java.util.HashSet)

Example 33 with ASN1Encodable

use of org.openecard.bouncycastle.asn1.ASN1Encodable in project xipki by xipki.

the class AlgorithmUtil method extractDigesetAlgFromSigAlg.

public static AlgorithmIdentifier extractDigesetAlgFromSigAlg(AlgorithmIdentifier sigAlgId) throws NoSuchAlgorithmException {
    ASN1ObjectIdentifier algOid = sigAlgId.getAlgorithm();
    ASN1ObjectIdentifier digestAlgOid;
    if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(algOid)) {
        ASN1Encodable asn1Encodable = sigAlgId.getParameters();
        RSASSAPSSparams param = RSASSAPSSparams.getInstance(asn1Encodable);
        digestAlgOid = param.getHashAlgorithm().getAlgorithm();
    } else {
        HashAlgo digestAlg = sigAlgOidToDigestMap.get(algOid);
        if (digestAlg == null) {
            throw new NoSuchAlgorithmException("unknown signature algorithm " + algOid.getId());
        }
        digestAlgOid = digestAlg.getOid();
    }
    return new AlgorithmIdentifier(digestAlgOid, DERNull.INSTANCE);
}
Also used : HashAlgo(org.xipki.security.HashAlgo) RSASSAPSSparams(org.bouncycastle.asn1.pkcs.RSASSAPSSparams) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 34 with ASN1Encodable

use of org.openecard.bouncycastle.asn1.ASN1Encodable in project xipki by xipki.

the class KeyUtil method createECPublicKey.

// CHECKSTYLE:SKIP
public static ECPublicKey createECPublicKey(byte[] encodedAlgorithmIdParameters, byte[] encodedPoint) throws InvalidKeySpecException {
    ParamUtil.requireNonNull("encodedAlgorithmIdParameters", encodedAlgorithmIdParameters);
    ParamUtil.requireNonNull("encodedPoint", encodedPoint);
    ASN1Encodable algParams;
    if (encodedAlgorithmIdParameters[0] == 6) {
        algParams = ASN1ObjectIdentifier.getInstance(encodedAlgorithmIdParameters);
    } else {
        algParams = X962Parameters.getInstance(encodedAlgorithmIdParameters);
    }
    AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, algParams);
    SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(algId, encodedPoint);
    X509EncodedKeySpec keySpec;
    try {
        keySpec = new X509EncodedKeySpec(spki.getEncoded());
    } catch (IOException ex) {
        throw new InvalidKeySpecException(ex.getMessage(), ex);
    }
    KeyFactory kf;
    try {
        kf = KeyFactory.getInstance("EC", "BC");
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
        throw new InvalidKeySpecException(ex.getMessage(), ex);
    }
    return (ECPublicKey) kf.generatePublic(keySpec);
}
Also used : ECPublicKey(java.security.interfaces.ECPublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) IOException(java.io.IOException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) KeyFactory(java.security.KeyFactory) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 35 with ASN1Encodable

use of org.openecard.bouncycastle.asn1.ASN1Encodable in project xipki by xipki.

the class ImportCrl method importEntries.

private void importEntries(Connection conn, int caId) throws DataAccessException, ImportCrlException {
    AtomicLong maxId = new AtomicLong(datasource.getMax(conn, "CERT", "ID"));
    // import the revoked information
    Set<? extends X509CRLEntry> revokedCertList = crl.getRevokedCertificates();
    if (revokedCertList != null) {
        for (X509CRLEntry c : revokedCertList) {
            X500Principal issuer = c.getCertificateIssuer();
            BigInteger serial = c.getSerialNumber();
            if (issuer != null) {
                if (!x500PrincipalCaSubject.equals(issuer)) {
                    throw new ImportCrlException("invalid CRLEntry for certificate number " + serial);
                }
            }
            Date rt = c.getRevocationDate();
            Date rit = null;
            byte[] extnValue = c.getExtensionValue(Extension.invalidityDate.getId());
            if (extnValue != null) {
                extnValue = extractCoreValue(extnValue);
                ASN1GeneralizedTime genTime = DERGeneralizedTime.getInstance(extnValue);
                try {
                    rit = genTime.getDate();
                } catch (ParseException ex) {
                    throw new ImportCrlException(ex.getMessage(), ex);
                }
                if (rt.equals(rit)) {
                    rit = null;
                }
            }
            CrlReason reason = CrlReason.fromReason(c.getRevocationReason());
            String sql = null;
            try {
                if (reason == CrlReason.REMOVE_FROM_CRL) {
                    if (!isDeltaCrl) {
                        LOG.warn("ignore CRL entry with reason removeFromCRL in non-Delta CRL");
                    }
                    // delete the entry
                    sql = SQL_DELETE_CERT;
                    psDeleteCert.setInt(1, caId);
                    psDeleteCert.setString(2, serial.toString(16));
                    psDeleteCert.executeUpdate();
                    continue;
                }
                Long id = getId(caId, serial);
                PreparedStatement ps;
                int offset = 1;
                if (id == null) {
                    sql = SQL_INSERT_CERT_REV;
                    id = maxId.incrementAndGet();
                    ps = psInsertCertRev;
                    ps.setLong(offset++, id);
                    ps.setInt(offset++, caId);
                    ps.setString(offset++, serial.toString(16));
                } else {
                    sql = SQL_UPDATE_CERT_REV;
                    ps = psUpdateCertRev;
                }
                ps.setInt(offset++, 1);
                ps.setInt(offset++, reason.getCode());
                ps.setLong(offset++, rt.getTime() / 1000);
                if (rit != null) {
                    ps.setLong(offset++, rit.getTime() / 1000);
                } else {
                    ps.setNull(offset++, Types.BIGINT);
                }
                ps.setLong(offset++, System.currentTimeMillis() / 1000);
                if (ps == psUpdateCertRev) {
                    ps.setLong(offset++, id);
                }
                ps.executeUpdate();
            } catch (SQLException ex) {
                throw datasource.translate(sql, ex);
            }
        }
    }
    // import the certificates
    // extract the certificate
    byte[] extnValue = crl.getExtensionValue(ObjectIdentifiers.id_xipki_ext_crlCertset.getId());
    if (extnValue != null) {
        extnValue = extractCoreValue(extnValue);
        ASN1Set asn1Set = DERSet.getInstance(extnValue);
        final int n = asn1Set.size();
        for (int i = 0; i < n; i++) {
            ASN1Encodable asn1 = asn1Set.getObjectAt(i);
            ASN1Sequence seq = ASN1Sequence.getInstance(asn1);
            BigInteger serialNumber = ASN1Integer.getInstance(seq.getObjectAt(0)).getValue();
            Certificate cert = null;
            String profileName = null;
            final int size = seq.size();
            for (int j = 1; j < size; j++) {
                ASN1TaggedObject taggedObj = DERTaggedObject.getInstance(seq.getObjectAt(j));
                int tagNo = taggedObj.getTagNo();
                switch(tagNo) {
                    case 0:
                        cert = Certificate.getInstance(taggedObj.getObject());
                        break;
                    case 1:
                        profileName = DERUTF8String.getInstance(taggedObj.getObject()).getString();
                        break;
                    default:
                        break;
                }
            }
            if (cert == null) {
                continue;
            }
            if (!caSubject.equals(cert.getIssuer())) {
                LOG.warn("issuer not match (serial={}) in CRL Extension Xipki-CertSet, ignore it", LogUtil.formatCsn(serialNumber));
                continue;
            }
            if (!serialNumber.equals(cert.getSerialNumber().getValue())) {
                LOG.warn("serialNumber not match (serial={}) in CRL Extension Xipki-CertSet, ignore it", LogUtil.formatCsn(serialNumber));
                continue;
            }
            String certLogId = "(issuer='" + cert.getIssuer() + "', serialNumber=" + cert.getSerialNumber() + ")";
            addCertificate(maxId, caId, cert, profileName, certLogId);
        }
    } else {
        // cert dirs
        File certsDir = new File(certsDirName);
        if (!certsDir.exists()) {
            LOG.warn("the folder {} does not exist, ignore it", certsDirName);
            return;
        }
        if (!certsDir.isDirectory()) {
            LOG.warn("the path {} does not point to a folder, ignore it", certsDirName);
            return;
        }
        if (!certsDir.canRead()) {
            LOG.warn("the folder {} must not be read, ignore it", certsDirName);
            return;
        }
        File[] certFiles = certsDir.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".der") || name.endsWith(".crt");
            }
        });
        if (certFiles == null || certFiles.length == 0) {
            return;
        }
        for (File certFile : certFiles) {
            Certificate cert;
            try {
                byte[] encoded = IoUtil.read(certFile);
                cert = Certificate.getInstance(encoded);
            } catch (IllegalArgumentException | IOException ex) {
                LOG.warn("could not parse certificate {}, ignore it", certFile.getPath());
                continue;
            }
            String certLogId = "(file " + certFile.getName() + ")";
            addCertificate(maxId, caId, cert, null, certLogId);
        }
    }
}
Also used : SQLException(java.sql.SQLException) ASN1TaggedObject(org.bouncycastle.asn1.ASN1TaggedObject) ASN1GeneralizedTime(org.bouncycastle.asn1.ASN1GeneralizedTime) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) FilenameFilter(java.io.FilenameFilter) X509CRLEntry(java.security.cert.X509CRLEntry) CrlReason(org.xipki.security.CrlReason) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException) Date(java.util.Date) AtomicLong(java.util.concurrent.atomic.AtomicLong) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ASN1Set(org.bouncycastle.asn1.ASN1Set) AtomicLong(java.util.concurrent.atomic.AtomicLong) X500Principal(javax.security.auth.x500.X500Principal) BigInteger(java.math.BigInteger) ParseException(java.text.ParseException) File(java.io.File) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate)

Aggregations

ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)129 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)71 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)56 IOException (java.io.IOException)32 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)31 DEROctetString (org.bouncycastle.asn1.DEROctetString)29 DERIA5String (org.bouncycastle.asn1.DERIA5String)25 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)23 DERSequence (org.bouncycastle.asn1.DERSequence)22 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)21 DERPrintableString (org.bouncycastle.asn1.DERPrintableString)21 ArrayList (java.util.ArrayList)20 GeneralName (org.bouncycastle.asn1.x509.GeneralName)19 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)17 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)17 X509Certificate (java.security.cert.X509Certificate)15 HashSet (java.util.HashSet)15 ASN1Primitive (org.bouncycastle.asn1.ASN1Primitive)15 DirectoryString (org.bouncycastle.asn1.x500.DirectoryString)15 DERBMPString (org.bouncycastle.asn1.DERBMPString)14