Search in sources :

Example 16 with Certificate

use of org.apache.harmony.security.x509.Certificate in project xipki by xipki.

the class ScepUtil method generateSelfsignedCert.

public static X509Certificate generateSelfsignedCert(X500Name subjectDn, SubjectPublicKeyInfo pubKeyInfo, PrivateKey identityKey) throws CertificateException {
    requireNonNull("subjectDn", subjectDn);
    requireNonNull("pubKeyInfo", pubKeyInfo);
    requireNonNull("identityKey", identityKey);
    Date notBefore = new Date(System.currentTimeMillis() - 5 * MIN_IN_MS);
    Date notAfter = new Date(notBefore.getTime() + 30 * DAY_IN_MS);
    X509v3CertificateBuilder certGenerator = new X509v3CertificateBuilder(subjectDn, BigInteger.ONE, notBefore, notAfter, subjectDn, pubKeyInfo);
    X509KeyUsage ku = new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.dataEncipherment | X509KeyUsage.keyAgreement | X509KeyUsage.keyEncipherment);
    try {
        certGenerator.addExtension(Extension.keyUsage, true, ku);
    } catch (CertIOException ex) {
        throw new CertificateException("could not generate self-signed certificate: " + ex.getMessage(), ex);
    }
    String sigAlgorithm = ScepUtil.getSignatureAlgorithm(identityKey, ScepHashAlgo.SHA1);
    ContentSigner contentSigner;
    try {
        contentSigner = new JcaContentSignerBuilder(sigAlgorithm).build(identityKey);
    } catch (OperatorCreationException ex) {
        throw new CertificateException("error while creating signer", ex);
    }
    Certificate asn1Cert = certGenerator.build(contentSigner).toASN1Structure();
    return toX509Cert(asn1Cert);
}
Also used : X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) CertificateException(java.security.cert.CertificateException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CertIOException(org.bouncycastle.cert.CertIOException) Date(java.util.Date) X509KeyUsage(org.bouncycastle.jce.X509KeyUsage) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 17 with Certificate

use of org.apache.harmony.security.x509.Certificate in project xipki by xipki.

the class ExtractCertFromCrlCmd method execute0.

@Override
protected Object execute0() throws Exception {
    X509CRL crl = X509Util.parseCrl(crlFile);
    String oidExtnCerts = ObjectIdentifiers.id_xipki_ext_crlCertset.getId();
    byte[] extnValue = crl.getExtensionValue(oidExtnCerts);
    if (extnValue == null) {
        throw new IllegalCmdParamException("no certificate is contained in " + crlFile);
    }
    extnValue = removingTagAndLenFromExtensionValue(extnValue);
    ASN1Set asn1Set = DERSet.getInstance(extnValue);
    final int n = asn1Set.size();
    if (n == 0) {
        throw new CmdFailure("no certificate is contained in " + crlFile);
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ZipOutputStream zip = new ZipOutputStream(out);
    for (int i = 0; i < n; i++) {
        ASN1Encodable asn1 = asn1Set.getObjectAt(i);
        Certificate cert;
        try {
            ASN1Sequence seq = ASN1Sequence.getInstance(asn1);
            cert = Certificate.getInstance(seq.getObjectAt(0));
        } catch (IllegalArgumentException ex) {
            // backwards compatibility
            cert = Certificate.getInstance(asn1);
        }
        byte[] certBytes = cert.getEncoded();
        String sha1FpCert = HashAlgo.SHA1.hexHash(certBytes);
        ZipEntry certZipEntry = new ZipEntry(sha1FpCert + ".der");
        zip.putNextEntry(certZipEntry);
        try {
            zip.write(certBytes);
        } finally {
            zip.closeEntry();
        }
    }
    zip.flush();
    zip.close();
    saveVerbose("extracted " + n + " certificates to", new File(outFile), out.toByteArray());
    return null;
}
Also used : X509CRL(java.security.cert.X509CRL) ZipEntry(java.util.zip.ZipEntry) DEROctetString(org.bouncycastle.asn1.DEROctetString) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ASN1Set(org.bouncycastle.asn1.ASN1Set) CmdFailure(org.xipki.console.karaf.CmdFailure) ZipOutputStream(java.util.zip.ZipOutputStream) IllegalCmdParamException(org.xipki.console.karaf.IllegalCmdParamException) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) File(java.io.File) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 18 with Certificate

use of org.apache.harmony.security.x509.Certificate in project jasn1 by openmuc.

the class AuthenticateResponseOk method decode.

public int decode(InputStream is, boolean withTag) throws IOException {
    int codeLength = 0;
    int subCodeLength = 0;
    BerTag berTag = new BerTag();
    if (withTag) {
        codeLength += tag.decodeAndCheck(is);
    }
    BerLength length = new BerLength();
    codeLength += length.decode(is);
    int totalLength = length.val;
    if (totalLength == -1) {
        subCodeLength += berTag.decode(is);
        if (berTag.tagNumber == 0 && berTag.tagClass == 0 && berTag.primitive == 0) {
            int nextByte = is.read();
            if (nextByte != 0) {
                if (nextByte == -1) {
                    throw new EOFException("Unexpected end of input stream.");
                }
                throw new IOException("Decoded sequence has wrong end of contents octets");
            }
            codeLength += subCodeLength + 1;
            return codeLength;
        }
        if (berTag.equals(EuiccSigned1.tag)) {
            euiccSigned1 = new EuiccSigned1();
            subCodeLength += euiccSigned1.decode(is, false);
            subCodeLength += berTag.decode(is);
        }
        if (berTag.tagNumber == 0 && berTag.tagClass == 0 && berTag.primitive == 0) {
            int nextByte = is.read();
            if (nextByte != 0) {
                if (nextByte == -1) {
                    throw new EOFException("Unexpected end of input stream.");
                }
                throw new IOException("Decoded sequence has wrong end of contents octets");
            }
            codeLength += subCodeLength + 1;
            return codeLength;
        }
        if (berTag.equals(BerTag.APPLICATION_CLASS, BerTag.PRIMITIVE, 55)) {
            euiccSignature1 = new BerOctetString();
            subCodeLength += euiccSignature1.decode(is, false);
            subCodeLength += berTag.decode(is);
        }
        if (berTag.tagNumber == 0 && berTag.tagClass == 0 && berTag.primitive == 0) {
            int nextByte = is.read();
            if (nextByte != 0) {
                if (nextByte == -1) {
                    throw new EOFException("Unexpected end of input stream.");
                }
                throw new IOException("Decoded sequence has wrong end of contents octets");
            }
            codeLength += subCodeLength + 1;
            return codeLength;
        }
        if (berTag.equals(Certificate.tag)) {
            euiccCertificate = new Certificate();
            subCodeLength += euiccCertificate.decode(is, false);
            subCodeLength += berTag.decode(is);
        }
        if (berTag.tagNumber == 0 && berTag.tagClass == 0 && berTag.primitive == 0) {
            int nextByte = is.read();
            if (nextByte != 0) {
                if (nextByte == -1) {
                    throw new EOFException("Unexpected end of input stream.");
                }
                throw new IOException("Decoded sequence has wrong end of contents octets");
            }
            codeLength += subCodeLength + 1;
            return codeLength;
        }
        if (berTag.equals(Certificate.tag)) {
            eumCertificate = new Certificate();
            subCodeLength += eumCertificate.decode(is, false);
            subCodeLength += berTag.decode(is);
        }
        int nextByte = is.read();
        if (berTag.tagNumber != 0 || berTag.tagClass != 0 || berTag.primitive != 0 || nextByte != 0) {
            if (nextByte == -1) {
                throw new EOFException("Unexpected end of input stream.");
            }
            throw new IOException("Decoded sequence has wrong end of contents octets");
        }
        codeLength += subCodeLength + 1;
        return codeLength;
    }
    codeLength += totalLength;
    subCodeLength += berTag.decode(is);
    if (berTag.equals(EuiccSigned1.tag)) {
        euiccSigned1 = new EuiccSigned1();
        subCodeLength += euiccSigned1.decode(is, false);
        subCodeLength += berTag.decode(is);
    } else {
        throw new IOException("Tag does not match the mandatory sequence element tag.");
    }
    if (berTag.equals(BerTag.APPLICATION_CLASS, BerTag.PRIMITIVE, 55)) {
        euiccSignature1 = new BerOctetString();
        subCodeLength += euiccSignature1.decode(is, false);
        subCodeLength += berTag.decode(is);
    } else {
        throw new IOException("Tag does not match the mandatory sequence element tag.");
    }
    if (berTag.equals(Certificate.tag)) {
        euiccCertificate = new Certificate();
        subCodeLength += euiccCertificate.decode(is, false);
        subCodeLength += berTag.decode(is);
    } else {
        throw new IOException("Tag does not match the mandatory sequence element tag.");
    }
    if (berTag.equals(Certificate.tag)) {
        eumCertificate = new Certificate();
        subCodeLength += eumCertificate.decode(is, false);
        if (subCodeLength == totalLength) {
            return codeLength;
        }
    }
    throw new IOException("Unexpected end of sequence, length tag: " + totalLength + ", actual sequence length: " + subCodeLength);
}
Also used : EOFException(java.io.EOFException) IOException(java.io.IOException) Certificate(org.openmuc.jasn1.compiler.pkix1explicit88.Certificate)

Example 19 with Certificate

use of org.apache.harmony.security.x509.Certificate in project jruby-openssl by jruby.

the class OCSPRequest method verify.

@JRubyMethod(name = "verify", rest = true)
public IRubyObject verify(IRubyObject[] args) {
    Ruby runtime = getRuntime();
    ThreadContext context = runtime.getCurrentContext();
    int flags = 0;
    boolean ret = false;
    if (Arity.checkArgumentCount(runtime, args, 2, 3) == 3) {
        flags = RubyFixnum.fix2int((RubyFixnum) args[2]);
    }
    IRubyObject certificates = args[0];
    IRubyObject store = args[1];
    OCSPReq bcOCSPReq = getBCOCSPReq();
    if (bcOCSPReq == null) {
        throw newOCSPError(runtime, new NullPointerException("Missing BC asn1bcReq. Missing certIDs or signature?"));
    }
    if (!bcOCSPReq.isSigned()) {
        return RubyBoolean.newBoolean(runtime, ret);
    }
    GeneralName genName = bcOCSPReq.getRequestorName();
    if (genName.getTagNo() != 4) {
        return RubyBoolean.newBoolean(runtime, ret);
    }
    X500Name genX500Name = X500Name.getInstance(genName.getName());
    X509StoreContext storeContext = null;
    JcaContentVerifierProviderBuilder jcacvpb = new JcaContentVerifierProviderBuilder();
    jcacvpb.setProvider("BC");
    try {
        java.security.cert.Certificate signer = findCertByName(genX500Name, certificates, flags);
        if (signer == null)
            return RubyBoolean.newBoolean(runtime, ret);
        if ((flags & RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_NOINTERN))) > 0 && ((flags & RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_TRUSTOTHER))) > 0))
            flags |= RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_NOVERIFY));
        if ((flags & RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_NOSIGS))) == 0) {
            PublicKey signerPubKey = signer.getPublicKey();
            ContentVerifierProvider cvp = jcacvpb.build(signerPubKey);
            ret = bcOCSPReq.isSignatureValid(cvp);
            if (!ret) {
                return RubyBoolean.newBoolean(runtime, ret);
            }
        }
        if ((flags & RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_NOVERIFY))) == 0) {
            if ((flags & RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_NOCHAIN))) > 0) {
                storeContext = X509StoreContext.newStoreContext(context, (X509Store) store, X509Cert.wrap(runtime, signer), context.nil);
            } else {
                RubyArray certs = RubyArray.newEmptyArray(runtime);
                ASN1Sequence bcCerts = asn1bcReq.getOptionalSignature().getCerts();
                if (bcCerts != null) {
                    Iterator<ASN1Encodable> it = bcCerts.iterator();
                    while (it.hasNext()) {
                        Certificate cert = Certificate.getInstance(it.next());
                        certs.add(X509Cert.wrap(runtime, new X509AuxCertificate(cert)));
                    }
                }
                storeContext = X509StoreContext.newStoreContext(context, (X509Store) store, X509Cert.wrap(runtime, signer), certs);
            }
            storeContext.set_purpose(context, _X509(runtime).getConstant("PURPOSE_OCSP_HELPER"));
            storeContext.set_trust(context, _X509(runtime).getConstant("TRUST_OCSP_REQUEST"));
            ret = storeContext.verify(context).isTrue();
            if (!ret)
                return RubyBoolean.newBoolean(runtime, false);
        }
    } catch (Exception e) {
        debugStackTrace(e);
        throw newOCSPError(runtime, e);
    }
    return RubyBoolean.newBoolean(getRuntime(), ret);
}
Also used : RubyArray(org.jruby.RubyArray) X500Name(org.bouncycastle.asn1.x500.X500Name) IRubyObject(org.jruby.runtime.builtin.IRubyObject) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) Ruby(org.jruby.Ruby) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider) PublicKey(java.security.PublicKey) ThreadContext(org.jruby.runtime.ThreadContext) RubyFixnum(org.jruby.RubyFixnum) RaiseException(org.jruby.exceptions.RaiseException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) JcaContentVerifierProviderBuilder(org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) GeneralName(org.bouncycastle.asn1.x509.GeneralName) X509AuxCertificate(org.jruby.ext.openssl.x509store.X509AuxCertificate) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate) X509AuxCertificate(org.jruby.ext.openssl.x509store.X509AuxCertificate) JRubyMethod(org.jruby.anno.JRubyMethod)

