Example usage for org.bouncycastle.asn1 DERUTF8String getString

List of usage examples for org.bouncycastle.asn1 DERUTF8String getString

Introduction

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

Prototype

public String getString() 

Source Link

Usage

From source file:bluecrystal.bcdeps.helper.DerEncoder.java

License:Open Source License

public static SignPolicyRef extractVerifyRefence(byte[] policy) throws IOException, ParseException {
    SignPolicyRef ret = new SignPolicyRef();

    ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(policy));
    ASN1Primitive topLevel = is.readObject();
    // SignaturePolicy ::= SEQUENCE {
    // signPolicyHashAlg AlgorithmIdentifier,
    // signPolicyInfo SignPolicyInfo,
    // signPolicyHash SignPolicyHash OPTIONAL }
    if (topLevel instanceof DLSequence) {
        DLSequence topLevelDLS = (DLSequence) topLevel;
        ASN1Encodable dseqL10 = topLevelDLS.getObjectAt(0);
        ASN1Encodable psHashAlg = null;/*  www . j ava2s .  com*/
        if (dseqL10 instanceof DLSequence) {
            DLSequence dseqL10DLS = (DLSequence) dseqL10;
            psHashAlg = dseqL10DLS.getObjectAt(0);

        } else if (dseqL10 instanceof ASN1ObjectIdentifier) {
            psHashAlg = (ASN1ObjectIdentifier) dseqL10;
        } else
            return null;

        if (psHashAlg instanceof ASN1ObjectIdentifier) {
            ASN1ObjectIdentifier psHashAlgOid = (ASN1ObjectIdentifier) psHashAlg;
            ret.setPsHashAlg(psHashAlgOid.toString());
        }

        ASN1Encodable dseqL11 = topLevelDLS.getObjectAt(1);
        if (dseqL11 instanceof DLSequence) {
            // SignPolicyInfo ::= SEQUENCE {
            DLSequence dseqL11DLS = (DLSequence) dseqL11;
            ASN1Encodable psOid = dseqL11DLS.getObjectAt(0);
            // signPolicyIdentifier SignPolicyId,
            // 2.16.76.1.7.1.6.2.1
            if (psOid instanceof ASN1ObjectIdentifier) {
                ASN1ObjectIdentifier psOidOid = (ASN1ObjectIdentifier) psOid;
                ret.setPsOid(psOidOid.toString());

            }
            ASN1Encodable dateOfIssue = dseqL11DLS.getObjectAt(1);
            // dateOfIssue GeneralizedTime,
            // 2012-03-22
            if (dateOfIssue instanceof ASN1GeneralizedTime) {
                ASN1GeneralizedTime dateOfIssueGT = (ASN1GeneralizedTime) dateOfIssue;
                ret.setDateOfIssue(dateOfIssueGT.getDate());
            }

            ASN1Encodable policyIssuerName = dseqL11DLS.getObjectAt(2);
            // policyIssuerName PolicyIssuerName,
            // C=BR, O=ICP-Brasil, OU=Instituto Nacional de Tecnologia da
            // Informacao
            // - ITI
            if (policyIssuerName instanceof DLSequence) {
                DLSequence policyIssuerNameDLSeq = (DLSequence) policyIssuerName;
                ASN1Encodable policyIssuerName2 = policyIssuerNameDLSeq.getObjectAt(0);
                if (policyIssuerName2 instanceof DERTaggedObject) {
                    DERTaggedObject policyIssuerName2DTO = (DERTaggedObject) policyIssuerName2;
                    ASN1Primitive polIssuerNameObj = policyIssuerName2DTO.getObject();
                    if (polIssuerNameObj instanceof DEROctetString) {
                        String polIssuerNameStr = new String(((DEROctetString) polIssuerNameObj).getOctets());
                        ret.setPolIssuerName(polIssuerNameStr);
                    }
                }

            }

            ASN1Encodable fieldOfApplication = dseqL11DLS.getObjectAt(3);
            // fieldOfApplication FieldOfApplication,
            // Este tipo de assinatura deve ser utilizado em aplicacoes ou
            // processos
            // de negocio nos quais a assinatura digital agrega seguranca a
            // autenticacao de entidades e verificacao de integridade,
            // permitindo
            // sua validacao durante o prazo de, validade dos certificados
            // dos
            // signatarios. Uma vez que nao sao usados carimbos do tempo, a
            // validacao posterior so sera possivel se existirem referencias
            // temporais que identifiquem o momento em que ocorreu a
            // assinatura
            // digital. Nessas situacoes, deve existir legislacao especifica
            // ou um
            // acordo previo entre as partes definindo as referencias a
            // serem
            // utilizadas. Segundo esta PA, e permitido o emprego de
            // multiplas
            // assinaturas.
            if (fieldOfApplication instanceof DEROctetString) {
                DERUTF8String fieldOfApplicationDUS = (DERUTF8String) fieldOfApplication;
                ret.setFieldOfApplication(fieldOfApplicationDUS.getString());
            }
            // signatureValidationPolicy SignatureValidationPolicy,
            // signPolExtensions SignPolExtensions OPTIONAL
            // SignatureValidationPolicy ::= SEQUENCE {
            ASN1Encodable signatureValidationPolicy = dseqL11DLS.getObjectAt(4);
            if (signatureValidationPolicy instanceof DLSequence) {
                DLSequence signatureValidationPolicyDLS = (DLSequence) signatureValidationPolicy;
                // signingPeriod SigningPeriod,
                // NotBefore 2012-03-22
                // NotAfter 2023-06-21
                ASN1Encodable signingPeriod = signatureValidationPolicyDLS.getObjectAt(0);
                if (signingPeriod instanceof DLSequence) {
                    DLSequence signingPeriodDLS = (DLSequence) signingPeriod;
                    ASN1Encodable notBefore = signingPeriodDLS.getObjectAt(0);
                    if (notBefore instanceof ASN1GeneralizedTime) {
                        ASN1GeneralizedTime notBeforeAGT = (ASN1GeneralizedTime) notBefore;
                        ret.setNotBefore(notBeforeAGT.getDate());

                    }

                    ASN1Encodable notAfter = signingPeriodDLS.getObjectAt(1);
                    if (notAfter instanceof ASN1GeneralizedTime) {
                        ASN1GeneralizedTime notAfterAGT = (ASN1GeneralizedTime) notAfter;
                        ret.setNotAfter(notAfterAGT.getDate());
                    }

                }

                //
                // commonRules CommonRules,
                ASN1Encodable commonRules = getAt(signatureValidationPolicyDLS, 1);
                if (commonRules instanceof DLSequence) {
                    DLSequence commonRulesDLS = (DLSequence) commonRules;
                    // CommonRules ::= SEQUENCE {
                    // signerAndVeriferRules [0] SignerAndVerifierRules
                    // OPTIONAL,
                    // signingCertTrustCondition [1]
                    // SigningCertTrustCondition OPTIONAL,
                    // timeStampTrustCondition [2] TimestampTrustCondition
                    // OPTIONAL,
                    // attributeTrustCondition [3] AttributeTrustCondition
                    // OPTIONAL,
                    // algorithmConstraintSet [4] AlgorithmConstraintSet
                    // OPTIONAL,
                    // signPolExtensions [5] SignPolExtensions OPTIONAL
                    // }
                    ASN1Encodable signerAndVeriferRules = getAt(commonRulesDLS, 0);

                    // SignerAndVerifierRules ::= SEQUENCE {
                    // signerRules SignerRules,
                    // verifierRules VerifierRules }

                    if (signerAndVeriferRules instanceof DERTaggedObject) {
                        DERTaggedObject signerAndVeriferRulesDTO = (DERTaggedObject) signerAndVeriferRules;
                        ASN1Encodable signerAndVeriferRulesTmp = signerAndVeriferRulesDTO.getObject();
                        if (signerAndVeriferRulesTmp instanceof DERSequence) {
                            DERSequence signerAndVeriferRulesDERSeq = (DERSequence) signerAndVeriferRulesTmp;
                            ASN1Encodable signerRules = getAt(signerAndVeriferRulesDERSeq, 0);
                            if (signerRules instanceof DERSequence) {
                                DERSequence signerRulesDERSeq = (DERSequence) signerRules;
                                // SignerRules ::= SEQUENCE {
                                // externalSignedData BOOLEAN OPTIONAL,
                                // -- True if signed data is external to CMS
                                // structure
                                // -- False if signed data part of CMS
                                // structure
                                // -- not present if either allowed
                                // mandatedSignedAttr CMSAttrs,
                                // -- Mandated CMS signed attributes
                                // 1.2.840.113549.1.9.3
                                // 1.2.840.113549.1.9.4
                                // 1.2.840.113549.1.9.16.2.15
                                // 1.2.840.113549.1.9.16.2.47
                                // mandatedUnsignedAttr CMSAttrs,
                                // <empty sequence>
                                // -- Mandated CMS unsigned attributed
                                // mandatedCertificateRef [0] CertRefReq
                                // DEFAULT signerOnly,
                                // (1)
                                // -- Mandated Certificate Reference
                                // mandatedCertificateInfo [1] CertInfoReq
                                // DEFAULT none,
                                // -- Mandated Certificate Info
                                // signPolExtensions [2] SignPolExtensions
                                // OPTIONAL}

                                // CMSAttrs ::= SEQUENCE OF OBJECT
                                // IDENTIFIER
                                ASN1Encodable mandatedSignedAttr = getAt(signerRulesDERSeq, 0);
                                if (mandatedSignedAttr instanceof DERSequence) {
                                    DERSequence mandatedSignedAttrDERSeq = (DERSequence) mandatedSignedAttr;
                                    for (int i = 0; i < mandatedSignedAttrDERSeq.size(); i++) {
                                        ASN1Encodable at = getAt(mandatedSignedAttrDERSeq, i);
                                        ret.addMandatedSignedAttr(at.toString());
                                    }
                                }
                                ASN1Encodable mandatedUnsignedAttr = getAt(signerRulesDERSeq, 1);
                                if (mandatedUnsignedAttr instanceof DERSequence) {
                                    DERSequence mandatedUnsignedAttrDERSeq = (DERSequence) mandatedUnsignedAttr;
                                }
                                ASN1Encodable mandatedCertificateRef = getAt(signerRulesDERSeq, 2);
                                if (mandatedCertificateRef instanceof DERTaggedObject) {
                                    DERTaggedObject mandatedCertificateRefDERSeq = (DERTaggedObject) mandatedCertificateRef;
                                    // CertRefReq ::= ENUMERATED {
                                    // signerOnly (1),
                                    // -- Only reference to signer cert
                                    // mandated
                                    // fullpath (2)
                                    //
                                    // -- References for full cert path up
                                    // to a trust point required
                                    // }
                                    ASN1Encodable mandatedCertificateRefTmp = mandatedCertificateRefDERSeq
                                            .getObject();
                                    ASN1Enumerated mandatedCertificateRefEnum = (ASN1Enumerated) mandatedCertificateRefTmp;
                                    BigInteger valEnum = mandatedCertificateRefEnum.getValue();
                                    int mandatedCertificateRefInt = valEnum.intValue();
                                    ret.setMandatedCertificateRef(mandatedCertificateRefInt);
                                    int x = 0;
                                }
                            }

                            ASN1Encodable verifierRules = getAt(signerAndVeriferRulesDERSeq, 1);
                            if (verifierRules instanceof DERSequence) {
                                DERSequence verifierRulesDERSeq = (DERSequence) verifierRules;

                            }

                        }

                    }

                    ASN1Encodable signingCertTrustCondition = getAt(commonRulesDLS, 1);
                    if (signingCertTrustCondition instanceof DERTaggedObject) {
                        DERTaggedObject signingCertTrustConditionDTO = (DERTaggedObject) signingCertTrustCondition;
                        ASN1Encodable signingCertTrustConditionTmp = signingCertTrustConditionDTO.getObject();
                        if (signingCertTrustConditionTmp instanceof DERSequence) {
                            DERSequence signingCertTrustConditionDERSeq = (DERSequence) signingCertTrustConditionTmp;
                        }

                    }
                    ASN1Encodable timeStampTrustCondition = getAt(commonRulesDLS, 2);
                    if (timeStampTrustCondition instanceof DERTaggedObject) {
                        DERTaggedObject timeStampTrustConditionDTO = (DERTaggedObject) timeStampTrustCondition;
                        ASN1Encodable timeStampTrustConditionTmp = timeStampTrustConditionDTO.getObject();
                        if (timeStampTrustConditionTmp instanceof DERSequence) {
                            DERSequence timeStampTrustConditionDERSeq = (DERSequence) timeStampTrustConditionTmp;
                        }

                    }
                    ASN1Encodable attributeTrustCondition = getAt(commonRulesDLS, 3);
                    if (attributeTrustCondition instanceof DERTaggedObject) {
                        DERTaggedObject attributeTrustConditionDTO = (DERTaggedObject) attributeTrustCondition;
                        ASN1Encodable attributeTrustConditionTmp = attributeTrustConditionDTO.getObject();
                        if (attributeTrustConditionTmp instanceof DERSequence) {
                            DERSequence attributeTrustConditionDERSeq = (DERSequence) attributeTrustConditionTmp;
                        }

                    }

                    // *****************************
                    ASN1Encodable algorithmConstraintSet = getAt(commonRulesDLS, 4);
                    ASN1Encodable signPolExtensions = getAt(commonRulesDLS, 5);

                }
                // commitmentRules CommitmentRules,
                ASN1Encodable commitmentRules = getAt(signatureValidationPolicyDLS, 2);
                if (commitmentRules instanceof DLSequence) {

                }

                // signPolExtensions SignPolExtensions
                // OPTIONAL
                ASN1Encodable signPolExtensions = getAt(signatureValidationPolicyDLS, 3);
                if (signPolExtensions instanceof DLSequence) {

                }
                // }
            }
        }

    }

    // CertInfoReq ::= ENUMERATED {
    // none (0) ,
    // -- No mandatory requirements
    // signerOnly (1) ,
    // -- Only reference to signer cert mandated
    // fullpath (2)
    // -- References for full cert path up to a
    // -- trust point mandated
    // }

    is.close();
    return ret;

}

