Example usage for org.bouncycastle.asn1 ASN1Integer ASN1Integer

List of usage examples for org.bouncycastle.asn1 ASN1Integer ASN1Integer

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1Integer ASN1Integer.

Prototype

public ASN1Integer(byte[] bytes) 

Source Link

Document

Construct an INTEGER from the passed in byte array.

Usage

From source file:net.sf.keystore_explorer.crypto.publickey.KeyIdentifierGenerator.java

License:Open Source License

private byte[] encodeDsaPublicKeyAsBitString(DSAPublicKey dsaPublicKey) throws IOException {
    ASN1Integer publicKey = new ASN1Integer(dsaPublicKey.getY());

    return publicKey.getEncoded(ASN1Encoding.DER);
}

From source file:net.sf.keystore_explorer.crypto.x509.InhibitAnyPolicy.java

License:Open Source License

@Override
public ASN1Primitive toASN1Primitive() {
    return new ASN1Integer(skipCerts);
}

From source file:net.sf.keystore_explorer.crypto.x509.PolicyConstraints.java

License:Open Source License

@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector vec = new ASN1EncodableVector();

    if (requireExplicitPolicy != -1) {
        vec.add(new DERTaggedObject(0, new ASN1Integer(requireExplicitPolicy)));
    }/*ww  w . j ava 2s .c  om*/

    if (inhibitPolicyMapping != -1) {
        vec.add(new DERTaggedObject(1, new ASN1Integer(inhibitPolicyMapping)));
    }

    return new DERSequence(vec);
}

From source file:net.sf.keystore_explorer.gui.crypto.policyinformation.DUserNoticeChooser.java

License:Open Source License

private void okPressed() {

    String organizationString = jtfOrganization.getText().trim();
    int[] noticeNumberInts = extractNoticeNumbers();
    String explicitTextString = jtfExplicitText.getText().trim();

    if (noticeNumberInts == null) {
        JOptionPane.showMessageDialog(this, res.getString("DUserNoticeChooser.InvalidNoticeNumbers.message"),
                getTitle(), JOptionPane.WARNING_MESSAGE);
        return;//from w w  w .  ja v  a 2  s . c  o  m
    }

    if (((organizationString.length() > 0) && (noticeNumberInts.length == 0))
            || ((organizationString.length() == 0) && (noticeNumberInts.length > 0))) {
        JOptionPane.showMessageDialog(this,
                res.getString("DUserNoticeChooser.OrganizationOrNoticeNumbersValueReq.message"), getTitle(),
                JOptionPane.WARNING_MESSAGE);
        return;
    }

    if ((organizationString.length() == 0) && (noticeNumberInts.length == 0)
            && (explicitTextString.length() == 0)) {
        JOptionPane.showMessageDialog(this,
                res.getString("DUserNoticeChooser.NoticeRefOrExplicitTextValueReq.message"), getTitle(),
                JOptionPane.WARNING_MESSAGE);
        return;
    }

    NoticeReference noticeReference = null;
    if (organizationString.length() > 0) { // If organization is present then so is al of notice reference

        Vector<ASN1Integer> noticeNumbers = new Vector<ASN1Integer>();

        for (int noticeNumber : noticeNumberInts) {
            noticeNumbers.add(new ASN1Integer(noticeNumber));
        }

        noticeReference = new NoticeReference(organizationString, noticeNumbers);
    }

    userNotice = new UserNotice(noticeReference, explicitTextString);

    closeDialog();
}

From source file:net.sf.portecle.crypto.X509Ext.java

License:Open Source License

