Search in sources :

Example 76 with Time

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

the class X509CRLStreamWriter method writeNewTime.

/**
 * Write a UTCTime or GeneralizedTime to an output stream.
 *
 * @param out
 * @param newTime
 * @param originalLength
 * @throws IOException
 */
protected void writeNewTime(OutputStream out, ASN1Object newTime, int originalLength) throws IOException {
    byte[] newEncodedTime = newTime.getEncoded();
    InputStream timeIn = null;
    try {
        timeIn = new ByteArrayInputStream(newEncodedTime);
        int newTag = readTag(timeIn, null);
        readTagNumber(timeIn, newTag, null);
        int newLength = readLength(timeIn, null);
        /* If the length changes, it's going to create a discrepancy with the length
             * reported in the TBSCertList sequence.  The length could change with the addition
             * or removal of time zone information for example. */
        if (newLength != originalLength) {
            throw new IllegalStateException("Length of generated time does not match " + "the original length. DER corruption would result.");
        }
    } finally {
        IOUtils.closeQuietly(timeIn);
    }
    writeBytes(out, newEncodedTime);
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream)

Example 77 with Time

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

the class X509CRLStreamWriter method add.

/**
 * Create an entry to be added to the CRL.
 *
 * @param serial
 * @param date
 * @param reason
 * @throws IOException if an entry fails to generate
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public void add(BigInteger serial, Date date, int reason) throws IOException {
    if (locked) {
        throw new IllegalStateException("Cannot add to a locked stream.");
    }
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1Integer(serial));
    v.add(new Time(date));
    CRLReason crlReason = CRLReason.getInstance(new ASN1Enumerated(reason));
    ExtensionsGenerator generator = new ExtensionsGenerator();
    generator.addExtension(Extension.reasonCode, false, crlReason);
    v.add(generator.generate());
    newEntries.add(new DERSequence(v));
}
Also used : DERSequence(org.bouncycastle.asn1.DERSequence) ASN1Enumerated(org.bouncycastle.asn1.ASN1Enumerated) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) DERGeneralizedTime(org.bouncycastle.asn1.DERGeneralizedTime) ASN1GeneralizedTime(org.bouncycastle.asn1.ASN1GeneralizedTime) DERUTCTime(org.bouncycastle.asn1.DERUTCTime) Time(org.bouncycastle.asn1.x509.Time) ASN1UTCTime(org.bouncycastle.asn1.ASN1UTCTime) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) CRLReason(org.bouncycastle.asn1.x509.CRLReason) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator)

Example 78 with Time

use of org.bouncycastle.asn1.x509.Time in project jruby-openssl by jruby.

the class ASN1 method createASN1.

public static void createASN1(final Ruby runtime, final RubyModule OpenSSL) {
    final RubyModule ASN1 = OpenSSL.defineModuleUnder("ASN1");
    final RubyClass OpenSSLError = OpenSSL.getClass("OpenSSLError");
    ASN1.defineClassUnder("ASN1Error", OpenSSLError, OpenSSLError.getAllocator());
    ASN1.defineAnnotatedMethods(ASN1.class);
    final RubyArray UNIVERSAL_TAG_NAME = runtime.newArray(ASN1_INFO.length);
    for (int i = 0; i < ASN1_INFO.length; i++) {
        final String name = (String) ASN1_INFO[i][0];
        if (name.charAt(0) != '[') {
            UNIVERSAL_TAG_NAME.append(runtime.newString(name));
            ASN1.setConstant(name, runtime.newFixnum(i));
        } else {
            UNIVERSAL_TAG_NAME.append(runtime.getNil());
        }
    }
    ASN1.setConstant("UNIVERSAL_TAG_NAME", UNIVERSAL_TAG_NAME);
    final ThreadContext context = runtime.getCurrentContext();
    final ObjectAllocator asn1DataAllocator = ASN1Data.ALLOCATOR;
    RubyClass _ASN1Data = ASN1.defineClassUnder("ASN1Data", runtime.getObject(), asn1DataAllocator);
    _ASN1Data.addReadWriteAttribute(context, "value");
    _ASN1Data.addReadWriteAttribute(context, "tag");
    _ASN1Data.addReadWriteAttribute(context, "tag_class");
    _ASN1Data.defineAnnotatedMethods(ASN1Data.class);
    final ObjectAllocator primitiveAllocator = Primitive.ALLOCATOR;
    RubyClass Primitive = ASN1.defineClassUnder("Primitive", _ASN1Data, primitiveAllocator);
    Primitive.addReadWriteAttribute(context, "tagging");
    Primitive.addReadAttribute(context, "infinite_length");
    Primitive.defineAnnotatedMethods(Primitive.class);
    final ObjectAllocator constructiveAllocator = Constructive.ALLOCATOR;
    RubyClass Constructive = ASN1.defineClassUnder("Constructive", _ASN1Data, constructiveAllocator);
    Constructive.includeModule(runtime.getModule("Enumerable"));
    Constructive.addReadWriteAttribute(context, "tagging");
    Constructive.addReadWriteAttribute(context, "infinite_length");
    Constructive.defineAnnotatedMethods(Constructive.class);
    // OpenSSL::ASN1::Boolean <=> value is a Boolean
    ASN1.defineClassUnder("Boolean", Primitive, primitiveAllocator);
    // OpenSSL::ASN1::Integer <=> value is a Number
    ASN1.defineClassUnder("Integer", Primitive, primitiveAllocator);
    // OpenSSL::ASN1::Null <=> value is always nil
    ASN1.defineClassUnder("Null", Primitive, primitiveAllocator);
    // OpenSSL::ASN1::Object <=> value is a String
    ASN1.defineClassUnder("Object", Primitive, primitiveAllocator);
    // OpenSSL::ASN1::Enumerated <=> value is a Number
    ASN1.defineClassUnder("Enumerated", Primitive, primitiveAllocator);
    RubyClass BitString = ASN1.defineClassUnder("BitString", Primitive, primitiveAllocator);
    BitString.addReadWriteAttribute(context, "unused_bits");
    ASN1.defineClassUnder("OctetString", Primitive, primitiveAllocator);
    ASN1.defineClassUnder("UTF8String", Primitive, primitiveAllocator);
    ASN1.defineClassUnder("NumericString", Primitive, primitiveAllocator);
    ASN1.defineClassUnder("PrintableString", Primitive, primitiveAllocator);
    ASN1.defineClassUnder("T61String", Primitive, primitiveAllocator);
    ASN1.defineClassUnder("VideotexString", Primitive, primitiveAllocator);
    ASN1.defineClassUnder("IA5String", Primitive, primitiveAllocator);
    ASN1.defineClassUnder("GraphicString", Primitive, primitiveAllocator);
    ASN1.defineClassUnder("ISO64String", Primitive, primitiveAllocator);
    ASN1.defineClassUnder("GeneralString", Primitive, primitiveAllocator);
    ASN1.defineClassUnder("UniversalString", Primitive, primitiveAllocator);
    ASN1.defineClassUnder("BMPString", Primitive, primitiveAllocator);
    // OpenSSL::ASN1::UTCTime <=> value is a Time
    ASN1.defineClassUnder("UTCTime", Primitive, primitiveAllocator);
    // OpenSSL::ASN1::GeneralizedTime <=> value is a Time
    ASN1.defineClassUnder("GeneralizedTime", Primitive, primitiveAllocator);
    // OpenSSL::ASN1::EndOfContent <=> value is always nil
    ASN1.defineClassUnder("EndOfContent", Primitive, primitiveAllocator);
    RubyClass ObjectId = ASN1.defineClassUnder("ObjectId", Primitive, primitiveAllocator);
    ObjectId.defineAnnotatedMethods(ObjectId.class);
    ASN1.defineClassUnder("Sequence", Constructive, Constructive.getAllocator());
    ASN1.defineClassUnder("Set", Constructive, Constructive.getAllocator());
}
Also used : RubyModule(org.jruby.RubyModule) RubyArray(org.jruby.RubyArray) ThreadContext(org.jruby.runtime.ThreadContext) RubyClass(org.jruby.RubyClass) DERBitString(org.bouncycastle.asn1.DERBitString) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERBMPString(org.bouncycastle.asn1.DERBMPString) DERGeneralString(org.bouncycastle.asn1.DERGeneralString) RubyString(org.jruby.RubyString) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DERNumericString(org.bouncycastle.asn1.DERNumericString) DEROctetString(org.bouncycastle.asn1.DEROctetString) BEROctetString(org.bouncycastle.asn1.BEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DERT61String(org.bouncycastle.asn1.DERT61String) DERVisibleString(org.bouncycastle.asn1.DERVisibleString) ASN1String(org.bouncycastle.asn1.ASN1String) DERUniversalString(org.bouncycastle.asn1.DERUniversalString) ObjectAllocator(org.jruby.runtime.ObjectAllocator)

Example 79 with Time

use of org.bouncycastle.asn1.x509.Time in project pac4j by pac4j.

the class SAML2ClientConfiguration method createSelfSignedCert.

/**
 * Generate a self-signed certificate for dn using the provided signature algorithm and key pair.
 *
 * @param dn X.500 name to associate with certificate issuer/subject.
 * @param sigName name of the signature algorithm to use.
 * @param sigAlgID algorithm ID associated with the signature algorithm name.
 * @param keyPair the key pair to associate with the certificate.
 * @return an X509Certificate containing the public key in keyPair.
 * @throws Exception
 */
