Search in sources :

Example 51 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project xipki by xipki.

the class X509Ca method createGrantedCertTemplate.

private GrantedCertTemplate createGrantedCertTemplate(CertTemplateData certTemplate, RequestorInfo requestor, boolean keyUpdate) throws OperationException {
    ParamUtil.requireNonNull("certTemplate", certTemplate);
    if (caInfo.getRevocationInfo() != null) {
        throw new OperationException(ErrorCode.NOT_PERMITTED, "CA is revoked");
    }
    IdentifiedX509Certprofile certprofile = getX509Certprofile(certTemplate.getCertprofileName());
    if (certprofile == null) {
        throw new OperationException(ErrorCode.UNKNOWN_CERT_PROFILE, "unknown cert profile " + certTemplate.getCertprofileName());
    }
    ConcurrentContentSigner signer = caInfo.getSigner(certprofile.getSignatureAlgorithms());
    if (signer == null) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, "CA does not support any signature algorithm restricted by the cert profile");
    }
    final NameId certprofileIdent = certprofile.getIdent();
    if (certprofile.getVersion() != X509CertVersion.v3) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, "unknown cert version " + certprofile.getVersion());
    }
    if (certprofile.isOnlyForRa()) {
        if (requestor == null || !requestor.isRa()) {
            throw new OperationException(ErrorCode.NOT_PERMITTED, "profile " + certprofileIdent + " not applied to non-RA");
        }
    }
    X500Name requestedSubject = removeEmptyRdns(certTemplate.getSubject());
    if (!certprofile.isSerialNumberInReqPermitted()) {
        RDN[] rdns = requestedSubject.getRDNs(ObjectIdentifiers.DN_SN);
        if (rdns != null && rdns.length > 0) {
            throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "subjectDN SerialNumber in request is not permitted");
        }
    }
    Date now = new Date();
    Date reqNotBefore;
    if (certTemplate.getNotBefore() != null && certTemplate.getNotBefore().after(now)) {
        reqNotBefore = certTemplate.getNotBefore();
    } else {
        reqNotBefore = now;
    }
    Date grantedNotBefore = certprofile.getNotBefore(reqNotBefore);
    // notBefore in the past is not permitted
    if (grantedNotBefore.before(now)) {
        grantedNotBefore = now;
    }
    if (certprofile.hasMidnightNotBefore()) {
        grantedNotBefore = setToMidnight(grantedNotBefore, certprofile.getTimezone());
    }
    if (grantedNotBefore.before(caInfo.getNotBefore())) {
        grantedNotBefore = caInfo.getNotBefore();
        if (certprofile.hasMidnightNotBefore()) {
            grantedNotBefore = setToMidnight(grantedNotBefore, certprofile.getTimezone());
        }
    }
    long time = caInfo.getNoNewCertificateAfter();
    if (grantedNotBefore.getTime() > time) {
        throw new OperationException(ErrorCode.NOT_PERMITTED, "CA is not permitted to issue certifate after " + new Date(time));
    }
    SubjectPublicKeyInfo grantedPublicKeyInfo;
    try {
        grantedPublicKeyInfo = X509Util.toRfc3279Style(certTemplate.getPublicKeyInfo());
    } catch (InvalidKeySpecException ex) {
        LogUtil.warn(LOG, ex, "invalid SubjectPublicKeyInfo");
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "invalid SubjectPublicKeyInfo");
    }
    // public key
    try {
        grantedPublicKeyInfo = certprofile.checkPublicKey(grantedPublicKeyInfo);
    } catch (BadCertTemplateException ex) {
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
    }
    // CHECK weak public key, like RSA key (ROCA)
    if (grantedPublicKeyInfo.getAlgorithm().getAlgorithm().equals(PKCSObjectIdentifiers.rsaEncryption)) {
        try {
            ASN1Sequence seq = ASN1Sequence.getInstance(grantedPublicKeyInfo.getPublicKeyData().getOctets());
            if (seq.size() != 2) {
                throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "invalid format of RSA public key");
            }
            BigInteger modulus = ASN1Integer.getInstance(seq.getObjectAt(0)).getPositiveValue();
            if (RSABrokenKey.isAffected(modulus)) {
                throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "RSA public key is too weak");
            }
        } catch (IllegalArgumentException ex) {
            throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "invalid format of RSA public key");
        }
    }
    Date gsmckFirstNotBefore = null;
    if (certprofile.getspecialCertprofileBehavior() == SpecialX509CertprofileBehavior.gematik_gSMC_K) {
        gsmckFirstNotBefore = grantedNotBefore;
        RDN[] cnRdns = requestedSubject.getRDNs(ObjectIdentifiers.DN_CN);
        if (cnRdns != null && cnRdns.length > 0) {
            String requestedCn = X509Util.rdnValueToString(cnRdns[0].getFirst().getValue());
            Long gsmckFirstNotBeforeInSecond = certstore.getNotBeforeOfFirstCertStartsWithCommonName(requestedCn, certprofileIdent);
            if (gsmckFirstNotBeforeInSecond != null) {
                gsmckFirstNotBefore = new Date(gsmckFirstNotBeforeInSecond * MS_PER_SECOND);
            }
            // append the commonName with '-' + yyyyMMdd
            SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMdd");
            dateF.setTimeZone(new SimpleTimeZone(0, "Z"));
            String yyyyMMdd = dateF.format(gsmckFirstNotBefore);
            String suffix = "-" + yyyyMMdd;
            // append the -yyyyMMdd to the commonName
            RDN[] rdns = requestedSubject.getRDNs();
            for (int i = 0; i < rdns.length; i++) {
                if (ObjectIdentifiers.DN_CN.equals(rdns[i].getFirst().getType())) {
                    rdns[i] = new RDN(ObjectIdentifiers.DN_CN, new DERUTF8String(requestedCn + suffix));
                }
            }
            requestedSubject = new X500Name(rdns);
        }
    // end if
    }
    // end if
    // subject
    SubjectInfo subjectInfo;
    try {
        subjectInfo = certprofile.getSubject(requestedSubject);
    } catch (CertprofileException ex) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, "exception in cert profile " + certprofileIdent);
    } catch (BadCertTemplateException ex) {
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
    }
    X500Name grantedSubject = subjectInfo.getGrantedSubject();
    // make sure that empty subject is not permitted
    ASN1ObjectIdentifier[] attrTypes = grantedSubject.getAttributeTypes();
    if (attrTypes == null || attrTypes.length == 0) {
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "empty subject is not permitted");
    }
    // make sure that the grantedSubject does not equal the CA's subject
    if (X509Util.canonicalizName(grantedSubject).equals(caInfo.getPublicCaInfo().getC14nSubject())) {
        throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate with the same subject as CA is not allowed");
    }
    boolean duplicateKeyPermitted = caInfo.isDuplicateKeyPermitted();
    if (duplicateKeyPermitted && !certprofile.isDuplicateKeyPermitted()) {
        duplicateKeyPermitted = false;
    }
    byte[] subjectPublicKeyData = grantedPublicKeyInfo.getPublicKeyData().getBytes();
    long fpPublicKey = FpIdCalculator.hash(subjectPublicKeyData);
    if (keyUpdate) {
        CertStatus certStatus = certstore.getCertStatusForSubject(caIdent, grantedSubject);
        if (certStatus == CertStatus.REVOKED) {
            throw new OperationException(ErrorCode.CERT_REVOKED);
        } else if (certStatus == CertStatus.UNKNOWN) {
            throw new OperationException(ErrorCode.UNKNOWN_CERT);
        }
    } else {
        if (!duplicateKeyPermitted) {
            if (certstore.isCertForKeyIssued(caIdent, fpPublicKey)) {
                throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate for the given public key already issued");
            }
        }
    // duplicateSubject check will be processed later
    }
    // end if(keyUpdate)
    StringBuilder msgBuilder = new StringBuilder();
    if (subjectInfo.getWarning() != null) {
        msgBuilder.append(", ").append(subjectInfo.getWarning());
    }
    CertValidity validity = certprofile.getValidity();
    if (validity == null) {
        validity = caInfo.getMaxValidity();
    } else if (validity.compareTo(caInfo.getMaxValidity()) > 0) {
        validity = caInfo.getMaxValidity();
    }
    Date maxNotAfter = validity.add(grantedNotBefore);
    if (maxNotAfter.getTime() > MAX_CERT_TIME_MS) {
        maxNotAfter = new Date(MAX_CERT_TIME_MS);
    }
    // CHECKSTYLE:SKIP
    Date origMaxNotAfter = maxNotAfter;
    if (certprofile.getspecialCertprofileBehavior() == SpecialX509CertprofileBehavior.gematik_gSMC_K) {
        String str = certprofile.setParameter(SpecialX509CertprofileBehavior.PARAMETER_MAXLIFTIME);
        long maxLifetimeInDays = Long.parseLong(str);
        Date maxLifetime = new Date(gsmckFirstNotBefore.getTime() + maxLifetimeInDays * DAY_IN_MS - MS_PER_SECOND);
        if (maxNotAfter.after(maxLifetime)) {
            maxNotAfter = maxLifetime;
        }
    }
    Date grantedNotAfter = certTemplate.getNotAfter();
    if (grantedNotAfter != null) {
        if (grantedNotAfter.after(maxNotAfter)) {
            grantedNotAfter = maxNotAfter;
            msgBuilder.append(", notAfter modified");
        }
    } else {
        grantedNotAfter = maxNotAfter;
    }
    if (grantedNotAfter.after(caInfo.getNotAfter())) {
        ValidityMode mode = caInfo.getValidityMode();
        if (mode == ValidityMode.CUTOFF) {
            grantedNotAfter = caInfo.getNotAfter();
        } else if (mode == ValidityMode.STRICT) {
            throw new OperationException(ErrorCode.NOT_PERMITTED, "notAfter outside of CA's validity is not permitted");
        } else if (mode == ValidityMode.LAX) {
        // permitted
        } else {
            throw new RuntimeException("should not reach here, unknown CA ValidityMode " + mode);
        }
    // end if (mode)
    }
    if (certprofile.hasMidnightNotBefore() && !maxNotAfter.equals(origMaxNotAfter)) {
        Calendar cal = Calendar.getInstance(certprofile.getTimezone());
        cal.setTime(new Date(grantedNotAfter.getTime() - DAY_IN_MS));
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 0);
        grantedNotAfter = cal.getTime();
    }
    String warning = null;
    if (msgBuilder.length() > 2) {
        warning = msgBuilder.substring(2);
    }
    GrantedCertTemplate gct = new GrantedCertTemplate(certTemplate.getExtensions(), certprofile, grantedNotBefore, grantedNotAfter, requestedSubject, grantedPublicKeyInfo, fpPublicKey, subjectPublicKeyData, signer, warning);
    gct.setGrantedSubject(grantedSubject);
    return gct;
}
Also used : DERUTF8String(org.bouncycastle.asn1.DERUTF8String) NameId(org.xipki.ca.api.NameId) CertValidity(org.xipki.ca.api.profile.CertValidity) X500Name(org.bouncycastle.asn1.x500.X500Name) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) ValidityMode(org.xipki.ca.server.mgmt.api.ValidityMode) SimpleTimeZone(java.util.SimpleTimeZone) CertprofileException(org.xipki.ca.api.profile.CertprofileException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) RDN(org.bouncycastle.asn1.x500.RDN) OperationException(org.xipki.ca.api.OperationException) Calendar(java.util.Calendar) SubjectInfo(org.xipki.ca.api.profile.x509.SubjectInfo) Date(java.util.Date) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) ConcurrentContentSigner(org.xipki.security.ConcurrentContentSigner) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) BadCertTemplateException(org.xipki.ca.api.BadCertTemplateException) BigInteger(java.math.BigInteger) SimpleDateFormat(java.text.SimpleDateFormat) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 52 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project xipki by xipki.

