Search in sources :

Example 26 with ASN1Boolean

use of com.github.zhenwei.core.asn1.ASN1Boolean in project LinLong-Java by zhenwei1108.

the class OEROutputStream method write.

public void write(ASN1Encodable encodable, OERDefinition.Element oerElement) throws IOException {
    if (encodable == OEROptional.ABSENT) {
        return;
    } else if (encodable instanceof OEROptional) {
        write(((OEROptional) encodable).get(), oerElement);
        return;
    }
    encodable = encodable.toASN1Primitive();
    switch(oerElement.baseType) {
        case SEQ:
            {
                ASN1Sequence seq = ASN1Sequence.getInstance(encodable);
                // build mask.
                int j = 7;
                int mask = 0;
                if (oerElement.extensionsInDefinition) {
                    if (oerElement.hasPopulatedExtension()) {
                        mask |= bits[j];
                    }
                    j--;
                }
                for (int t = 0; t < oerElement.children.size(); t++) {
                    OERDefinition.Element childOERDescription = oerElement.children.get(t);
                    if (j < 0) {
                        out.write(mask);
                        j = 7;
                        mask = 0;
                    }
                    ASN1Encodable asn1EncodableChild = seq.getObjectAt(t);
                    if (childOERDescription.explicit && asn1EncodableChild instanceof OEROptional) {
                        // TODO call stack like definition error.
                        throw new IllegalStateException("absent sequence element that is required by oer definition");
                    }
                    if (!childOERDescription.explicit) {
                        ASN1Encodable obj = seq.getObjectAt(t);
                        if (childOERDescription.getDefaultValue() != null) {
                            if (obj instanceof OEROptional) {
                                if (((OEROptional) obj).isDefined()) {
                                    if (!((OEROptional) obj).get().equals(childOERDescription.defaultValue)) {
                                        mask |= bits[j];
                                    }
                                }
                            } else {
                                if (!childOERDescription.getDefaultValue().equals(obj)) {
                                    mask |= bits[j];
                                }
                            }
                        } else {
                            if (asn1EncodableChild != OEROptional.ABSENT) {
                                mask |= bits[j];
                            }
                        }
                        j--;
                    }
                }
                if (j != 7) {
                    out.write(mask);
                }
                // 
                for (int t = 0; t < oerElement.children.size(); t++) {
                    ASN1Encodable child = seq.getObjectAt(t);
                    OERDefinition.Element childOERElement = oerElement.children.get(t);
                    if (childOERElement.getDefaultValue() != null) {
                        if (childOERElement.getDefaultValue().equals(child)) {
                            continue;
                        }
                    }
                    write(child, childOERElement);
                }
                out.flush();
                debugPrint(oerElement.appendLabel(""));
            }
            break;
        case SEQ_OF:
            // 
            // Assume this comes in as a sequence.
            // 
            Enumeration e;
            if (encodable instanceof ASN1Set) {
                e = ((ASN1Set) encodable).getObjects();
                encodeQuantity(((ASN1Set) encodable).size());
            } else if (encodable instanceof ASN1Sequence) {
                e = ((ASN1Sequence) encodable).getObjects();
                encodeQuantity(((ASN1Sequence) encodable).size());
            } else {
                throw new IllegalStateException("encodable at for SEQ_OF is not a container");
            }
            while (e.hasMoreElements()) {
                Object o = e.nextElement();
                write((ASN1Encodable) o, oerElement.getFirstChid());
            }
            out.flush();
            debugPrint(oerElement.appendLabel(""));
            break;
        case CHOICE:
            {
                ASN1Primitive item = encodable.toASN1Primitive();
                BitBuilder bb = new BitBuilder();
                int tag;
                if (item instanceof ASN1ApplicationSpecific) {
                    // 
                    // Application specific tag prefix.
                    // 
                    tag = ((ASN1ApplicationSpecific) item).getApplicationTag();
                    bb.writeBit(0).writeBit(1);
                    item = ((ASN1ApplicationSpecific) item).getEnclosedObject();
                } else if (item instanceof ASN1TaggedObject) {
                    ASN1TaggedObject taggedObject = (ASN1TaggedObject) item;
                    // 
                    // Tag prefix.
                    // 
                    int tagClass = taggedObject.getTagClass();
                    bb.writeBit(tagClass & BERTags.CONTEXT_SPECIFIC).writeBit(tagClass & BERTags.APPLICATION);
                    tag = taggedObject.getTagNo();
                    item = taggedObject.getBaseObject().toASN1Primitive();
                } else {
                    throw new IllegalStateException("only support tagged objects");
                }
                // Small tag value encode in remaining bits
                if (tag <= 63) {
                    bb.writeBits(tag, 6);
                } else {
                    // Large tag value variant.
                    bb.writeBits(0xFF, 6);
                    // Encode as 7bit bytes where MSB indicated continuing byte.
                    bb.write7BitBytes(tag);
                }
                if (debugOutput != null) {
                    if (item instanceof ASN1ApplicationSpecific) {
                        debugPrint(oerElement.appendLabel("AS"));
                    } else if (item instanceof ASN1TaggedObject) {
                        debugPrint(oerElement.appendLabel("CS"));
                    }
                }
                // Save the header.
                bb.writeAndClear(out);
                write(item, oerElement.children.get(tag));
                out.flush();
                break;
            }
        case ENUM:
            {
                BigInteger ordinal;
                if (encodable instanceof ASN1Integer) {
                    ordinal = ASN1Integer.getInstance(encodable).getValue();
                } else {
                    ordinal = ASN1Enumerated.getInstance(encodable).getValue();
                }
                for (Iterator it = oerElement.children.iterator(); it.hasNext(); ) {
                    OERDefinition.Element child = (OERDefinition.Element) it.next();
                    // 
                    if (child.enumValue.equals(ordinal)) {
                        if (ordinal.compareTo(BigInteger.valueOf(127)) > 0) {
                            // Note 2 Section 11.4 of T-REC-X.696-201508-I!!PDF-E.pdf
                            byte[] val = ordinal.toByteArray();
                            int l = 0x80 | (val.length & 0xFF);
                            out.write(l);
                            out.write(val);
                        } else {
                            out.write(ordinal.intValue() & 0x7F);
                        }
                        out.flush();
                        debugPrint(oerElement.appendLabel(oerElement.rangeExpression()));
                        return;
                    }
                }
                throw new IllegalArgumentException("enum value " + ordinal + " " + Hex.toHexString(ordinal.toByteArray()) + " no in defined child list");
            }
        case INT:
            {
                ASN1Integer integer = ASN1Integer.getInstance(encodable);
                // >0 = positive and <0 = negative
                int intBytesForRange = oerElement.intBytesForRange();
                if (intBytesForRange > 0) {
                    // 
                    // For unsigned fixed length 1,2,4,8 byte integers.
                    // 
                    byte[] encoded = BigIntegers.asUnsignedByteArray(intBytesForRange, integer.getValue());
                    switch(intBytesForRange) {
                        case 1:
                        case 2:
                        case 4:
                        case 8:
                            out.write(encoded);
                            break;
                        default:
                            throw new IllegalStateException("unknown uint length " + intBytesForRange);
                    }
                } else if (intBytesForRange < 0) {
                    // 
                    // For twos compliment numbers of 1,2,4,8 bytes in encoded length.
                    // 
                    byte[] encoded;
                    BigInteger number = integer.getValue();
                    switch(intBytesForRange) {
                        case -1:
                            encoded = new byte[] { BigIntegers.byteValueExact(number) };
                            break;
                        case -2:
                            encoded = Pack.shortToBigEndian(BigIntegers.shortValueExact(number));
                            break;
                        case -4:
                            encoded = Pack.intToBigEndian(BigIntegers.intValueExact(number));
                            break;
                        case -8:
                            encoded = Pack.longToBigEndian(BigIntegers.longValueExact(number));
                            break;
                        default:
                            throw new IllegalStateException("unknown twos compliment length");
                    }
                    out.write(encoded);
                } else {
                    // Unbounded at one or both ends and needs length encoding.
                    byte[] encoded;
                    if (oerElement.isLowerRangeZero()) {
                        // Since we have already captured the fixed with unsigned ints.
                        // Everything is assumed unbounded we need to encode a length and write the value.
                        encoded = BigIntegers.asUnsignedByteArray(integer.getValue());
                    } else {
                        // Twos complement
                        encoded = integer.getValue().toByteArray();
                    }
                    // Deals with long and short forms.
                    encodeLength(encoded.length);
                    out.write(encoded);
                }
                debugPrint(oerElement.appendLabel(oerElement.rangeExpression()));
                out.flush();
            }
            break;
        case OCTET_STRING:
            {
                ASN1OctetString octets = ASN1OctetString.getInstance(encodable);
                byte[] bytes = octets.getOctets();
                if (oerElement.isFixedLength()) {
                    out.write(bytes);
                } else {
                    encodeLength(bytes.length);
                    out.write(bytes);
                }
                debugPrint(oerElement.appendLabel(oerElement.rangeExpression()));
                out.flush();
                break;
            }
        case UTF8_STRING:
            {
                ASN1UTF8String utf8 = ASN1UTF8String.getInstance(encodable);
                byte[] encoded = Strings.toUTF8ByteArray(utf8.getString());
                encodeLength(encoded.length);
                out.write(encoded);
                debugPrint(oerElement.appendLabel(""));
                out.flush();
                break;
            }
        case BIT_STRING:
            {
                DERBitString bitString = DERBitString.getInstance(encodable);
                byte[] bytes = bitString.getBytes();
                if (oerElement.isFixedLength()) {
                    out.write(bytes);
                    debugPrint(oerElement.appendLabel(oerElement.rangeExpression()));
                } else {
                    int padBits = bitString.getPadBits();
                    // 13.3.1
                    encodeLength(bytes.length + 1);
                    // 13.3.2
                    out.write(padBits);
                    // 13.3.3
                    out.write(bytes);
                    debugPrint(oerElement.appendLabel(oerElement.rangeExpression()));
                }
                out.flush();
            }
            break;
        case NULL:
            // Does not encode in OER.
            break;
        case EXTENSION:
            {
                ASN1OctetString octets = ASN1OctetString.getInstance(encodable);
                byte[] bytes = octets.getOctets();
                if (oerElement.isFixedLength()) {
                    out.write(bytes);
                } else {
                    encodeLength(bytes.length);
                    out.write(bytes);
                }
                debugPrint(oerElement.appendLabel(oerElement.rangeExpression()));
                out.flush();
                break;
            }
        case ENUM_ITEM:
            // Used to define options does not encode.
            break;
        case BOOLEAN:
            debugPrint(oerElement.label);
            ASN1Boolean asn1Boolean = ASN1Boolean.getInstance(encodable);
            if (asn1Boolean.isTrue()) {
                out.write(255);
            } else {
                out.write(0);
            }
            out.flush();
    }
}
Also used : ASN1OctetString(com.github.zhenwei.core.asn1.ASN1OctetString) Enumeration(java.util.Enumeration) ASN1UTF8String(com.github.zhenwei.core.asn1.ASN1UTF8String) ASN1TaggedObject(com.github.zhenwei.core.asn1.ASN1TaggedObject) ASN1ApplicationSpecific(com.github.zhenwei.core.asn1.ASN1ApplicationSpecific) DERBitString(com.github.zhenwei.core.asn1.DERBitString) ASN1Integer(com.github.zhenwei.core.asn1.ASN1Integer) ASN1Sequence(com.github.zhenwei.core.asn1.ASN1Sequence) ASN1Set(com.github.zhenwei.core.asn1.ASN1Set) Iterator(java.util.Iterator) BigInteger(java.math.BigInteger) ASN1TaggedObject(com.github.zhenwei.core.asn1.ASN1TaggedObject) ASN1Encodable(com.github.zhenwei.core.asn1.ASN1Encodable) ASN1Boolean(com.github.zhenwei.core.asn1.ASN1Boolean) ASN1Primitive(com.github.zhenwei.core.asn1.ASN1Primitive)

