Example usage for org.bouncycastle.asn1 ASN1Sequence getObjectAt

List of usage examples for org.bouncycastle.asn1 ASN1Sequence getObjectAt

Introduction

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

Prototype

public ASN1Encodable getObjectAt(int index) 

Source Link

Document

Return the object at the sequence position indicated by index.

Usage

From source file:org.cagrid.security.ssl.proxy.trust.ProxyPolicy.java

License:Open Source License

/**
 * Creates a new instance of the ProxyPolicy object from given ASN1Sequence
 * object.//from   ww w.  j  a va  2s.  c o m
 * 
 * @param seq
 *            ASN1Sequence object to create the instance from.
 */
public ProxyPolicy(ASN1Sequence seq) {
    if (seq.size() < 1) {
        throw new IllegalArgumentException("Invalid sequence");
    }
    this.policyLanguage = (DERObjectIdentifier) seq.getObjectAt(0);
    if (seq.size() > 1) {
        DEREncodable obj = seq.getObjectAt(1);
        if (obj instanceof DERTaggedObject) {
            obj = ((DERTaggedObject) obj).getObject();
        }
        this.policy = (DEROctetString) obj;
    }
    checkConstraints();
}

From source file:org.ccnx.ccn.impl.security.crypto.MerklePath.java

License:Open Source License

/**
 * Decode a DER encoded MerklePath//from   ww w . jav a 2  s  . com
 * @param derEncodedPath the encoded path
 * @throws CertificateEncodingException if there is a decoding error
 */
public MerklePath(byte[] derEncodedPath) throws CertificateEncodingException {
    DERObject decoded = CryptoUtil.decode(derEncodedPath);
    ASN1Sequence seq = (ASN1Sequence) decoded;
    DERInteger intVal = (DERInteger) seq.getObjectAt(0);
    _leafNodeIndex = intVal.getValue().intValue();
    ASN1Sequence seqOf = (ASN1Sequence) seq.getObjectAt(1);
    _path = new DEROctetString[seqOf.size()];
    Enumeration<?> en = seqOf.getObjects();
    int i = 0;
    while (en.hasMoreElements()) {
        _path[i++] = (DEROctetString) en.nextElement();
    }
}

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

License:Open Source License

/** 
 * Test that the CA can issue certificates with custom certificate extensions.
 */// w  ww .  j  ava  2  s.  co  m