/**
 * Get Policy Constraints (2.5.29.36) extension value as a string.
 * // ww  w  .j  a v a  2 s  .  co m
 * <pre>
 * PolicyConstraints ::= SEQUENCE {
 *     requireExplicitPolicy           [0] SkipCerts OPTIONAL,
 *     inhibitPolicyMapping            [1] SkipCerts OPTIONAL }
 * SkipCerts ::= INTEGER (0..MAX)
 * </pre>
 * 
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 */
private String getPolicyConstraintsStringValue(byte[] bValue) throws IOException {
    // Get sequence of policy constraint
    ASN1Sequence policyConstraints = (ASN1Sequence) ASN1Primitive.fromByteArray(bValue);

    StringBuilder strBuff = new StringBuilder();

    for (int i = 0, len = policyConstraints.size(); i < len; i++) {
        DERTaggedObject policyConstraint = (DERTaggedObject) policyConstraints.getObjectAt(i);
        ASN1Integer skipCerts = new ASN1Integer(((DEROctetString) policyConstraint.getObject()).getOctets());
        int iSkipCerts = skipCerts.getValue().intValue();

        switch (policyConstraint.getTagNo()) {
        case 0: // Require Explicit Policy Skip Certs
            if (strBuff.length() != 0) {
                strBuff.append("<br><br>");
            }
            strBuff.append(MessageFormat.format(RB.getString("RequireExplicitPolicy"), iSkipCerts));
            break;
        case 1: // Inhibit Policy Mapping Skip Certs
            if (strBuff.length() != 0) {
                strBuff.append("<br><br>");
            }
            strBuff.append(MessageFormat.format(RB.getString("InhibitPolicyMapping"), iSkipCerts));
            break;
        }
    }

    return strBuff.toString();

}

From source file:org.certificateservices.custom.c2x.its.crypto.DefaultCryptoManager.java

License:Open Source License

/**
 * @see org.certificateservices.custom.c2x.its.crypto.CryptoManager#verifySignature(byte[], Signature, PublicKey)
 *//*from  w w w .ja v a  2 s.com*/
@Override
public boolean verifySignature(byte[] message, Signature signature, PublicKey publicKey)
        throws IllegalArgumentException, SignatureException, IOException {
    PublicKeyAlgorithm alg = signature.getPublicKeyAlgorithm();

    if (alg == PublicKeyAlgorithm.ecdsa_nistp256_with_sha256) {
        try {
            EcdsaSignature ecdsaSignature = signature.getSignatureValue();

            // Create Signature Data
            ASN1Integer asn1R = new ASN1Integer(ecdsaSignature.getR().getX());
            ASN1Integer asn1S = new ASN1Integer(SerializationHelper.readFixedFieldSizeKey(alg,
                    new ByteArrayInputStream(ecdsaSignature.getSignatureValue())));
            DLSequence dLSequence = new DLSequence(new ASN1Encodable[] { asn1R, asn1S });
            byte[] dERSignature = dLSequence.getEncoded();

            byte[] messageDigest = digest(message, alg);

            java.security.Signature sig = java.security.Signature.getInstance("NONEwithECDSA", provider);
            sig.initVerify(publicKey);
            sig.update(messageDigest);
            return sig.verify(dERSignature);
        } catch (Exception e) {
            if (e instanceof IllegalArgumentException) {
                throw (IllegalArgumentException) e;
            }
            if (e instanceof IOException) {
                throw (IOException) e;
            }
            if (e instanceof SignatureException) {
                throw (SignatureException) e;
            }

            throw new SignatureException("Internal error verifying signature " + e.getClass().getSimpleName()
                    + ": " + e.getMessage(), e);
        }

    } else {
        throw new IllegalArgumentException(
                "Unsupported signature algoritm: " + signature.getPublicKeyAlgorithm());
    }
}

From source file:org.cesecore.certificates.ca.X509CA.java

License:Open Source License

/**
 * Constructs the SubjectAlternativeName extension that will end up on the generated certificate.
 * //from  w w  w.j  a v a 2 s .  c  om
 * If the DNS values in the subjectAlternativeName extension contain parentheses to specify labels that should be redacted, the parentheses are removed and another extension 
 * containing the number of redacted labels is added.
 * 
 * @param subAltNameExt
 * @param publishToCT
 * @return An extension generator containing the SubjectAlternativeName extension and an extension holding the number of redacted labels if the certificate is to be published 
 * to a CTLog
 * @throws IOException
 */