Example 27 with ASN1Boolean

use of com.github.zhenwei.core.asn1.ASN1Boolean in project openkeystore by cyberphone.

the class CA method createCert.

public X509Certificate createCert(CertSpec certSpec, DistinguishedName issuerName, BigInteger serialNumber, Date startDate, Date endDate, AsymKeySignerInterface signer, PublicKey issuerPublicKey, PublicKey subjectPublicKey) throws IOException, GeneralSecurityException {
    Extensions extensions = new Extensions();
    BaseASN1Object version = new CompositeContextSpecific(0, new ASN1Integer(2));
    DistinguishedName subjectName = certSpec.getSubjectDistinguishedName();
    BaseASN1Object validity = new ASN1Sequence(new BaseASN1Object[] { getASN1Time(startDate), getASN1Time(endDate) });
    AsymSignatureAlgorithms certSignAlg = signer.getAlgorithm();
    BaseASN1Object signatureAlgorithm = new ASN1Sequence(certSignAlg.getKeyType() == KeyTypes.RSA ? new BaseASN1Object[] { new ASN1ObjectID(certSignAlg.getOid()), // Relic from the RSA hey-days...
    new ASN1Null() } : new BaseASN1Object[] { new ASN1ObjectID(certSignAlg.getOid()) });
    BaseASN1Object subjectPublicKeyInfo = DerDecoder.decode(subjectPublicKey.getEncoded());
    // ////////////////////////////////////////////////////
    if (certSpec.endEntity) {
        extensions.add(CertificateExtensions.BASIC_CONSTRAINTS, false, new ASN1Sequence(new BaseASN1Object[] {}));
    }
    // ////////////////////////////////////////////////////
    if (certSpec.caCert) {
        extensions.add(CertificateExtensions.BASIC_CONSTRAINTS, true, new ASN1Sequence(new ASN1Boolean(true)));
    }
    // ////////////////////////////////////////////////////
    if (!certSpec.keyUsageSet.isEmpty()) {
        int i = 0;
        for (KeyUsageBits kubit : certSpec.keyUsageSet) {
            i |= 1 << kubit.ordinal();
        }
        byte[] keyUsage = new byte[i > 255 ? 2 : 1];
        keyUsage[0] = reverseBits(i);
        if (i > 255) {
            keyUsage[1] = reverseBits(i >> 8);
        }
        extensions.add(CertificateExtensions.KEY_USAGE, true, new ASN1BitString(keyUsage));
    }
    // ////////////////////////////////////////////////////
    if (!certSpec.extendedKeyUsageSet.isEmpty()) {
        int i = 0;
        BaseASN1Object[] ekus = new BaseASN1Object[certSpec.extendedKeyUsageSet.size()];
        for (ExtendedKeyUsages eku : certSpec.extendedKeyUsageSet.toArray(new ExtendedKeyUsages[0])) {
            ekus[i++] = new ASN1ObjectID(eku.getOID());
        }
        extensions.add(CertificateExtensions.EXTENDED_KEY_USAGE, false, new ASN1Sequence(ekus));
    }
    // ////////////////////////////////////////////////////
    if (certSpec.skiExtension) {
        extensions.add(CertificateExtensions.SUBJECT_KEY_IDENTIFIER, createKeyID(subjectPublicKey));
    }
    // ////////////////////////////////////////////////////
    if (certSpec.akiExtension) {
        extensions.add(CertificateExtensions.AUTHORITY_KEY_IDENTIFIER, new ASN1Sequence(new SimpleContextSpecific(0, createKeyID(issuerPublicKey))));
    }
    // ////////////////////////////////////////////////////
    if (!certSpec.subjectAltName.isEmpty()) {
        int i = 0;
        BaseASN1Object[] san = new BaseASN1Object[certSpec.subjectAltName.size()];
        for (CertSpec.NameValue nameValue : certSpec.subjectAltName) {
            int type = nameValue.name;
            // We currently only handle simple IA5String types.
            if (type == SubjectAltNameTypes.RFC822_NAME || type == SubjectAltNameTypes.DNS_NAME || type == SubjectAltNameTypes.UNIFORM_RESOURCE_IDENTIFIER) {
                if (!(nameValue.value instanceof ASN1IA5String)) {
                    throw new IOException("Wrong argument type to SubjectAltNames of type " + type);
                }
            } else // Or IP addresses.
            if (type == SubjectAltNameTypes.IP_ADDRESS) {
                if (!(nameValue.value instanceof ASN1OctetString)) {
                    throw new IOException("Wrong argument type to SubjectAltNames of type IP address");
                }
            } else {
                throw new IOException("SubjectAltNames of type " + type + " are not handled.");
            }
            san[i++] = new SimpleContextSpecific(type, nameValue.value);
        }
        extensions.add(CertificateExtensions.SUBJECT_ALT_NAME, new ASN1Sequence(san));
    }
    // ////////////////////////////////////////////////////
    if (!certSpec.certPolicyOids.isEmpty()) {
        int i = 0;
        BaseASN1Object[] policies = new BaseASN1Object[certSpec.certPolicyOids.size()];
        for (String oid : certSpec.certPolicyOids) {
            policies[i++] = new ASN1Sequence(new ASN1ObjectID(oid));
        }
        extensions.add(CertificateExtensions.CERTIFICATE_POLICIES, new ASN1Sequence(policies));
    }
    // ////////////////////////////////////////////////////
    if (!certSpec.aiaLocators.isEmpty()) {
        int i = 0;
        BaseASN1Object[] locators = new BaseASN1Object[certSpec.aiaLocators.size()];
        for (String[] loc_info : certSpec.aiaLocators) {
            locators[i++] = new ASN1Sequence(new BaseASN1Object[] { new ASN1ObjectID(loc_info[0]), new SimpleContextSpecific(6, new ASN1IA5String(loc_info[1])) });
        }
        extensions.add(CertificateExtensions.AUTHORITY_INFO_ACCESS, new ASN1Sequence(locators));
    }
    // ////////////////////////////////////////////////////
    if (!certSpec.crlDistPoints.isEmpty()) {
        int i = 0;
        BaseASN1Object[] cdps = new BaseASN1Object[certSpec.crlDistPoints.size()];
        for (String uri : certSpec.crlDistPoints) {
            cdps[i++] = new ASN1Sequence(new CompositeContextSpecific(0, new CompositeContextSpecific(0, new SimpleContextSpecific(6, new ASN1IA5String(uri)))));
        }
        extensions.add(CertificateExtensions.CRL_DISTRIBUTION_POINTS, new ASN1Sequence(cdps));
    }
    // ////////////////////////////////////////////////////
    // Certificate Creation!
    // ////////////////////////////////////////////////////
    BaseASN1Object[] inner = new BaseASN1Object[extensions.isEmpty() ? 7 : 8];
    inner[0] = version;
    inner[1] = new ASN1Integer(serialNumber);
    inner[2] = signatureAlgorithm;
    inner[3] = issuerName.toASN1();
    inner[4] = validity;
    inner[5] = subjectName.toASN1();
    inner[6] = subjectPublicKeyInfo;
    if (!extensions.isEmpty()) {
        inner[7] = new CompositeContextSpecific(3, extensions.getExtensionData());
    }
    BaseASN1Object tbsCertificate = new ASN1Sequence(inner);
    BaseASN1Object signature = new ASN1BitString(signer.signData(tbsCertificate.encode()));
    byte[] certificate = new ASN1Sequence(new BaseASN1Object[] { tbsCertificate, signatureAlgorithm, signature }).encode();
    return CertificateUtil.getCertificateFromBlob(certificate);
}
Also used : ASN1OctetString(org.webpki.asn1.ASN1OctetString) KeyUsageBits(org.webpki.crypto.KeyUsageBits) DistinguishedName(org.webpki.asn1.cert.DistinguishedName) BaseASN1Object(org.webpki.asn1.BaseASN1Object) CompositeContextSpecific(org.webpki.asn1.CompositeContextSpecific) ASN1Integer(org.webpki.asn1.ASN1Integer) IOException(java.io.IOException) ASN1IA5String(org.webpki.asn1.ASN1IA5String) ASN1OctetString(org.webpki.asn1.ASN1OctetString) ASN1BitString(org.webpki.asn1.ASN1BitString) CertificateExtensions(org.webpki.crypto.CertificateExtensions) ExtendedKeyUsages(org.webpki.crypto.ExtendedKeyUsages) ASN1BitString(org.webpki.asn1.ASN1BitString) ASN1Sequence(org.webpki.asn1.ASN1Sequence) ASN1ObjectID(org.webpki.asn1.ASN1ObjectID) ASN1IA5String(org.webpki.asn1.ASN1IA5String) ASN1Boolean(org.webpki.asn1.ASN1Boolean) AsymSignatureAlgorithms(org.webpki.crypto.AsymSignatureAlgorithms) SimpleContextSpecific(org.webpki.asn1.SimpleContextSpecific) ASN1Null(org.webpki.asn1.ASN1Null)