From source file:br.gov.frameworkdemoiselle.certificate.oid.OIDGeneric.java

License:Open Source License

/**
 * Instance for object.//from w ww . j a v  a  2 s  .c o  m
 *
 * @param data -> byte array with certificate content.
 * @return Object GenericOID
 * @throws IOException
 * @throws Exception
 */
public static OIDGeneric getInstance(byte[] data) throws IOException, Exception {
    ASN1InputStream is = new ASN1InputStream(data);
    DERSequence sequence = (DERSequence) is.readObject();
    DERObjectIdentifier objectIdentifier = (DERObjectIdentifier) sequence.getObjectAt(0);
    DERTaggedObject tag = (DERTaggedObject) sequence.getObjectAt(1);
    DEROctetString octetString = null;
    DERPrintableString printableString = null;
    DERUTF8String utf8String = null;
    DERIA5String ia5String = null;

    try {
        octetString = (DEROctetString) DEROctetString.getInstance(tag);
    } catch (Exception ex) {
        try {
            printableString = DERPrintableString.getInstance(tag);
        } catch (Exception e1) {
            try {
                utf8String = DERUTF8String.getInstance(tag);
            } catch (Exception e2) {
                ia5String = DERIA5String.getInstance(tag);
            }
        }
    }

    String className = "br.gov.frameworkdemoiselle.certificate.oid.OID_"
            + objectIdentifier.getId().replaceAll("[.]", "_");
    OIDGeneric oidGenerico;
    try {
        oidGenerico = (OIDGeneric) Class.forName(className).newInstance();
    } catch (InstantiationException e) {
        throw new Exception("Can not instace class '" + className + "'.", e);
    } catch (IllegalAccessException e) {
        throw new Exception("Was not possible instace class '" + className + "'.", e);
    } catch (ClassNotFoundException e) {
        oidGenerico = new OIDGeneric();
    }

    oidGenerico.setOid(objectIdentifier.getId());

    if (octetString != null) {
        oidGenerico.setData(new String(octetString.getOctets()));
    } else if (printableString != null) {
        oidGenerico.setData(printableString.getString());
    } else if (utf8String != null) {
        oidGenerico.setData(utf8String.getString());
    } else {
        oidGenerico.setData(ia5String.getString());
    }
    oidGenerico.initialize();
    return oidGenerico;
}