@Test
public void testCustomCertificateExtension() throws Exception {
    final CryptoToken cryptoToken = getNewCryptoToken();
    X509CA testCa = createTestCA(cryptoToken, "CN=foo");
    Collection<RevokedCertInfo> revcerts = new ArrayList<RevokedCertInfo>();
    X509CRLHolder testCrl = testCa.generateCRL(cryptoToken, revcerts, 0);
    assertNotNull(testCrl);
    X509CRL xcrl = CertTools.getCRLfromByteArray(testCrl.getEncoded());
    Collection<String> result = CertTools.getAuthorityInformationAccess(xcrl);
    assertEquals("A list was returned without any values present.", 0, result.size());
    // Issue a certificate with two different basic certificate extensions
    EndEntityInformation user = new EndEntityInformation("username", "CN=User", 666, "rfc822Name=user@user.com",
            "user@user.com", new EndEntityType(EndEntityTypes.ENDUSER), 0, 0, EndEntityConstants.TOKEN_USERGEN,
            0, null);
    CertificateProfile cp = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    // Configure some custom basic certificate extension
    // one with a good IA5String encoding
    Properties prop = new Properties();
    prop.put("id1.oid", "2.16.840.1.113730.1.13");
    prop.put("id1.classpath", "org.cesecore.certificates.certificate.certextensions.BasicCertificateExtension");
    prop.put("id1.displayname", "NetscapeComment");
    prop.put("id1.used", "true");
    prop.put("id1.translatable", "false");
    prop.put("id1.critical", "false");
    prop.put("id1.property.encoding", "DERIA5STRING");
    prop.put("id1.property.dynamin", "false");
    prop.put("id1.property.value", "Hello World");
    // one RAW with proper DER encoding
    prop.put("id2.oid", "1.2.3.4");
    prop.put("id2.classpath", "org.cesecore.certificates.certificate.certextensions.BasicCertificateExtension");
    prop.put("id2.displayname", "RawProper");
    prop.put("id2.used", "true");
    prop.put("id2.translatable", "false");
    prop.put("id2.critical", "false");
    prop.put("id2.property.encoding", "RAW");
    prop.put("id2.property.dynamin", "false");
    prop.put("id2.property.value", "301a300c060a2b060104018237140202300a06082b06010505070302");
    // one RAW with no DER encoding (actually invalid according to RFC5280)
    prop.put("id3.oid", "1.2.3.5");
    prop.put("id3.classpath", "org.cesecore.certificates.certificate.certextensions.BasicCertificateExtension");
    prop.put("id3.displayname", "RawNoDer");
    prop.put("id3.used", "true");
    prop.put("id3.translatable", "false");
    prop.put("id3.critical", "false");
    prop.put("id3.property.encoding", "RAW");
    prop.put("id3.property.dynamin", "false");
    prop.put("id3.property.value", "aabbccddeeff00");
    // Load the Custom extensions
    Field certificateExtensionFactoryInstance = CertificateExtensionFactory.class.getDeclaredField("instance");
    certificateExtensionFactoryInstance.setAccessible(true);
    Method parseConfiguration = CertificateExtensionFactory.class.getDeclaredMethod("parseConfiguration",
            Properties.class);
    parseConfiguration.setAccessible(true);
    CertificateExtensionFactory instance = (CertificateExtensionFactory) parseConfiguration.invoke(null, prop);
    certificateExtensionFactoryInstance.set(null, instance);
    CertificateExtensionFactory fact = CertificateExtensionFactory.getInstance();
    assertEquals(fact.getCertificateExtensions(1).getOID(), "2.16.840.1.113730.1.13");
    assertEquals(fact.getCertificateExtensions(2).getOID(), "1.2.3.4");
    assertEquals(fact.getCertificateExtensions(3).getOID(), "1.2.3.5");
    // Configure to use the custom extensions in the certificate profile
    List<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(2);
    list.add(3);
    cp.setUsedCertificateExtensions(list);
    final KeyPair keypair = KeyTools.genKeys("512", "RSA");
    X509Certificate cert = (X509Certificate) testCa.generateCertificate(cryptoToken, user, keypair.getPublic(),
            0, null, 10L, cp, "00000");
    assertNotNull("A certificate should have been issued", cert);
    byte[] ext1 = cert.getExtensionValue("2.16.840.1.113730.1.13");
    // The Extension value is an Octet String, containing my value
    ASN1InputStream is = new ASN1InputStream(ext1);
    ASN1OctetString oct = (ASN1OctetString) (is.readObject());
    is.close();
    ASN1InputStream is2 = new ASN1InputStream(oct.getOctets());
    DERIA5String str = (DERIA5String) is2.readObject();
    is2.close();
    assertEquals("Hello World", str.getString());

    byte[] ext2 = cert.getExtensionValue("1.2.3.4");
    is = new ASN1InputStream(ext2);
    oct = (ASN1OctetString) (is.readObject());
    is.close();
    is2 = new ASN1InputStream(oct.getOctets());
    ASN1Sequence seq = (ASN1Sequence) is2.readObject();
    System.out.println(ASN1Dump.dumpAsString(seq));
    is2.close();
    ASN1Encodable enc = seq.getObjectAt(0);
    ASN1Sequence seq2 = ASN1Sequence.getInstance(enc);
    ASN1Encodable enc2 = seq2.getObjectAt(0);
    ASN1ObjectIdentifier id = ASN1ObjectIdentifier.getInstance(enc2);
    assertEquals("1.3.6.1.4.1.311.20.2.2", id.getId());
    enc = seq.getObjectAt(1);
    seq2 = ASN1Sequence.getInstance(enc);
    enc2 = seq2.getObjectAt(0);
    id = ASN1ObjectIdentifier.getInstance(enc2);
    assertEquals("1.3.6.1.5.5.7.3.2", id.getId());

    byte[] ext3 = cert.getExtensionValue("1.2.3.5");
    is = new ASN1InputStream(ext3);
    oct = (ASN1OctetString) (is.readObject());
    is.close();
    // This value can not be parsed as ASN.1
    byte[] bytes = oct.getOctets();
    assertEquals("aabbccddeeff00", Hex.toHexString(bytes));
}

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