Example 28 with ASN1Boolean

use of com.github.zhenwei.core.asn1.ASN1Boolean in project jruby-openssl by jruby.

the class X509Extension method initialize.

@JRubyMethod(name = "initialize", rest = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(final ThreadContext context, final IRubyObject[] args) {
    if (args.length == 1) {
        final byte[] bytes = to_der_if_possible(context, args[0]).asString().getBytes();
        try {
            ASN1Sequence seq = (ASN1Sequence) ASN1.readObject(bytes);
            setRealObjectID((ASN1ObjectIdentifier) seq.getObjectAt(0));
            final ASN1Encodable criticalOrValue = seq.getObjectAt(1);
            if (criticalOrValue instanceof ASN1Boolean) {
                setRealCritical(((ASN1Boolean) criticalOrValue).isTrue());
                // byte[]
                this.value = ((DEROctetString) seq.getObjectAt(2)).getOctets();
            } else {
                // byte[]
                this.value = ((DEROctetString) criticalOrValue).getOctets();
            }
        } catch (IOException e) {
            throw newExtensionError(context.runtime, e);
        }
    } else if (args.length > 1) {
        setRealObjectID(ASN1.getObjectID(context.runtime, args[0].toString()));
        // a RubyString
        this.value = args[1];
    } else {
        // args.length < 1
        throw context.runtime.newArgumentError("wrong number of arguments (0 for 1..3)");
    }
    if (args.length > 2)
        setRealCritical(args[2].isTrue());
    return this;
}
Also used : ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) ASN1Boolean(org.bouncycastle.asn1.ASN1Boolean) IOException(java.io.IOException) JRubyMethod(org.jruby.anno.JRubyMethod)