From source file:com.tremolosecurity.proxy.auth.ssl.util.UpnExtractor.java

License:Apache License

private String loadNTPrincipal(X509Certificate[] certs) throws CertificateParsingException, IOException {
    X509Certificate cert = certs[0];
    Collection<List<?>> subjectAlternativeNames = cert.getSubjectAlternativeNames();
    if (subjectAlternativeNames != null && !subjectAlternativeNames.isEmpty()) {
        for (List<?> subjectAltName : subjectAlternativeNames) {
            if (((Integer) subjectAltName.get(0)) == GeneralName.otherName) {
                ASN1InputStream asn1Input = new ASN1InputStream((byte[]) subjectAltName.get(1));
                ASN1Primitive derObject = asn1Input.readObject();
                DLSequence seq = (DLSequence) derObject;
                ASN1ObjectIdentifier id = ASN1ObjectIdentifier.getInstance(seq.getObjectAt(0));
                if (id.getId().equals("1.3.6.1.4.1.311.20.2.3")) {
                    ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(1);
                    DERUTF8String str = null;
                    while (str == null) {
                        if (obj.getObject() instanceof DERTaggedObject) {
                            obj = (ASN1TaggedObject) obj.getObject();
                        } else if (obj.getObject() instanceof DERUTF8String) {
                            str = (DERUTF8String) obj.getObject();
                        } else {
                            asn1Input.close();
                            return null;
                        }//from   ww  w. jav  a2 s .  c  o m
                    }
                    asn1Input.close();
                    return str.getString();
                }
            }
        }
    }
    return null;
}

