Example usage for org.bouncycastle.asn1 DERUTF8String getInstance

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

Introduction

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

Prototype

public static DERUTF8String getInstance(Object obj) 

Source Link

Document

Return an UTF8 string from the passed in object.

Usage

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

License:Open Source License

/**
 * Instance for object./*from  w w w  .  j  a  va2  s  . co 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.vvote.thirdparty.ximix.util.BLSPublicKeyFactory.java

License:Apache License

/**
 * Create BLS01PublicKeyParameters from an ASN.1 encoding of a SubjectPublicKeyInfo object.
 *
 * @param publicKeyInfo the info structure containing the BLS public key.
 * @return a BLS public key./*  w w w. j av a  2s.  c  om*/
 */
public static BLS01PublicKeyParameters createKey(SubjectPublicKeyInfo publicKeyInfo) {
    AlgorithmIdentifier algId = publicKeyInfo.getAlgorithm();
    CurveParameters curveParameters;
    Element G;
    Pairing pairing;
    try {
        ASN1Sequence parameters = ASN1Sequence.getInstance(algId.getParameters());

        curveParameters = new DefaultCurveParameters().load(new ByteArrayInputStream(
                DERUTF8String.getInstance(parameters.getObjectAt(0)).getString().getBytes("UTF8")));
        pairing = PairingFactory.getPairing(curveParameters);
        G = pairing.getG2().newElement();
        G.setFromBytes(DEROctetString.getInstance(parameters.getObjectAt(1)).getOctets());
    } catch (IOException e) {
        throw new IllegalStateException("Unable to support encoding: " + e.getMessage(), e);
    }

    BLS01Parameters blsParameters = new BLS01Parameters(curveParameters, G.getImmutable());
    Element pK = pairing.getG2().newElement();

    pK.setFromBytes(publicKeyInfo.getPublicKeyData().getBytes());

    return new BLS01PublicKeyParameters(blsParameters, pK.getImmutable());
}

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

License:Open Source License

String getSubjectAltNameOtherNameUPN() {
    Collection<List<?>> generalNames = null;
    try {// www.  ja  v a2s .c  om
        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 w w .j  ava2 s. c  o  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:net.sf.keystore_explorer.crypto.x509.GeneralNameUtil.java

License:Open Source License

/**
 * Parse UPN/otherName/*from w w  w .j  a  va  2 s.co m*/
 *
 * @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 .j av  a2s  .  c o  m*/
 * @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.certificates.certificate.request.PKCS10RequestMessage.java

License:Open Source License

@Override
public String getPassword() {
    if (password != null) {
        return password;
    }//  w w  w  .  jav a 2s .c om
    try {
        if (pkcs10 == null) {
            init();
        }
    } catch (NullPointerException e) {
        log.error("PKCS10 not initated! " + e.getMessage());
        return null;
    }

    String ret = null;
    Attribute[] attributes = pkcs10.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_challengePassword);
    ASN1Encodable obj = null;
    if (attributes.length == 0) {
        // See if we have it embedded in an extension request instead
        attributes = pkcs10.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        if (attributes.length == 0) {
            return null;
        }
        if (log.isDebugEnabled()) {
            log.debug("got extension request");
        }
        ASN1Set values = attributes[0].getAttrValues();
        if (values.size() == 0) {
            return null;
        }
        Extensions exts = Extensions.getInstance(values.getObjectAt(0));
        Extension ext = exts.getExtension(PKCSObjectIdentifiers.pkcs_9_at_challengePassword);
        if (ext == null) {
            if (log.isDebugEnabled()) {
                log.debug("no challenge password extension");
            }
            return null;
        }
        obj = ext.getExtnValue();
    } else {
        // If it is a challengePassword directly, it's just to grab the value
        ASN1Set values = attributes[0].getAttrValues();
        obj = values.getObjectAt(0);
    }

    if (obj != null) {
        ASN1String str = null;

        try {
            str = DERPrintableString.getInstance((obj));
        } catch (IllegalArgumentException ie) {
            // This was not printable string, should be utf8string then according to pkcs#9 v2.0
            str = DERUTF8String.getInstance((obj));
        }

        if (str != null) {
            ret = str.getString();
        }
    }

    return ret;
}

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

License:Open Source License

/**
 * Helper method for the above method/*w  w w  .  j  av a  2  s .  com*/
 * 
 * @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;
}

From source file:org.cryptoworkshop.ximix.client.connection.ClientCommandService.java

License:Apache License

private String getHostName(final String boardName) throws ServiceConnectionException {
    if (!boardHostCache.containsKey(boardName)) {
        FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() {
            @Override//from  w  w  w  .  j  av  a  2  s .c om
            public String call() throws Exception {

                MessageReply reply;

                try {
                    reply = connection.sendMessage(CommandMessage.Type.GET_BOARD_HOST,
                            new BoardMessage(boardName));
                } catch (ServiceConnectionException e) {
                    eventNotifier.notify(EventNotifier.Level.ERROR, "Exception on upload: " + e.getMessage(),
                            e);

                    return "Exception on GET_BOARD_HOST: " + e.getMessage();
                }

                return (reply.getType() == MessageReply.Type.OKAY)
                        ? DERUTF8String.getInstance(reply.getPayload()).getString()
                        : reply.interpretPayloadAsError();
            }
        });

        if (boardHostCache.putIfAbsent(boardName, futureTask) == null) {
            executor.submit(futureTask);
        }
    }

    try {
        return boardHostCache.get(boardName).get();
    } catch (InterruptedException e) {
        boardHostCache.remove(boardName);
        eventNotifier.notify(EventNotifier.Level.ERROR, "Exception on getHostName(): " + e.getMessage(), e);
        Thread.currentThread().interrupt();
        throw new ServiceConnectionException(e.getMessage(), e);
    } catch (ExecutionException e) {
        boardHostCache.remove(boardName);
        eventNotifier.notify(EventNotifier.Level.ERROR, "Exception on getHostName(): " + e.getMessage(), e);
        throw new ServiceConnectionException(e.getMessage(), e);
    }
}

From source file:org.cryptoworkshop.ximix.client.connection.signing.message.BLSPartialCreateMessage.java

License:Apache License

private BLSPartialCreateMessage(ASN1Sequence seq) {
    this.keyID = DERUTF8String.getInstance(seq.getObjectAt(0)).getString();
    this.h = ASN1OctetString.getInstance(seq.getObjectAt(1));
    this.nodesToUse = MessageUtils.toArray(ASN1Sequence.getInstance(seq.getObjectAt(2)));
}