License:Open Source License

@Test
public void testQcStatement() throws CertificateExtensionException, IOException {
    CertificateProfile prof = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    prof.setUseQCStatement(true);//w  w w  .  ja va 2s.  c  o m
    prof.setUseQCEtsiQCCompliance(true);
    prof.setUseQCEtsiSignatureDevice(true);
    prof.setQCEtsiType("0.4.0.1862.1.6.1");
    prof.setQCEtsiPds(Arrays.asList(new PKIDisclosureStatement("http://qcs.localhost/QcPDS", "en")));
    QcStatement statement = new QcStatement();
    byte[] value = statement.getValueEncoded(null, null, prof, null, null, null);
    @SuppressWarnings("resource")
    final String dump = ASN1Dump.dumpAsString(new ASN1InputStream(value).readObject(), true);
    log.info(dump);
    // Hex dump can be used in Custom Certificate Extensions
    log.info(new String(Hex.encode(value)));
    // Dump included IDs
    final ASN1Sequence seq = (ASN1Sequence) ASN1Sequence.fromByteArray(value);
    // This is just a loop to get all the statement IDs in the QcStatements extension, so we can view them and count them
    ArrayList<String> oids = new ArrayList<>();
    for (int i = 0; i < seq.size(); i++) {
        final QCStatement qc = QCStatement.getInstance(seq.getObjectAt(i));
        final ASN1ObjectIdentifier oid = qc.getStatementId();
        if (oid != null) {
            oids.add(oid.getId());
        } else {
            fail("QC statements have empty statement");
        }
    }
    log.info(oids);
    // Check that all OIDs we set exist
    assertEquals("Not all QC statement Ids were included", 4, oids.size());
    assertTrue(oids.contains(ETSIQCObjectIdentifiers.id_etsi_qcs_QcCompliance.getId()));
    assertTrue(oids.contains(ETSIQCObjectIdentifiers.id_etsi_qcs_QcSSCD.getId()));
    assertTrue(oids.contains("0.4.0.1862.1.6")); // ETSIQCObjectIdentifiers.id_etsi_qcs_QcType
    assertTrue(oids.contains("0.4.0.1862.1.5")); // ETSIQCObjectIdentifiers.id_etsi_qcs_QcPds
    // Check the values we set
    assertEquals("0.4.0.1862.1.6.1", QCStatementExtension.getStatementStringValue(seq, "0.4.0.1862.1.6", 0));
    assertEquals("[http://qcs.localhost/QcPDS, en]",
            QCStatementExtension.getStatementStringValue(seq, "0.4.0.1862.1.5", 0));

}

From source file:org.cesecore.certificates.certificate.request.RequestMessageUtils.java

License:Open Source License