From source file:com.zimbra.cs.service.authenticator.CertUtil.java

License:Open Source License

String getSubjectAltNameOtherNameUPN() {
    Collection<List<?>> generalNames = null;
    try {//from  ww w.  j a v  a  2s.c o m
        generalNames = cert.getSubjectAlternativeNames();
    } catch (CertificateParsingException e) {
        ZimbraLog.account.warn(LOG_PREFIX + "unable to get subject alternative names", e);
    }

    if (generalNames == null) {
        return null;
    }

    ASN1InputStream decoder = null;
    try {
        // Check that the certificate includes the SubjectAltName extension
        for (List<?> generalName : generalNames) {
            Integer tag = (Integer) generalName.get(0);
            if (GeneralName.otherName == tag.intValue()) {
                // Value is encoded using ASN.1
                decoder = new ASN1InputStream((byte[]) generalName.toArray()[1]);
                DEREncodable encoded = decoder.readObject();
                DERSequence derSeq = (DERSequence) encoded;

                DERObjectIdentifier typeId = DERObjectIdentifier.getInstance(derSeq.getObjectAt(0));
                String oid = typeId.getId();

                String value = null;
                ASN1TaggedObject otherNameValue = ASN1TaggedObject.getInstance(derSeq.getObjectAt(1));
                if (OID_UPN.equals(oid)) {
                    ASN1TaggedObject upnValue = ASN1TaggedObject.getInstance(otherNameValue.getObject());
                    DERUTF8String str = DERUTF8String.getInstance(upnValue.getObject());
                    value = str.getString();
                    return value;
                }
            }
        }
    } catch (IOException e) {
        ZimbraLog.account.warn(LOG_PREFIX + "unable to process ASN.1 data", e);
    } finally {
        ByteUtil.closeStream(decoder);
    }

    return null;
}