private X509Certificate createSelfSignedCert(X500Name dn, String sigName, AlgorithmIdentifier sigAlgID, KeyPair keyPair) throws Exception {
    V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
    certGen.setSerialNumber(new ASN1Integer(BigInteger.valueOf(1)));
    certGen.setIssuer(dn);
    certGen.setSubject(dn);
    certGen.setStartDate(new Time(new Date(System.currentTimeMillis() - 1000L)));
    final Calendar c = Calendar.getInstance();
    c.setTime(new Date());
    c.add(Calendar.YEAR, 1);
    certGen.setEndDate(new Time(c.getTime()));
    certGen.setSignature(sigAlgID);
    certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));
    Signature sig = Signature.getInstance(sigName);
    sig.initSign(keyPair.getPrivate());
    sig.update(certGen.generateTBSCertificate().getEncoded(ASN1Encoding.DER));
    TBSCertificate tbsCert = certGen.generateTBSCertificate();
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(tbsCert);
    v.add(sigAlgID);
    v.add(new DERBitString(sig.sign()));
    X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER)));
    // check the certificate - this will confirm the encoded sig algorithm ID is correct.
    cert.verify(keyPair.getPublic());
    return cert;
}
Also used : DERSequence(org.bouncycastle.asn1.DERSequence) ByteArrayInputStream(java.io.ByteArrayInputStream) Calendar(java.util.Calendar) Signature(java.security.Signature) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) V3TBSCertificateGenerator(org.bouncycastle.asn1.x509.V3TBSCertificateGenerator) Time(org.bouncycastle.asn1.x509.Time) DERBitString(org.bouncycastle.asn1.DERBitString) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate)