Example 20 with Certificate

use of org.apache.harmony.security.x509.Certificate in project xipki by xipki.

the class OcspCertStoreFromCaDbImporter method importCert0.

// method importCert
private long importCert0(HashAlgo certhashAlgo, PreparedStatement psCert, String certsZipFile, Map<Integer, String> profileMap, boolean revokedOnly, List<Integer> caIds, long minId, File processLogFile, ProcessLog processLog, int numProcessedInLastProcess, ProcessLog importLog) throws Exception {
    ZipFile zipFile = new ZipFile(new File(certsZipFile));
    ZipEntry certsXmlEntry = zipFile.getEntry("overview.xml");
    CertsReader certs;
    try {
        certs = new CertsReader(zipFile.getInputStream(certsXmlEntry));
    } catch (Exception ex) {
        try {
            zipFile.close();
        } catch (Exception ex2) {
            LOG.error("could not close ZIP file {}: {}", certsZipFile, ex2.getMessage());
            LOG.debug("could not close ZIP file " + certsZipFile, ex2);
        }
        throw ex;
    }
    disableAutoCommit();
    try {
        int numProcessedEntriesInBatch = 0;
        int numImportedEntriesInBatch = 0;
        long lastSuccessfulCertId = 0;
        while (certs.hasNext()) {
            if (stopMe.get()) {
                throw new InterruptedException("interrupted by the user");
            }
            CertType cert = (CertType) certs.next();
            long id = cert.getId();
            lastSuccessfulCertId = id;
            if (id < minId) {
                continue;
            }
            numProcessedEntriesInBatch++;
            if (!revokedOnly || cert.getRev().booleanValue()) {
                int caId = cert.getCaId();
                if (caIds.contains(caId)) {
                    numImportedEntriesInBatch++;
                    String filename = cert.getFile();
                    // rawcert
                    ZipEntry certZipEnty = zipFile.getEntry(filename);
                    // rawcert
                    byte[] encodedCert = IoUtil.read(zipFile.getInputStream(certZipEnty));
                    String certhash = certhashAlgo.base64Hash(encodedCert);
                    TBSCertificate tbsCert;
                    try {
                        Certificate cc = Certificate.getInstance(encodedCert);
                        tbsCert = cc.getTBSCertificate();
                    } catch (RuntimeException ex) {
                        LOG.error("could not parse certificate in file {}", filename);
                        LOG.debug("could not parse certificate in file " + filename, ex);
                        throw new CertificateException(ex.getMessage(), ex);
                    }
                    String subject = X509Util.cutX500Name(tbsCert.getSubject(), maxX500nameLen);
                    // cert
                    try {
                        int idx = 1;
                        psCert.setLong(idx++, id);
                        psCert.setInt(idx++, caId);
                        psCert.setString(idx++, tbsCert.getSerialNumber().getPositiveValue().toString(16));
                        psCert.setLong(idx++, cert.getUpdate());
                        psCert.setLong(idx++, tbsCert.getStartDate().getDate().getTime() / 1000);
                        psCert.setLong(idx++, tbsCert.getEndDate().getDate().getTime() / 1000);
                        setBoolean(psCert, idx++, cert.getRev());
                        setInt(psCert, idx++, cert.getRr());
                        setLong(psCert, idx++, cert.getRt());
                        setLong(psCert, idx++, cert.getRit());
                        int certprofileId = cert.getPid();
                        String certprofileName = profileMap.get(certprofileId);
                        psCert.setString(idx++, certprofileName);
                        psCert.setString(idx++, certhash);
                        psCert.setString(idx++, subject);
                        psCert.addBatch();
                    } catch (SQLException ex) {
                        throw translate(SQL_ADD_CERT, ex);
                    }
                }
            // end if (caIds.contains(caId))
            }
            // end if (revokedOnly
            boolean isLastBlock = !certs.hasNext();
            if (numImportedEntriesInBatch > 0 && (numImportedEntriesInBatch % this.numCertsPerCommit == 0 || isLastBlock)) {
                if (evaulateOnly) {
                    psCert.clearBatch();
                } else {
                    try {
                        psCert.executeBatch();
                        commit("(commit import cert to OCSP)");
                    } catch (Throwable th) {
                        rollback();
                        deleteCertGreatherThan(lastSuccessfulCertId, LOG);
                        if (th instanceof SQLException) {
                            throw translate(SQL_ADD_CERT, (SQLException) th);
                        } else if (th instanceof Exception) {
                            throw (Exception) th;
                        } else {
                            throw new Exception(th);
                        }
                    }
                }
                lastSuccessfulCertId = id;
                processLog.addNumProcessed(numProcessedEntriesInBatch);
                importLog.addNumProcessed(numImportedEntriesInBatch);
                numProcessedEntriesInBatch = 0;
                numImportedEntriesInBatch = 0;
                String filename = (numProcessedInLastProcess + processLog.numProcessed()) + ":" + lastSuccessfulCertId;
                echoToFile(filename, processLogFile);
                processLog.printStatus();
            } else if (isLastBlock) {
                lastSuccessfulCertId = id;
                processLog.addNumProcessed(numProcessedEntriesInBatch);
                importLog.addNumProcessed(numImportedEntriesInBatch);
                numProcessedEntriesInBatch = 0;
                numImportedEntriesInBatch = 0;
                String filename = (numProcessedInLastProcess + processLog.numProcessed()) + ":" + lastSuccessfulCertId;
                echoToFile(filename, processLogFile);
                processLog.printStatus();
            }
        // if (numImportedEntriesInBatch)
        }
        return lastSuccessfulCertId;
    } finally {
        recoverAutoCommit();
        zipFile.close();
    }
}
Also used : SQLException(java.sql.SQLException) ZipEntry(java.util.zip.ZipEntry) CertType(org.xipki.ca.dbtool.xmlio.ca.CertType) CertificateException(java.security.cert.CertificateException) InvalidInputException(org.xipki.dbtool.InvalidInputException) SQLException(java.sql.SQLException) DataAccessException(org.xipki.datasource.DataAccessException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) JAXBException(javax.xml.bind.JAXBException) ZipFile(java.util.zip.ZipFile) ZipFile(java.util.zip.ZipFile) File(java.io.File) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) CertsReader(org.xipki.ca.dbtool.xmlio.ca.CertsReader) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Aggregations

Certificate (org.bouncycastle.asn1.x509.Certificate)35 X509Certificate (java.security.cert.X509Certificate)29 IOException (java.io.IOException)23 CertificateException (java.security.cert.CertificateException)18 ArrayList (java.util.ArrayList)11 Date (java.util.Date)11 BigInteger (java.math.BigInteger)9 List (java.util.List)9 X500Name (org.bouncycastle.asn1.x500.X500Name)9 File (java.io.File)7 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)7 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)7 GeneralName (org.apache.harmony.security.x509.GeneralName)6 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)6 TBSCertificate (org.bouncycastle.asn1.x509.TBSCertificate)6 DEROctetString (org.bouncycastle.asn1.DEROctetString)5 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)5 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)5 EOFException (java.io.EOFException)4 X509CRL (java.security.cert.X509CRL)4