Example 29 with ASN1Boolean

use of com.github.zhenwei.core.asn1.ASN1Boolean in project LinLong-Java by zhenwei1108.

the class TimeStampTokenGenerator method generate.

/**
 * Generate a TimeStampToken for the passed in request and serialNumber marking it with the passed
 * in genTime.
 *
 * @param request              the originating request.
 * @param serialNumber         serial number for the TimeStampToken
 * @param genTime              token generation time.
 * @param additionalExtensions extra extensions to be added to the response token.
 * @return a TimeStampToken
 * @throws TSPException
 */
public TimeStampToken generate(TimeStampRequest request, BigInteger serialNumber, Date genTime, Extensions additionalExtensions) throws TSPException {
    AlgorithmIdentifier algID = request.getMessageImprintAlgID();
    MessageImprint messageImprint = new MessageImprint(algID, request.getMessageImprintDigest());
    Accuracy accuracy = null;
    if (accuracySeconds > 0 || accuracyMillis > 0 || accuracyMicros > 0) {
        ASN1Integer seconds = null;
        if (accuracySeconds > 0) {
            seconds = new ASN1Integer(accuracySeconds);
        }
        ASN1Integer millis = null;
        if (accuracyMillis > 0) {
            millis = new ASN1Integer(accuracyMillis);
        }
        ASN1Integer micros = null;
        if (accuracyMicros > 0) {
            micros = new ASN1Integer(accuracyMicros);
        }
        accuracy = new Accuracy(seconds, millis, micros);
    }
    ASN1Boolean derOrdering = null;
    if (ordering) {
        derOrdering = ASN1Boolean.getInstance(ordering);
    }
    ASN1Integer nonce = null;
    if (request.getNonce() != null) {
        nonce = new ASN1Integer(request.getNonce());
    }
    ASN1ObjectIdentifier tsaPolicy = tsaPolicyOID;
    if (request.getReqPolicy() != null) {
        tsaPolicy = request.getReqPolicy();
    }
    Extensions respExtensions = request.getExtensions();
    if (additionalExtensions != null) {
        ExtensionsGenerator extGen = new ExtensionsGenerator();
        if (respExtensions != null) {
            for (Enumeration en = respExtensions.oids(); en.hasMoreElements(); ) {
                extGen.addExtension(respExtensions.getExtension(ASN1ObjectIdentifier.getInstance(en.nextElement())));
            }
        }
        for (Enumeration en = additionalExtensions.oids(); en.hasMoreElements(); ) {
            extGen.addExtension(additionalExtensions.getExtension(ASN1ObjectIdentifier.getInstance(en.nextElement())));
        }
        respExtensions = extGen.generate();
    }
    ASN1GeneralizedTime timeStampTime;
    if (resolution == R_SECONDS) {
        timeStampTime = (locale == null) ? new ASN1GeneralizedTime(genTime) : new ASN1GeneralizedTime(genTime, locale);
    } else {
        timeStampTime = createGeneralizedTime(genTime);
    }
    TSTInfo tstInfo = new TSTInfo(tsaPolicy, messageImprint, new ASN1Integer(serialNumber), timeStampTime, accuracy, derOrdering, nonce, tsa, respExtensions);
    try {
        CMSSignedDataGenerator signedDataGenerator = new CMSSignedDataGenerator();
        if (request.getCertReq()) {
            // TODO: do we need to check certs non-empty?
            signedDataGenerator.addCertificates(new CollectionStore(certs));
            signedDataGenerator.addAttributeCertificates(new CollectionStore(attrCerts));
        }
        signedDataGenerator.addCRLs(new CollectionStore(crls));
        if (!otherRevoc.isEmpty()) {
            for (Iterator it = otherRevoc.keySet().iterator(); it.hasNext(); ) {
                ASN1ObjectIdentifier format = (ASN1ObjectIdentifier) it.next();
                signedDataGenerator.addOtherRevocationInfo(format, new CollectionStore((Collection) otherRevoc.get(format)));
            }
        }
        signedDataGenerator.addSignerInfoGenerator(signerInfoGen);
        byte[] derEncodedTSTInfo = tstInfo.getEncoded(ASN1Encoding.DER);
        CMSSignedData signedData = signedDataGenerator.generate(new CMSProcessableByteArray(PKCSObjectIdentifiers.id_ct_TSTInfo, derEncodedTSTInfo), true);
        return new TimeStampToken(signedData);
    } catch (CMSException cmsEx) {
        throw new TSPException("Error generating time-stamp token", cmsEx);
    } catch (IOException e) {
        throw new TSPException("Exception encoding info", e);
    }
}
Also used : CMSSignedDataGenerator(com.github.zhenwei.pkix.cms.CMSSignedDataGenerator) CMSProcessableByteArray(com.github.zhenwei.pkix.cms.CMSProcessableByteArray) Enumeration(java.util.Enumeration) MessageImprint(com.github.zhenwei.pkix.util.asn1.tsp.MessageImprint) ASN1GeneralizedTime(com.github.zhenwei.core.asn1.ASN1GeneralizedTime) ASN1Integer(com.github.zhenwei.core.asn1.ASN1Integer) IOException(java.io.IOException) Extensions(com.github.zhenwei.core.asn1.x509.Extensions) CMSSignedData(com.github.zhenwei.pkix.cms.CMSSignedData) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) ExtensionsGenerator(com.github.zhenwei.core.asn1.x509.ExtensionsGenerator) Accuracy(com.github.zhenwei.pkix.util.asn1.tsp.Accuracy) TSTInfo(com.github.zhenwei.pkix.util.asn1.tsp.TSTInfo) Iterator(java.util.Iterator) Collection(java.util.Collection) ASN1Boolean(com.github.zhenwei.core.asn1.ASN1Boolean) CollectionStore(com.github.zhenwei.core.util.CollectionStore) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier) CMSException(com.github.zhenwei.pkix.cms.CMSException)