Example 80 with Time

use of org.bouncycastle.asn1.x509.Time in project xipki by xipki.

the class CertStoreQueryExecutor method listCertificates.

List<CertListInfo> listCertificates(NameId ca, X500Name subjectPattern, Date validFrom, Date validTo, CertListOrderBy orderBy, int numEntries) throws DataAccessException, OperationException {
    ParamUtil.requireNonNull("ca", ca);
    ParamUtil.requireMin("numEntries", numEntries, 1);
    StringBuilder sb = new StringBuilder(200);
    sb.append("SN,NBEFORE,NAFTER,SUBJECT FROM CERT WHERE CA_ID=?");
    // .append(caId)
    Integer idxNotBefore = null;
    Integer idxNotAfter = null;
    Integer idxSubject = null;
    int idx = 2;
    if (validFrom != null) {
        idxNotBefore = idx++;
        sb.append(" AND NBEFORE<?");
    }
    if (validTo != null) {
        idxNotAfter = idx++;
        sb.append(" AND NAFTER>?");
    }
    String subjectLike = null;
    if (subjectPattern != null) {
        idxSubject = idx++;
        sb.append(" AND SUBJECT LIKE ?");
        StringBuilder buffer = new StringBuilder(100);
        buffer.append("%");
        RDN[] rdns = subjectPattern.getRDNs();
        for (int i = 0; i < rdns.length; i++) {
            X500Name rdnName = new X500Name(new RDN[] { rdns[i] });
            String rdnStr = X509Util.getRfc4519Name(rdnName);
            if (rdnStr.indexOf('%') != -1) {
                throw new OperationException(ErrorCode.BAD_REQUEST, "the character '%' is not allowed in subjectPattern");
            }
            if (rdnStr.indexOf('*') != -1) {
                rdnStr = rdnStr.replace('*', '%');
            }
            buffer.append(rdnStr);
            buffer.append("%");
        }
        subjectLike = buffer.toString();
    }
    String sortByStr = null;
    if (orderBy != null) {
        switch(orderBy) {
            case NOT_BEFORE:
                sortByStr = "NBEFORE";
                break;
            case NOT_BEFORE_DESC:
                sortByStr = "NBEFORE DESC";
                break;
            case NOT_AFTER:
                sortByStr = "NAFTER";
                break;
            case NOT_AFTER_DESC:
                sortByStr = "NAFTER DESC";
                break;
            case SUBJECT:
                sortByStr = "SUBJECT";
                break;
            case SUBJECT_DESC:
                sortByStr = "SUBJECT DESC";
                break;
            default:
                throw new RuntimeException("unknown CertListOrderBy " + orderBy);
        }
    }
    final String sql = datasource.buildSelectFirstSql(numEntries, sortByStr, sb.toString());
    ResultSet rs = null;
    PreparedStatement ps = borrowPreparedStatement(sql);
    try {
        ps.setInt(1, ca.getId());
        if (idxNotBefore != null) {
            long time = validFrom.getTime() / 1000;
            ps.setLong(idxNotBefore, time - 1);
        }
        if (idxNotAfter != null) {
            long time = validTo.getTime() / 1000;
            ps.setLong(idxNotAfter, time);
        }
        if (idxSubject != null) {
            ps.setString(idxSubject, subjectLike);
        }
        rs = ps.executeQuery();
        List<CertListInfo> ret = new LinkedList<>();
        while (rs.next()) {
            String snStr = rs.getString("SN");
            BigInteger sn = new BigInteger(snStr, 16);
            Date notBefore = new Date(rs.getLong("NBEFORE") * 1000);
            Date notAfter = new Date(rs.getLong("NAFTER") * 1000);
            String subject = rs.getString("SUBJECT");
            CertListInfo info = new CertListInfo(sn, subject, notBefore, notAfter);
            ret.add(info);
        }
        return ret;
    } catch (SQLException ex) {
        throw datasource.translate(sql, ex);
    } finally {
        releaseDbResources(ps, rs);
    }
}
Also used : SQLException(java.sql.SQLException) CertListInfo(org.xipki.ca.server.mgmt.api.CertListInfo) PreparedStatement(java.sql.PreparedStatement) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DEROctetString(org.bouncycastle.asn1.DEROctetString) X500Name(org.bouncycastle.asn1.x500.X500Name) LinkedList(java.util.LinkedList) Date(java.util.Date) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) BigInteger(java.math.BigInteger) ResultSet(java.sql.ResultSet) BigInteger(java.math.BigInteger) RDN(org.bouncycastle.asn1.x500.RDN) OperationException(org.xipki.ca.api.OperationException)

Aggregations

Time (com.android.calendarcommon2.Time)178 IOException (java.io.IOException)50 Date (java.util.Date)43 X509Certificate (java.security.cert.X509Certificate)37 BigInteger (java.math.BigInteger)32 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)32 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)32 X500Name (org.bouncycastle.asn1.x500.X500Name)28 DEROctetString (org.bouncycastle.asn1.DEROctetString)27 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)26 ArrayList (java.util.ArrayList)25 Paint (android.graphics.Paint)20 DERSequence (org.bouncycastle.asn1.DERSequence)17 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)16 ByteArrayInputStream (java.io.ByteArrayInputStream)15 CertificateException (java.security.cert.CertificateException)15 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)15 Time (org.bouncycastle.asn1.x509.Time)15 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)14 SecureRandom (java.security.SecureRandom)14