the class X509Ca method generateCertificate0.

private X509CertificateInfo generateCertificate0(GrantedCertTemplate gct, RequestorInfo requestor, boolean keyUpdate, RequestType reqType, byte[] transactionId, AuditEvent event) throws OperationException {
    ParamUtil.requireNonNull("gct", gct);
    event.addEventData(CaAuditConstants.NAME_reqSubject, X509Util.getRfc4519Name(gct.requestedSubject));
    event.addEventData(CaAuditConstants.NAME_certprofile, gct.certprofile.getIdent().getName());
    event.addEventData(CaAuditConstants.NAME_notBefore, DateUtil.toUtcTimeyyyyMMddhhmmss(gct.grantedNotBefore));
    event.addEventData(CaAuditConstants.NAME_notAfter, DateUtil.toUtcTimeyyyyMMddhhmmss(gct.grantedNotAfter));
    adaptGrantedSubejct(gct);
    IdentifiedX509Certprofile certprofile = gct.certprofile;
    boolean publicKeyCertInProcessExisted = publicKeyCertsInProcess.add(gct.fpPublicKey);
    if (!publicKeyCertInProcessExisted) {
        if (!certprofile.isDuplicateKeyPermitted()) {
            throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate with the given public key already in process");
        }
    }
    if (!subjectCertsInProcess.add(gct.fpSubject)) {
        if (!certprofile.isDuplicateSubjectPermitted()) {
            if (!publicKeyCertInProcessExisted) {
                publicKeyCertsInProcess.remove(gct.fpPublicKey);
            }
            throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate with the given subject " + gct.grantedSubjectText + " already in process");
        }
    }
    try {
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(caInfo.getPublicCaInfo().getX500Subject(), caInfo.nextSerial(), gct.grantedNotBefore, gct.grantedNotAfter, gct.grantedSubject, gct.grantedPublicKey);
        X509CertificateInfo ret;
        try {
            X509CrlSignerEntryWrapper crlSigner = getCrlSigner();
            X509Certificate crlSignerCert = (crlSigner == null) ? null : crlSigner.getCert();
            ExtensionValues extensionTuples = certprofile.getExtensions(gct.requestedSubject, gct.grantedSubject, gct.extensions, gct.grantedPublicKey, caInfo.getPublicCaInfo(), crlSignerCert, gct.grantedNotBefore, gct.grantedNotAfter);
            if (extensionTuples != null) {
                for (ASN1ObjectIdentifier extensionType : extensionTuples.getExtensionTypes()) {
                    ExtensionValue extValue = extensionTuples.getExtensionValue(extensionType);
                    certBuilder.addExtension(extensionType, extValue.isCritical(), extValue.getValue());
                }
            }
            ConcurrentBagEntrySigner signer0;
            try {
                signer0 = gct.signer.borrowSigner();
            } catch (NoIdleSignerException ex) {
                throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
            }
            X509CertificateHolder certHolder;
            try {
                certHolder = certBuilder.build(signer0.value());
            } finally {
                gct.signer.requiteSigner(signer0);
            }
            Certificate bcCert = certHolder.toASN1Structure();
            byte[] encodedCert = bcCert.getEncoded();
            int maxCertSize = gct.certprofile.getMaxCertSize();
            if (maxCertSize > 0) {
                int certSize = encodedCert.length;
                if (certSize > maxCertSize) {
                    throw new OperationException(ErrorCode.NOT_PERMITTED, String.format("certificate exceeds the maximal allowed size: %d > %d", certSize, maxCertSize));
                }
            }
            X509Certificate cert;
            try {
                cert = X509Util.toX509Cert(bcCert);
            } catch (CertificateException ex) {
                String message = "should not happen, could not parse generated certificate";
                LOG.error(message, ex);
                throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
            }
            if (!verifySignature(cert)) {
                throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not verify the signature of generated certificate");
            }
            X509CertWithDbId certWithMeta = new X509CertWithDbId(cert, encodedCert);
            ret = new X509CertificateInfo(certWithMeta, caIdent, caCert, gct.grantedPublicKeyData, gct.certprofile.getIdent(), requestor.getIdent());
            if (requestor instanceof ByUserRequestorInfo) {
                ret.setUser((((ByUserRequestorInfo) requestor).getUserId()));
            }
            ret.setReqType(reqType);
            ret.setTransactionId(transactionId);
            ret.setRequestedSubject(gct.requestedSubject);
            if (publishCertificate0(ret) == 1) {
                throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not save certificate");
            }
        } catch (BadCertTemplateException ex) {
            throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
        } catch (OperationException ex) {
            throw ex;
        } catch (Throwable th) {
            LogUtil.error(LOG, th, "could not generate certificate");
            throw new OperationException(ErrorCode.SYSTEM_FAILURE, th);
        }
        if (gct.warning != null) {
            ret.setWarningMessage(gct.warning);
        }
        return ret;
    } finally {
        publicKeyCertsInProcess.remove(gct.fpPublicKey);
        subjectCertsInProcess.remove(gct.fpSubject);
    }
}
Also used : X509CertificateInfo(org.xipki.ca.api.publisher.x509.X509CertificateInfo) CertificateException(java.security.cert.CertificateException) X509CertWithDbId(org.xipki.ca.api.X509CertWithDbId) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) ConcurrentBagEntrySigner(org.xipki.security.ConcurrentBagEntrySigner) X509Certificate(java.security.cert.X509Certificate) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) ExtensionValue(org.xipki.ca.api.profile.ExtensionValue) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) NoIdleSignerException(org.xipki.security.exception.NoIdleSignerException) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BadCertTemplateException(org.xipki.ca.api.BadCertTemplateException) ExtensionValues(org.xipki.ca.api.profile.ExtensionValues) OperationException(org.xipki.ca.api.OperationException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) Certificate(org.bouncycastle.asn1.x509.Certificate) X509Certificate(java.security.cert.X509Certificate)