Example 30 with ASN1Boolean

use of com.github.zhenwei.core.asn1.ASN1Boolean in project LinLong-Java by zhenwei1108.

the class AlgorithmParametersSpi method engineInit.

protected void engineInit(byte[] params) throws IOException {
    try {
        ASN1Sequence s = (ASN1Sequence) ASN1Primitive.fromByteArray(params);
        if (s.size() > 5) {
            throw new IOException("sequence too big");
        }
        byte[] derivationV = null;
        byte[] encodingV = null;
        BigInteger macKeySize = null;
        BigInteger keySize = null;
        byte[] nonce = null;
        boolean pointCompression = false;
        for (Enumeration en = s.getObjects(); en.hasMoreElements(); ) {
            Object o = en.nextElement();
            if (o instanceof ASN1TaggedObject) {
                ASN1TaggedObject t = ASN1TaggedObject.getInstance(o);
                if (t.getTagNo() == 0) {
                    derivationV = ASN1OctetString.getInstance(t, false).getOctets();
                } else if (t.getTagNo() == 1) {
                    encodingV = ASN1OctetString.getInstance(t, false).getOctets();
                }
            } else if (o instanceof ASN1Integer) {
                macKeySize = ASN1Integer.getInstance(o).getValue();
            } else if (o instanceof ASN1Sequence) {
                ASN1Sequence seq = ASN1Sequence.getInstance(o);
                keySize = ASN1Integer.getInstance(seq.getObjectAt(0)).getValue();
                nonce = ASN1OctetString.getInstance(seq.getObjectAt(1)).getOctets();
            } else if (o instanceof ASN1Boolean) {
                pointCompression = ASN1Boolean.getInstance(o).isTrue();
            }
        }
        if (keySize != null) {
            this.currentSpec = new IESParameterSpec(derivationV, encodingV, macKeySize.intValue(), keySize.intValue(), nonce, pointCompression);
        } else {
            this.currentSpec = new IESParameterSpec(derivationV, encodingV, macKeySize.intValue(), -1, null, pointCompression);
        }
    } catch (ClassCastException e) {
        throw new IOException("Not a valid IES Parameter encoding.");
    } catch (ArrayIndexOutOfBoundsException e) {
        throw new IOException("Not a valid IES Parameter encoding.");
    }
}
Also used : Enumeration(java.util.Enumeration) ASN1TaggedObject(com.github.zhenwei.core.asn1.ASN1TaggedObject) IESParameterSpec(com.github.zhenwei.provider.jce.spec.IESParameterSpec) IOException(java.io.IOException) ASN1Integer(com.github.zhenwei.core.asn1.ASN1Integer) ASN1Sequence(com.github.zhenwei.core.asn1.ASN1Sequence) BigInteger(java.math.BigInteger) ASN1TaggedObject(com.github.zhenwei.core.asn1.ASN1TaggedObject) DERTaggedObject(com.github.zhenwei.core.asn1.DERTaggedObject) ASN1Boolean(com.github.zhenwei.core.asn1.ASN1Boolean)