public static RequestMessage getSimpleRequestMessageFromType(final String username, final String password,
        final String req, final int reqType) throws SignRequestSignatureException, InvalidKeyException,
        NoSuchAlgorithmException, NoSuchProviderException, IOException, SignatureException,
        InvalidKeySpecException, ParseException, ConstructionException, NoSuchFieldException {
    RequestMessage ret = null;//w  w w  . j  av  a  2  s.  c o  m
    if (reqType == CertificateConstants.CERT_REQ_TYPE_PKCS10) {
        final RequestMessage pkcs10req = RequestMessageUtils.genPKCS10RequestMessage(req.getBytes());
        final PublicKey pubKey = pkcs10req.getRequestPublicKey();
        SimpleRequestMessage simplereq = new SimpleRequestMessage(pubKey, username, password);
        final Extensions ext = pkcs10req.getRequestExtensions();
        simplereq.setRequestExtensions(ext);
        ret = simplereq;
    } else if (reqType == CertificateConstants.CERT_REQ_TYPE_SPKAC) {
        byte[] reqBytes = req.getBytes();
        if (reqBytes != null) {
            if (log.isDebugEnabled()) {
                log.debug("Received NS request: " + new String(reqBytes));
            }
            byte[] buffer = Base64.decode(reqBytes);
            if (buffer == null) {
                return null;
            }
            ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(buffer));
            ASN1Sequence spkacSeq = (ASN1Sequence) in.readObject();
            in.close();
            NetscapeCertRequest nscr = new NetscapeCertRequest(spkacSeq);
            // Verify POPO, we don't care about the challenge, it's not important.
            nscr.setChallenge("challenge");
            if (nscr.verify("challenge") == false) {
                if (log.isDebugEnabled()) {
                    log.debug("SPKAC POPO verification Failed");
                }
                throw new SignRequestSignatureException(
                        "Invalid signature in NetscapeCertRequest, popo-verification failed.");
            }
            if (log.isDebugEnabled()) {
                log.debug("POPO verification successful");
            }
            PublicKey pubKey = nscr.getPublicKey();
            ret = new SimpleRequestMessage(pubKey, username, password);
        }
    } else if (reqType == CertificateConstants.CERT_REQ_TYPE_CRMF) {
        byte[] request = Base64.decode(req.getBytes());
        ASN1InputStream in = new ASN1InputStream(request);
        try {
            ASN1Sequence crmfSeq = (ASN1Sequence) in.readObject();
            ASN1Sequence reqSeq = (ASN1Sequence) ((ASN1Sequence) crmfSeq.getObjectAt(0)).getObjectAt(0);
            CertRequest certReq = CertRequest.getInstance(reqSeq);
            SubjectPublicKeyInfo pKeyInfo = certReq.getCertTemplate().getPublicKey();
            KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC");
            KeySpec keySpec = new X509EncodedKeySpec(pKeyInfo.getEncoded());
            PublicKey pubKey = keyFact.generatePublic(keySpec); // just check it's ok
            SimpleRequestMessage simplereq = new SimpleRequestMessage(pubKey, username, password);
            Extensions ext = certReq.getCertTemplate().getExtensions();
            simplereq.setRequestExtensions(ext);
            ret = simplereq;
        } finally {
            in.close();
        }
        // a simple crmf is not a complete PKI message, as desired by the CrmfRequestMessage class
        //PKIMessage msg = PKIMessage.getInstance(new ASN1InputStream(new ByteArrayInputStream(request)).readObject());
        //CrmfRequestMessage reqmsg = new CrmfRequestMessage(msg, null, true, null);
        //imsg = reqmsg;
    } else if (reqType == CertificateConstants.CERT_REQ_TYPE_PUBLICKEY) {
        byte[] request;
        // Request can be Base64 encoded or in PEM format
        try {
            request = FileTools.getBytesFromPEM(req.getBytes(), CertTools.BEGIN_PUBLIC_KEY,
                    CertTools.END_PUBLIC_KEY);
        } catch (IOException ex) {
            try {
                request = Base64.decode(req.getBytes());
                if (request == null) {
                    throw new IOException("Base64 decode of buffer returns null");
                }
            } catch (DecoderException de) {
                throw new IOException("Base64 decode fails, message not base64 encoded: " + de.getMessage());
            }
        }
        final PublicKey pubKey = KeyTools.getPublicKeyFromBytes(request);
        ret = new SimpleRequestMessage(pubKey, username, password);
    } else if (reqType == CertificateConstants.CERT_REQ_TYPE_CVC) {
        CVCObject parsedObject = CertificateParser.parseCVCObject(Base64.decode(req.getBytes()));
        // We will handle both the case if the request is an authenticated request, i.e. with an outer signature
        // and when the request is missing the (optional) outer signature.
        CVCertificate cvccert = null;
        if (parsedObject instanceof CVCAuthenticatedRequest) {
            CVCAuthenticatedRequest cvcreq = (CVCAuthenticatedRequest) parsedObject;
            cvccert = cvcreq.getRequest();
        } else {
            cvccert = (CVCertificate) parsedObject;
        }
        CVCRequestMessage reqmsg = new CVCRequestMessage(cvccert.getDEREncoded());
        reqmsg.setUsername(username);
        reqmsg.setPassword(password);
        // Popo is really actually verified by the CA (in SignSessionBean) as well
        if (reqmsg.verify() == false) {
            if (log.isDebugEnabled()) {
                log.debug("CVC POPO verification Failed");
            }
            throw new SignRequestSignatureException(
                    "Invalid inner signature in CVCRequest, popo-verification failed.");
        } else {
            if (log.isDebugEnabled()) {
                log.debug("POPO verification successful");
            }
        }
        ret = reqmsg;
    }
    return ret;
}