Example 53 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project spring-cloud-digital-sign by SpringForAll.

the class ServerPKCSUtil method genCsr.

/**
 * genCsr
 *
 * @param alg0 alg
 * 密钥算法
 * @return
 */
public static String genCsr(String alg0) {
    if ("".equals(alg0)) {
        alg = alg0;
    }
    // 产生秘钥对
    KeyPairGenerator kpg = null;
    try {
        kpg = KeyPairGenerator.getInstance(alg);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    // 根据秘钥算法配置秘钥长度
    if ("SM2".equalsIgnoreCase(alg)) {
        kpg.initialize(256);
    } else {
        kpg.initialize(2048);
    }
    KeyPair kp = kpg.generateKeyPair();
    securityKP = kp;
    // 获取公钥以及公钥算法
    byte[] publickey = kp.getPublic().getEncoded();
    String pubAlg = kp.getPublic().getAlgorithm();
    String sAlg = null;
    try {
        sAlg = AlgorithmId.get(pubAlg).getOID().toString();
    } catch (NoSuchAlgorithmException e) {
    }
    SubjectPublicKeyInfo spki = null;
    // 区分SM2和RSA
    if (sAlg.equals("1.2.156.10197.1.301")) {
        spki = SubjectPublicKeyInfo.getInstance(publickey);
    } else {
        spki = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publickey));
    }
    String subject = "CN=defaultName";
    X500Name x500 = new X500Name(subject);
    // 产生csr构造器
    PKCS10CertificationRequestBuilder prb = new PKCS10CertificationRequestBuilder(x500, spki);
    // 构建签名信息
    ContentSigner signer = null;
    PrivateKey privateKey = kp.getPrivate();
    Signature sign = null;
    try {
        if (privateKey.getAlgorithm().equals("SM2")) {
            sign = Signature.getInstance("SM3withSM2");
        } else {
            sign = Signature.getInstance("SHA1withRSA");
        }
        sign.initSign(privateKey);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    final Signature sign1 = sign;
    signer = new ContentSigner() {

        ByteArrayOutputStream originStream = new ByteArrayOutputStream();

        public byte[] getSignature() {
            try {
                sign1.update(originStream.toByteArray());
                return sign1.sign();
            } catch (SignatureException e) {
                throw new RuntimeException(e);
            }
        }

        public OutputStream getOutputStream() {
            return originStream;
        }

        public AlgorithmIdentifier getAlgorithmIdentifier() {
            try {
                return new AlgorithmIdentifier(AlgorithmId.get(sign1.getAlgorithm()).getOID().toString());
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            }
        }
    };
    PKCS10CertificationRequestHolder pr = prb.build(signer);
    try {
        return new String(Base64.encode(pr.getEncoded()));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ContentSigner(org.bouncycastle.operator.ContentSigner) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) KeyPairGenerator(java.security.KeyPairGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X500Name(org.bouncycastle.asn1.x500.X500Name) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SignatureException(java.security.SignatureException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) PKCS10CertificationRequestHolder(org.bouncycastle.pkcs.PKCS10CertificationRequestHolder) Signature(java.security.Signature)

Example 54 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project webcert by sklintyg.

the class ASN1UtilImpl method getValue.

@Override
public String getValue(String identifier, InputStream asn1Signature) {
    ByteArrayInputStream bais = null;
    ASN1InputStream asn1InputStream = null;
    try {
        bais = convertStream(asn1Signature);
        asn1InputStream = new ASN1InputStream(bais);
        DERObject obj = asn1InputStream.readObject();
        ContentInfo contentInfo = ContentInfo.getInstance(obj);
        // Extract certificates
        SignedData signedData = SignedData.getInstance(contentInfo.getContent());
        return findInCertificate(identifier, (DERObject) signedData.getCertificates().getObjectAt(0));
    } catch (IOException e) {
        LOG.error("Error parsing signature: {}", e.getMessage());
        throw new IllegalStateException(e);
    } finally {
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(asn1InputStream);
    }
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) DERObject(org.bouncycastle.asn1.DERObject) SignedData(org.bouncycastle.asn1.pkcs.SignedData) ByteArrayInputStream(java.io.ByteArrayInputStream) ContentInfo(org.bouncycastle.asn1.pkcs.ContentInfo) IOException(java.io.IOException)

Example 55 with Signature

use of org.bouncycastle.asn1.ocsp.Signature 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)

Aggregations

IOException (java.io.IOException)58 DERIA5String (org.bouncycastle.asn1.DERIA5String)36 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)31 DERBitString (org.bouncycastle.asn1.DERBitString)31 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)30 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)30 InvalidKeyException (java.security.InvalidKeyException)28 X509Certificate (java.security.cert.X509Certificate)28 SignatureException (java.security.SignatureException)27 DERSequence (org.bouncycastle.asn1.DERSequence)26 PublicKey (java.security.PublicKey)25 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)23 DEROctetString (org.bouncycastle.asn1.DEROctetString)22 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)22 Signature (java.security.Signature)21 CertificateException (java.security.cert.CertificateException)21 BigInteger (java.math.BigInteger)20 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)19 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)18 NoSuchProviderException (java.security.NoSuchProviderException)16