From source file:com.zimbra.cs.service.authenticator.CertUtil.java

License:Open Source License

private void printSubjectAlternativeNames(PrintStream outStream) throws Exception {

    final String UPN_DISPLAY = "Principal Name";
    final String RFC822NAME_DISPLAY = "RFC822 Name";
    final String DNSNAME_DISPLAY = "DNS Name";

    outStream.format("X509v3 Subject Alternative Name: \n");

    ASN1InputStream decoder = null;
    try {/* w  ww  .  j  a va 2 s  .co m*/
        Collection<List<?>> generalNames = cert.getSubjectAlternativeNames();
        // Check that the certificate includes the SubjectAltName extension
        if (generalNames == null) {
            return;
        }

        /*
           OtherName ::= SEQUENCE {
          type-id    OBJECT IDENTIFIER,
          value      [0] EXPLICIT ANY DEFINED BY type-id }
         */

        for (List<?> generalName : generalNames) {
            Integer tag = (Integer) generalName.get(0);
            if (GeneralName.otherName == tag.intValue()) {
                // Value is encoded using ASN.1
                decoder = new ASN1InputStream((byte[]) generalName.toArray()[1]);
                DEREncodable encoded = decoder.readObject();
                DERSequence derSeq = (DERSequence) encoded;

                DERObjectIdentifier typeId = DERObjectIdentifier.getInstance(derSeq.getObjectAt(0));
                String oid = typeId.getId();

                String value = null;
                ASN1TaggedObject otherNameValue = ASN1TaggedObject.getInstance(derSeq.getObjectAt(1));
                if (OID_UPN.equals(oid)) {
                    ASN1TaggedObject upnValue = ASN1TaggedObject.getInstance(otherNameValue.getObject());
                    DERUTF8String str = DERUTF8String.getInstance(upnValue.getObject());
                    value = str.getString();
                }

                outStream.format("    [%d] %s(%s) = %s\n", tag, oid, UPN_DISPLAY, value);
            } else if (GeneralName.rfc822Name == tag.intValue()) {
                String value = (String) generalName.get(1);
                outStream.format("    [%d] %s = %s\n", tag, RFC822NAME_DISPLAY, value);
            } else if (GeneralName.dNSName == tag.intValue()) {
                String value = (String) generalName.get(1);
                outStream.format("    [%d] %s = %s\n", tag, DNSNAME_DISPLAY, value);
            } else {
                outStream.format("    [%d] - not yet supported\n", tag);
            }

        }
    } catch (CertificateParsingException e) {
        e.printStackTrace();
    } finally {
        ByteUtil.closeStream(decoder);
    }
}