From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java

License:Open Source License

/**
 * Select the preferred OCSP response sigAlg according to RFC6960 Section 4.4.7 in the following order:
 * /*from ww  w. j  a va2 s. c o  m*/
 *    1. Select an algorithm specified as a preferred signature algorithm in the client request if it is 
 *       an acceptable algorithm by EJBCA.
 *    2. Select the signature algorithm used to sign a certificate revocation list (CRL) issued by the 
 *       certificate issuer providing status information for the certificate specified by CertID.
 *       (NOT APPLIED)
 *    3. Select the signature algorithm used to sign the OCSPRequest if it is an acceptable algorithm in EJBCA.
 *    4. Select a signature algorithm that has been advertised as being the default signature algorithm for 
 *       the signing service using an out-of-band mechanism.
 *    5. Select a mandatory or recommended signature algorithm specified for the version of OCSP in use, aka. 
 *       specified in the properties file.
 * 
 *    The acceptable algorithm by EJBCA are the algorithms specified in ocsp.properties file in 'ocsp.signaturealgorithm'
 * 
 * @param req
 * @param ocspSigningCacheEntry
 * @param signerCert
 * @return
 */
private String getSigAlg(OCSPReq req, final OcspSigningCacheEntry ocspSigningCacheEntry,
        final X509Certificate signerCert) {
    String sigAlg = null;
    PublicKey pk = signerCert.getPublicKey();
    // Start with the preferred signature algorithm in the OCSP request
    final Extension preferredSigAlgExtension = req
            .getExtension(new ASN1ObjectIdentifier(OCSPObjectIdentifiers.id_pkix_ocsp + ".8"));
    if (preferredSigAlgExtension != null) {
        final ASN1Sequence preferredSignatureAlgorithms = ASN1Sequence
                .getInstance(preferredSigAlgExtension.getParsedValue());
        for (int i = 0; i < preferredSignatureAlgorithms.size(); i++) {
            final ASN1Encodable asn1Encodable = preferredSignatureAlgorithms.getObjectAt(i);
            final ASN1ObjectIdentifier algorithmOid;
            if (asn1Encodable instanceof ASN1ObjectIdentifier) {
                // Handle client requests that were adapted to EJBCA 6.1.0's implementation
                log.info(
                        "OCSP request's PreferredSignatureAlgorithms did not contain an PreferredSignatureAlgorithm, but instead an algorithm OID."
                                + " This will not be supported in a future versions of EJBCA.");
                algorithmOid = (ASN1ObjectIdentifier) asn1Encodable;
            } else {
                // Handle client requests that provide a proper AlgorithmIdentifier as specified in RFC 6960 + RFC 5280
                final ASN1Sequence preferredSignatureAlgorithm = ASN1Sequence.getInstance(asn1Encodable);
                final AlgorithmIdentifier algorithmIdentifier = AlgorithmIdentifier
                        .getInstance(preferredSignatureAlgorithm.getObjectAt(0));
                algorithmOid = algorithmIdentifier.getAlgorithm();
            }
            if (algorithmOid != null) {
                sigAlg = AlgorithmTools.getAlgorithmNameFromOID(algorithmOid);
                if (sigAlg != null && OcspConfiguration.isAcceptedSignatureAlgorithm(sigAlg)
                        && AlgorithmTools.isCompatibleSigAlg(pk, sigAlg)) {
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "Using OCSP response signature algorithm extracted from OCSP request extension. "
                                        + algorithmOid);
                    }
                    return sigAlg;
                }
            }
        }
    }
    // the signature algorithm used to sign the OCSPRequest
    if (req.getSignatureAlgOID() != null) {
        sigAlg = AlgorithmTools.getAlgorithmNameFromOID(req.getSignatureAlgOID());
        if (OcspConfiguration.isAcceptedSignatureAlgorithm(sigAlg)
                && AlgorithmTools.isCompatibleSigAlg(pk, sigAlg)) {
            if (log.isDebugEnabled()) {
                log.debug(
                        "OCSP response signature algorithm: the signature algorithm used to sign the OCSPRequest. "
                                + sigAlg);
            }
            return sigAlg;
        }
    }
    // The signature algorithm that has been advertised as being the default signature algorithm for the signing service using an
    // out-of-band mechanism.
    if (ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate()) {
        // If we have an OcspKeyBinding we use this configuration to override the default
        sigAlg = ocspSigningCacheEntry.getOcspKeyBinding().getSignatureAlgorithm();
        if (log.isDebugEnabled()) {
            log.debug(
                    "OCSP response signature algorithm: the signature algorithm that has been advertised as being the default signature algorithm "
                            + "for the signing service using an out-of-band mechanism. " + sigAlg);
        }
        return sigAlg;
    }
    // The signature algorithm specified for the version of OCSP in use.
    String sigAlgs = OcspConfiguration.getSignatureAlgorithm();
    sigAlg = getSigningAlgFromAlgSelection(sigAlgs, pk);
    if (log.isDebugEnabled()) {
        log.debug("Using configured signature algorithm to sign OCSP response. " + sigAlg);
    }
    return sigAlg;
}