Aggregations

ASN1Boolean (com.unboundid.asn1.ASN1Boolean)51 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)51 ASN1Sequence (com.unboundid.asn1.ASN1Sequence)51 ASN1Element (com.unboundid.asn1.ASN1Element)38 NotNull (com.unboundid.util.NotNull)32 ArrayList (java.util.ArrayList)32 ASN1Integer (com.unboundid.asn1.ASN1Integer)15 Test (org.testng.annotations.Test)14 ASN1Enumerated (com.unboundid.asn1.ASN1Enumerated)12 ASN1Boolean (com.github.zhenwei.core.asn1.ASN1Boolean)5 Nullable (com.unboundid.util.Nullable)5 IOException (java.io.IOException)5 ASN1Integer (com.github.zhenwei.core.asn1.ASN1Integer)4 ASN1Sequence (com.github.zhenwei.core.asn1.ASN1Sequence)4 ASN1TaggedObject (com.github.zhenwei.core.asn1.ASN1TaggedObject)4 ASN1Set (com.unboundid.asn1.ASN1Set)4 DERTaggedObject (com.github.zhenwei.core.asn1.DERTaggedObject)3 ASN1Long (com.unboundid.asn1.ASN1Long)3 Control (com.unboundid.ldap.sdk.Control)3 ASN1Boolean (org.bouncycastle.asn1.ASN1Boolean)3