From source file:eu.europa.ec.markt.dss.validation102853.cades.CAdESSignature.java

License:Open Source License

@Override
public SignatureProductionPlace getSignatureProductionPlace() {

    final AttributeTable attributes = signerInformation.getSignedAttributes();
    if (attributes == null) {

        return null;
    }//w  w w  .  j  a v a 2s.  co  m
    Attribute signatureProductionPlaceAttr = attributes.get(PKCSObjectIdentifiers.id_aa_ets_signerLocation);
    if (signatureProductionPlaceAttr == null) {

        return null;
    }

    final ASN1Encodable asn1Encodable = signatureProductionPlaceAttr.getAttrValues().getObjectAt(0);
    SignerLocation signerLocation = null;
    try {
        signerLocation = SignerLocation.getInstance(asn1Encodable);
    } catch (Exception e) {
        /*
                    // TODO: (Bob: 2013 Dec 11) ---> Validation: /C:/ws_trunk/apps/dss/core/dss-document/target/test-classes/cades2013/CAdES-EPES.SCOK/BULL/Signature-C-EPES-2.p7s
                
                    WARN  SignedDocumentValidator.java:557 - org.bouncycastle.asn1.DERUTF8String cannot be cast to org.bouncycastle.asn1.DERTaggedObject
                    java.lang.ClassCastException: org.bouncycastle.asn1.DERUTF8String cannot be cast to org.bouncycastle.asn1.DERTaggedObject
                    at org.bouncycastle.asn1.esf.SignerLocation.<init>(Unknown Source) ~[bcprov-ext-jdk15on-1.49.jar:1.49.0]
                    at org.bouncycastle.asn1.esf.SignerLocation.getInstance(Unknown Source) ~[bcprov-ext-jdk15on-1.49.jar:1.49.0]
                    at eu.europa.ec.markt.dss.validation102853.cades.CAdESSignature.getSignatureProductionPlace(CAdESSignature.java:663) ~[classes/:na]
                    at eu.europa.ec.markt.dss.validation102853.SignedDocumentValidator.dealSignature(SignedDocumentValidator.java:1209) [classes/:na]
                    at eu.europa.ec.markt.dss.validation102853.SignedDocumentValidator.validateSignature(SignedDocumentValidator.java:535) [classes/:na]
                    at eu.europa.ec.markt.dss.validation102853.SignedDocumentValidator.generateDiagnosticData(SignedDocumentValidator.java:510) [classes/:na]
                    at eu.europa.ec.markt.dss.validation102853.SignedDocumentValidator.validateDocument(SignedDocumentValidator.java:469) [classes/:na]
                    at eu.europa.ec.markt.dss.validation102853.SignedDocumentValidator.validateDocument(SignedDocumentValidator.java:450) [classes/:na]
        */
        LOG.error(e.getMessage(), e);
    }
    if (signerLocation == null) {
        return null;
    }
    final SignatureProductionPlace signatureProductionPlace = new SignatureProductionPlace();
    final DERUTF8String countryName = signerLocation.getCountryName();
    if (countryName != null) {

        signatureProductionPlace.setCountryName(countryName.getString());
    }
    final DERUTF8String localityName = signerLocation.getLocalityName();
    if (localityName != null) {

        signatureProductionPlace.setCity(localityName.getString());
    }
    final StringBuilder address = new StringBuilder();
    final ASN1Sequence seq = signerLocation.getPostalAddress();
    if (seq != null) {

        for (int ii = 0; ii < seq.size(); ii++) {

            if (seq.getObjectAt(ii) instanceof DEROctetString) {
                if (address.length() > 0) {
                    address.append(" / ");
                }
                // TODO: getOctets returns an array
                address.append(new String(((DEROctetString) seq.getObjectAt(ii)).getOctets()));
            } else if (seq.getObjectAt(ii) instanceof DERUTF8String) {

                if (address.length() > 0) {
                    address.append(" / ");
                }
                final DERUTF8String derutf8String = (DERUTF8String) seq.getObjectAt(ii);
                address.append(derutf8String.getString());
            }
        }
    }
    signatureProductionPlace.setAddress(address.toString());
    // This property is not used in CAdES version of signature
    // signatureProductionPlace.setStateOrProvince(stateOrProvince);
    return signatureProductionPlace;
}