private ExtensionsGenerator getSubjectAltNameExtensionForCert(Extension subAltNameExt, boolean publishToCT)
        throws IOException {
    String subAltName = CertTools.getAltNameStringFromExtension(subAltNameExt);
    List<String> dnsValues = CertTools.getPartsFromDN(subAltName, CertTools.DNS);
    int[] nrOfRecactedLables = new int[dnsValues.size()];
    boolean sanEdited = false;
    int i = 0;
    for (String dns : dnsValues) {
        if (StringUtils.contains(dns, "(") && StringUtils.contains(dns, ")")) { // if it contains parts that should be redacted
            // Remove the parentheses from the SubjectAltName that will end up on the certificate
            String certBuilderDNSValue = StringUtils.remove(dns, '(');
            certBuilderDNSValue = StringUtils.remove(certBuilderDNSValue, ')');
            subAltName = StringUtils.replace(subAltName, dns, certBuilderDNSValue);
            sanEdited = true;
            if (publishToCT) {
                String redactedLable = StringUtils.substring(dns, StringUtils.indexOf(dns, "("),
                        StringUtils.lastIndexOf(dns, ")") + 1); // tex. (top.secret).domain.se => redactedLable = (top.secret) aka. including the parentheses 
                nrOfRecactedLables[i] = StringUtils.countMatches(redactedLable, ".") + 1;
            }
        }
        i++;
    }
    ExtensionsGenerator gen = new ExtensionsGenerator();
    gen.addExtension(Extension.subjectAlternativeName, subAltNameExt.isCritical(),
            CertTools.getGeneralNamesFromAltName(subAltName));
    // If there actually are redacted parts, add the extension containing the number of redacted lables to the certificate 
    if (publishToCT && sanEdited) {
        ASN1EncodableVector v = new ASN1EncodableVector();
        for (int val : nrOfRecactedLables) {
            v.add(new ASN1Integer(val));
        }
        ASN1Encodable seq = new DERSequence(v);
        gen.addExtension(new ASN1ObjectIdentifier("1.3.6.1.4.1.11129.2.4.6"), false, seq);
    }

    return gen;
}

From source file:org.cesecore.certificates.certificate.certextensions.BasicCertificateExtension.java

License:Open Source License

private ASN1Encodable parseDERInteger(String value) throws CertificateExtensionException {
    ASN1Encodable retval = null;//from ww  w  . j  av a2 s  .  c om
    try {
        BigInteger intValue = new BigInteger(value, 10);
        retval = new ASN1Integer(intValue);
    } catch (NumberFormatException e) {
        throw new CertificateExtensionException(intres.getLocalizedMessage("certext.basic.illegalvalue", value,
                Integer.valueOf(getId()), getOID()));
    }

    return retval;
}

From source file:org.cesecore.certificates.certificate.certextensions.standard.DocumentTypeList.java

License:Open Source License

@Override
public ASN1Encodable getValue(final EndEntityInformation subject, final CA ca,
        final CertificateProfile certProfile, final PublicKey userPublicKey, final PublicKey caPublicKey,
        CertificateValidity val) {

    ArrayList<String> docTypes = certProfile.getDocumentTypeList();
    if (docTypes.size() == 0) {
        if (log.isDebugEnabled()) {
            log.debug("No DocumentTypeList to make a certificate extension");
        }//from  w  ww .  j a v  a2s .c  om
        return null;
    }

    ASN1EncodableVector vec = new ASN1EncodableVector();

    // version
    vec.add(new ASN1Integer(0));

    // Add SET OF DocumentType
    Iterator<String> itr = docTypes.iterator();
    while (itr.hasNext()) {
        String type = itr.next();
        vec.add(new DERSet(new ASN1Encodable[] { new DERPrintableString(type) }));
    }

    ASN1Object gn = new DERSequence(vec);
    if (log.isDebugEnabled()) {
        log.debug("Constructed DocumentTypeList:");
        log.debug(ASN1Dump.dumpAsString(gn, true));
    }

    return gn;
}

From source file:org.cesecore.certificates.certificate.certextensions.standard.QcStatement.java

License:Open Source License