From source file:org.cesecore.certificates.util.cert.QCStatementExtension.java

License:Open Source License

/** Returns all the 'statementId' defined in the QCStatement extension (rfc3739).
 * //from w  w  w.  j a  v  a2s .c om
 * @param cert Certificate containing the extension
 * @return Collection of String with the oid, for example "1.1.1.2", or empty Collection if no identifier is found, never returns null.
 * @throws IOException if there is a problem parsing the certificate
 */
public static Collection<String> getQcStatementIds(final Certificate cert) throws IOException {
    final ArrayList<String> ret = new ArrayList<String>();
    if (cert instanceof X509Certificate) {
        final X509Certificate x509cert = (X509Certificate) cert;
        final ASN1Primitive obj = getExtensionValue(x509cert, Extension.qCStatements.getId());
        if (obj == null) {
            return ret;
        }
        final ASN1Sequence seq = (ASN1Sequence) obj;
        for (int i = 0; i < seq.size(); i++) {
            final QCStatement qc = QCStatement.getInstance(seq.getObjectAt(i));
            final ASN1ObjectIdentifier oid = qc.getStatementId();
            if (oid != null) {
                ret.add(oid.getId());
            }
        }
    }
    return ret;
}

From source file:org.cesecore.certificates.util.cert.QCStatementExtension.java

License:Open Source License

/** Returns the value limit ETSI QCStatement if present.
 * /* w  ww  .j  a v a  2 s .c om*/
 * @param cert Certificate possibly containing the QCStatement extension
 * @return String with the value and currency (ex '50000 SEK')or null if the extension is not present
 * @throws IOException if there is a problem parsing the certificate
 */