From source file:eu.europa.esig.dss.cades.validation.CAdESSignature.java

License:Open Source License

@Override
public SignatureProductionPlace getSignatureProductionPlace() {

    final AttributeTable attributes = signerInformation.getSignedAttributes();
    if (attributes == null) {

        return null;
    }//from  w w  w.  jav  a  2s .  c o m
    Attribute signatureProductionPlaceAttr = attributes.get(PKCSObjectIdentifiers.id_aa_ets_signerLocation);
    if (signatureProductionPlaceAttr == null) {

        return null;
    }

    final ASN1Encodable asn1Encodable = signatureProductionPlaceAttr.getAttrValues().getObjectAt(0);
    SignerLocation signerLocation = null;
    try {
        signerLocation = SignerLocation.getInstance(asn1Encodable);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }
    if (signerLocation == null) {
        return null;
    }
    final SignatureProductionPlace signatureProductionPlace = new SignatureProductionPlace();
    final DERUTF8String countryName = signerLocation.getCountryName();
    if (countryName != null) {

        signatureProductionPlace.setCountryName(countryName.getString());
    }
    final DERUTF8String localityName = signerLocation.getLocalityName();
    if (localityName != null) {

        signatureProductionPlace.setCity(localityName.getString());
    }
    final StringBuilder address = new StringBuilder();
    final ASN1Sequence seq = signerLocation.getPostalAddress();
    if (seq != null) {

        for (int ii = 0; ii < seq.size(); ii++) {

            if (seq.getObjectAt(ii) instanceof DEROctetString) {
                if (address.length() > 0) {
                    address.append(" / ");
                }
                // TODO: getOctets returns an array
                address.append(new String(((DEROctetString) seq.getObjectAt(ii)).getOctets()));
            } else if (seq.getObjectAt(ii) instanceof DERUTF8String) {

                if (address.length() > 0) {
                    address.append(" / ");
                }
                final DERUTF8String derutf8String = (DERUTF8String) seq.getObjectAt(ii);
                address.append(derutf8String.getString());
            }
        }
    }
    signatureProductionPlace.setStreetAddress(address.toString());
    // This property is not used in CAdES version of signature
    // signatureProductionPlace.setStateOrProvince(stateOrProvince);
    return signatureProductionPlace;
}

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