@Override
public ASN1Encodable getValue(final EndEntityInformation subject, final CA ca,
        final CertificateProfile certProfile, final PublicKey userPublicKey, final PublicKey caPublicKey,
        CertificateValidity val) throws CertificateExtensionException {
    DERSequence ret = null;/*w w w  .  j  ava2s  . c om*/
    final String names = certProfile.getQCStatementRAName();
    final GeneralNames san = CertTools.getGeneralNamesFromAltName(names);
    SemanticsInformation si = null;
    if (san != null) {
        if (StringUtils.isNotEmpty(certProfile.getQCSemanticsId())) {
            si = new SemanticsInformation(new ASN1ObjectIdentifier(certProfile.getQCSemanticsId()),
                    san.getNames());
        } else {
            si = new SemanticsInformation(san.getNames());
        }
    } else if (StringUtils.isNotEmpty(certProfile.getQCSemanticsId())) {
        si = new SemanticsInformation(new ASN1ObjectIdentifier(certProfile.getQCSemanticsId()));
    }
    final ArrayList<QCStatement> qcs = new ArrayList<QCStatement>();
    QCStatement qc = null;
    // First the standard rfc3739 QCStatement with an optional SematicsInformation
    // We never add RFC3739QCObjectIdentifiers.id_qcs_pkixQCSyntax_v1. This is so old so we think it has never been used in the wild basically.
    // That means no need to have code we have to maintain for that.
    if (certProfile.getUsePkixQCSyntaxV2()) {
        ASN1ObjectIdentifier pkixQcSyntax = RFC3739QCObjectIdentifiers.id_qcs_pkixQCSyntax_v2;
        if ((si != null)) {
            qc = new QCStatement(pkixQcSyntax, si);
            qcs.add(qc);
        } else {
            qc = new QCStatement(pkixQcSyntax);
            qcs.add(qc);
        }
    }
    // ETSI Statement that the certificate is a Qualified Certificate
    if (certProfile.getUseQCEtsiQCCompliance()) {
        qc = new QCStatement(ETSIQCObjectIdentifiers.id_etsi_qcs_QcCompliance);
        qcs.add(qc);
    }
    // ETSI Statement regarding limit on the value of transactions
    // Both value and currency must be available for this extension
    if (certProfile.getUseQCEtsiValueLimit() && (certProfile.getQCEtsiValueLimit() >= 0)
            && (certProfile.getQCEtsiValueLimitCurrency() != null)) {
        final int limit = certProfile.getQCEtsiValueLimit();
        // The exponent should be default 0
        final int exponent = certProfile.getQCEtsiValueLimitExp();
        final MonetaryValue value = new MonetaryValue(
                new Iso4217CurrencyCode(certProfile.getQCEtsiValueLimitCurrency()), limit, exponent);
        qc = new QCStatement(ETSIQCObjectIdentifiers.id_etsi_qcs_LimiteValue, value);
        qcs.add(qc);
    }

    if (certProfile.getUseQCEtsiRetentionPeriod()) {
        final ASN1Integer years = new ASN1Integer(((Integer) certProfile.getQCEtsiRetentionPeriod()));
        qc = new QCStatement(ETSIQCObjectIdentifiers.id_etsi_qcs_RetentionPeriod, years);
        qcs.add(qc);
    }

    // ETSI Statement claiming that the private key resides in a Signature Creation Device
    if (certProfile.getUseQCEtsiSignatureDevice()) {
        qc = new QCStatement(ETSIQCObjectIdentifiers.id_etsi_qcs_QcSSCD);
        qcs.add(qc);
    }
    // Custom UTF8String QC-statement:
    // qcStatement-YourCustom QC-STATEMENT ::= { SYNTAX YourCustomUTF8String
    //   IDENTIFIED BY youroid }
    //   -- This statement gives you the possibility to define your own QC-statement
    //   -- using an OID and a simple UTF8String, with describing text. A sample text could for example be:
    //   -- This certificate, according to Act. No. xxxx Electronic Signature Law is a qualified electronic certificate
    //
    // YourCustomUTF8String ::= UTF8String
    if (certProfile.getUseQCCustomString() && !StringUtils.isEmpty(certProfile.getQCCustomStringOid())
            && !StringUtils.isEmpty(certProfile.getQCCustomStringText())) {
        final DERUTF8String str = new DERUTF8String(certProfile.getQCCustomStringText());
        final ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(certProfile.getQCCustomStringOid());
        qc = new QCStatement(oid, str);
        qcs.add(qc);
    }
    if (!qcs.isEmpty()) {
        final ASN1EncodableVector vec = new ASN1EncodableVector();
        final Iterator<QCStatement> iter = qcs.iterator();
        while (iter.hasNext()) {
            final QCStatement q = (QCStatement) iter.next();
            vec.add(q);
        }
        ret = new DERSequence(vec);
    }
    if (ret == null) {
        log.error(
                "Qualified certificate statements extension has been enabled, but no statements were included!");
        throw new CertificateExtensionException(
                "If qualified certificate statements extension has been enabled, at least one statement must be included!");
    }
    return ret;
}