public static String getQcStatementValueLimit(final Certificate cert) throws IOException {
    String ret = null;
    if (cert instanceof X509Certificate) {
        final X509Certificate x509cert = (X509Certificate) cert;
        final ASN1Primitive obj = getExtensionValue(x509cert, Extension.qCStatements.getId());
        if (obj == null) {
            return null;
        }
        final ASN1Sequence seq = (ASN1Sequence) obj;
        MonetaryValue mv = null;
        // Look through all the QCStatements and see if we have a stadard ETSI LimitValue
        for (int i = 0; i < seq.size(); i++) {
            final QCStatement qc = QCStatement.getInstance(seq.getObjectAt(i));
            final ASN1ObjectIdentifier oid = qc.getStatementId();
            if ((oid != null) && oid.equals(ETSIQCObjectIdentifiers.id_etsi_qcs_LimiteValue)) {
                // We MAY have a MonetaryValue object here
                final ASN1Encodable enc = qc.getStatementInfo();
                if (enc != null) {
                    mv = MonetaryValue.getInstance(enc);
                    // We can break the loop now, we got it!
                    break;
                }
            }
        }
        if (mv != null) {
            final BigInteger amount = mv.getAmount();
            final BigInteger exp = mv.getExponent();
            final BigInteger ten = BigInteger.valueOf(10);
            // A possibly gotcha here if the monetary value is larger than what fits in a long...
            final long value = amount.longValue() * (ten.pow(exp.intValue())).longValue();
            if (value < 0) {
                log.error("ETSI LimitValue amount is < 0.");
            }
            final String curr = mv.getCurrency().getAlphabetic();
            if (curr == null) {
                log.error("ETSI LimitValue currency is null");
            }
            if ((value >= 0) && (curr != null)) {
                ret = value + " " + curr;
            }
        }
    }
    return ret;
}

From source file:org.cesecore.certificates.util.cert.QCStatementExtension.java

License:Open Source License

/** Returns the 'NameRegistrationAuthorities' defined in the QCStatement extension (rfc3739).
 * //from  ww w .  jav  a  2 s  .c  o m
 * @param cert Certificate containing the extension
 * @return String with for example 'rfc822Name=foo2bar.se, rfc822Name=bar2foo.se' etc. Supports email, dns and uri name, or null of no RAs are found.
 * @throws IOException if there is a problem parsing the certificate
 */
public static String getQcStatementAuthorities(final Certificate cert) throws IOException {
    String ret = null;
    if (cert instanceof X509Certificate) {
        final X509Certificate x509cert = (X509Certificate) cert;
        final ASN1Primitive obj = getExtensionValue(x509cert, Extension.qCStatements.getId());
        if (obj == null) {
            return null;
        }
        final ASN1Sequence seq = (ASN1Sequence) obj;
        SemanticsInformation si = null;
        // Look through all the QCStatements and see if we have a standard RFC3739 pkixQCSyntax
        for (int i = 0; i < seq.size(); i++) {
            final QCStatement qc = QCStatement.getInstance(seq.getObjectAt(i));
            final ASN1ObjectIdentifier oid = qc.getStatementId();
            if ((oid != null) && (oid.equals(RFC3739QCObjectIdentifiers.id_qcs_pkixQCSyntax_v1)
                    || oid.equals(RFC3739QCObjectIdentifiers.id_qcs_pkixQCSyntax_v2))) {
                // We MAY have a SemanticsInformation object here
                final ASN1Encodable enc = qc.getStatementInfo();
                if (enc != null) {
                    si = SemanticsInformation.getInstance(enc);
                    // We can break the loop now, we got it!
                    break;
                }
            }
        }
        if (si != null) {
            final GeneralName[] gns = si.getNameRegistrationAuthorities();
            if (gns == null) {
                return null;
            }
            final StringBuilder strBuf = new StringBuilder();
            for (int i = 0; i < gns.length; i++) {
                final GeneralName gn = gns[i];
                if (strBuf.length() != 0) {
                    // Append comma so we get nice formatting if there are more than one authority
                    strBuf.append(", ");
                }
                final String str = getGeneralNameString(gn.getTagNo(), gn.getName());
                if (str != null) {
                    strBuf.append(str);
                }
            }
            if (strBuf.length() > 0) {
                ret = strBuf.toString();
            }
        }
    }
    return ret;
}