License:Open Source License

/**
 * Parse UPN/otherName//from   w w w .  j  a  v  a 2 s .  c  om
 *
 * @param generalName otherName object
 * @return UPN as string
 */
public static String parseUPN(GeneralName generalName) {
    // OtherName ::= SEQUENCE {
    //    type-id OBJECT IDENTIFIER,
    //    value [0] EXPLICIT ANY DEFINED BY type-id }

    ASN1Sequence otherName = (ASN1Sequence) generalName.getName();
    ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) otherName.getObjectAt(0);

    if (UPN_OID.equals(oid.getId())) {
        DERTaggedObject derTaggedObject = (DERTaggedObject) otherName.getObjectAt(1);
        DERUTF8String upn = DERUTF8String.getInstance(derTaggedObject.getObject());
        return MessageFormat.format(res.getString("GeneralNameUtil.OtherGeneralName"), "UPN", upn.getString());
    }

    // fallback to generic handling
    ASN1Encodable value = otherName.getObjectAt(1);
    try {
        return MessageFormat.format(res.getString("GeneralNameUtil.OtherGeneralName"),
                ObjectIdUtil.toString(oid),
                HexUtil.getHexString(value.toASN1Primitive().getEncoded(ASN1Encoding.DER)));
    } catch (IOException e) {
        return MessageFormat.format(res.getString("GeneralNameUtil.OtherGeneralName"),
                ObjectIdUtil.toString(oid), "");
    }
}

From source file:org.apache.catalina.realm.X509SubjectAlternativeNameRetriever.java

License:Apache License

/**
 * The method converts ASNDerEncodedByteArray into String
 * @param byteArray//from w w  w  .  ja va2s.c om
 * @return String 
 */
private String getStringFromASNDerEncodedByteArray(byte[] byteArray) {
    if (logger.isDebugEnabled()) {
        logger.debug("getStringFromASNDerEncodedByteArray(byte[]) - start");
    }

    String ret = null;
    try {
        ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(byteArray));
        DERObject derObject = asn1InputStream.readObject();
        ASN1Sequence asn1Sequence = ASN1Sequence.getInstance(derObject);
        Object objectValue = asn1Sequence.getObjectAt(1);
        if (objectValue instanceof ASN1TaggedObject) {
            ASN1TaggedObject asn1TaggedObject = (ASN1TaggedObject) objectValue;
            try {
                if (logger.isDebugEnabled()) {
                    logger.debug("Try to get string from DERUTF8String.");
                }
                DERObject derTaggedObject = asn1TaggedObject.getObject();
                DERUTF8String derUtf8String = DERUTF8String.getInstance(derTaggedObject);
                ret = derUtf8String.getString();
            } catch (IllegalArgumentException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Can not get String From DERUTF8String, [" + e.getMessage() + "].");
                }
            }
        }
    } catch (Exception e) {
        if (logger.isInfoEnabled()) {
            logger.info("Can not get String From ASNDerEncoded ByteArray, [" + e.getMessage() + "].");
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("getStringFromASNDerEncodedByteArray(byte[]) - end. Ret is [" + ret + "].");
    }
    return ret;

}

From source file:org.cesecore.util.CertTools.java

License:Open Source License

/**
 * Helper method for the above method/*from  w w w  .  j a v  a2  s . c  o m*/
 * 
 * @param seq the OtherName sequence
 */
private static String getUPNStringFromSequence(ASN1Sequence seq) {
    if (seq != null) {
        // First in sequence is the object identifier, that we must check
        ASN1ObjectIdentifier id = ASN1ObjectIdentifier.getInstance(seq.getObjectAt(0));
        if (id.getId().equals(CertTools.UPN_OBJECTID)) {
            ASN1TaggedObject oobj = (ASN1TaggedObject) seq.getObjectAt(1);
            // Due to bug in java cert.getSubjectAltName regarding OtherName, it can be tagged an extra time...
            ASN1Primitive obj = oobj.getObject();
            if (obj instanceof ASN1TaggedObject) {
                obj = ASN1TaggedObject.getInstance(obj).getObject();
            }
            DERUTF8String str = DERUTF8String.getInstance(obj);
            return str.getString();
        }
    }
    return null;
}