From source file:org.cesecore.certificates.util.cert.SubjectDirAttrExtension.java

License:Open Source License

/**
* SubjectDirectoryAttributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
*
* Attribute ::= SEQUENCE {//  w  w  w  .  j a  v a2 s  .  c om
 *  type AttributeType,
 *  values SET OF AttributeValue }
 *  -- at least one value is required
 * 
 * AttributeType ::= OBJECT IDENTIFIER
 * AttributeValue ::= ANY
 * 
* SubjectDirectoryAttributes is of form 
* dateOfBirth=<19590927>, placeOfBirth=<string>, gender=<M/F>, countryOfCitizenship=<two letter ISO3166>, countryOfResidence=<two letter ISO3166>
 * 
 * Supported subjectDirectoryAttributes are the ones above 
*
* @param certificate containing subject directory attributes
* @return String containing directoryAttributes of form the form specified above or null if no directoryAttributes exist. 
*   Values in returned String is from CertTools constants. 
*   DirectoryAttributes not supported are simply not shown in the resulting string.  
* @throws java.lang.Exception
*/
public static String getSubjectDirectoryAttributes(Certificate certificate) throws Exception {
    log.debug("Search for SubjectAltName");
    String result = "";
    if (certificate instanceof X509Certificate) {
        X509Certificate x509cert = (X509Certificate) certificate;
        ASN1Primitive obj = CertTools.getExtensionValue(x509cert, Extension.subjectDirectoryAttributes.getId());
        if (obj == null) {
            return null;
        }
        ASN1Sequence seq = (ASN1Sequence) obj;

        String prefix = "";
        SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMdd");
        for (int i = 0; i < seq.size(); i++) {
            Attribute attr = Attribute.getInstance(seq.getObjectAt(i));
            if (!StringUtils.isEmpty(result)) {
                prefix = ", ";
            }
            if (attr.getAttrType().getId().equals(id_pda_dateOfBirth)) {
                ASN1Set set = attr.getAttrValues();
                // Come on, we'll only allow one dateOfBirth, we're not allowing such frauds with multiple birth dates
                ASN1GeneralizedTime time = ASN1GeneralizedTime.getInstance(set.getObjectAt(0));
                Date date = time.getDate();
                String dateStr = dateF.format(date);
                result += prefix + "dateOfBirth=" + dateStr;
            }
            if (attr.getAttrType().getId().equals(id_pda_placeOfBirth)) {
                ASN1Set set = attr.getAttrValues();
                // same here only one placeOfBirth
                String pb = ((ASN1String) set.getObjectAt(0)).getString();
                result += prefix + "placeOfBirth=" + pb;
            }
            if (attr.getAttrType().getId().equals(id_pda_gender)) {
                ASN1Set set = attr.getAttrValues();
                // same here only one gender
                String g = ((ASN1String) set.getObjectAt(0)).getString();
                result += prefix + "gender=" + g;
            }
            if (attr.getAttrType().getId().equals(id_pda_countryOfCitizenship)) {
                ASN1Set set = attr.getAttrValues();
                // same here only one citizenship
                String g = ((ASN1String) set.getObjectAt(0)).getString();
                result += prefix + "countryOfCitizenship=" + g;
            }
            if (attr.getAttrType().getId().equals(id_pda_countryOfResidence)) {
                ASN1Set set = attr.getAttrValues();
                // same here only one residence
                String g = ((ASN1String) set.getObjectAt(0)).getString();
                result += prefix + "countryOfResidence=" + g;
            }
        }
    }
    if (StringUtils.isEmpty(result)) {
        return null;
    }
    return result;
}