Example usage for org.bouncycastle.asn1 DEROctetString getOctets

List of usage examples for org.bouncycastle.asn1 DEROctetString getOctets

Introduction

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

Prototype

public byte[] getOctets() 

Source Link

Document

Return the content of the OCTET STRING as a byte array.

Usage

From source file:br.gov.frameworkdemoiselle.certificate.extension.BasicCertificate.java

License:Open Source License

/**
 * Returns the DERObject for the informed OID<br>
 * atraves do OID.<br>//  ww w.j  av a 2 s  .c o m
 *
 * @param oid
 * @return DERObject
 * @see DERObject
 */
public DERObject getExtensionValue(String oid) {
    byte[] extvalue = certificate.getExtensionValue(oid);
    if (extvalue == null) {
        return null;
    }
    try {
        DEROctetString oct = (DEROctetString) (new ASN1InputStream(extvalue).readObject());
        return (new ASN1InputStream(oct.getOctets()).readObject());
    } catch (IOException ex) {
        LOGGER.info(ex.getMessage());
    }
    return null;
}

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

License:Open Source License

/**
 * Instance for object.// ww  w .jav 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:br.gov.frameworkdemoiselle.certificate.signer.util.ValidadorUtil.java

License:Open Source License

public static void validate(X509Certificate certificate) {
    /*/*from  w  ww. java  2s.co  m*/
     * Assinaturas digitais geradas segundo esta Poltica de Assinatura
     * devero ser criadas com chave privada associada ao certificado
     * ICP-Brasil * tipo A1 (do OID 2.16.76.1.2.1.1 ao OID
     * 2.16.76.1.2.1.100), tipo A2 (do OID 2.16.76.1.2.2.1 ao OID
     * 2.16.76.1.2.2.100), do tipo A3 (do OID 2.16.76.1.2.3.1 ao OID
     * 2.16.76.1.2.3.100) e do tipo A4 (do OID 2.16.76.1.2.4.1 ao OID
     * 2.16.76.1.2.4.100), conforme definido em DOC-ICP-04.
     */

    try {
        byte[] val1 = certificate.getExtensionValue("2.5.29.32");
        ASN1InputStream ans1InputStream = new ASN1InputStream(new ByteArrayInputStream(val1));
        DERObject derObject = ans1InputStream.readObject();
        ans1InputStream.close();
        DEROctetString derOctetString = (DEROctetString) derObject;
        byte[] val2 = derOctetString.getOctets();
        ASN1InputStream asn1InputStream2 = new ASN1InputStream(new ByteArrayInputStream(val2));
        DERObject derObject2 = asn1InputStream2.readObject();
        asn1InputStream2.close();
        DERSequence derSequence = (DERSequence) derObject2;
        DERSequence derObject3 = (DERSequence) derSequence.getObjectAt(0).getDERObject();
        DERObjectIdentifier objectIdentifier = (DERObjectIdentifier) derObject3.getObjectAt(0);
        String identificador = objectIdentifier.toString();

        if (!(identificador.startsWith("2.16.76.1.2.1.") || identificador.startsWith("2.16.76.1.2.2.")
                || identificador.startsWith("2.16.76.1.2.3.") || identificador.startsWith("2.16.76.1.2.4."))) {
            throw new SignerException("O OID no corresponde a uma Poltica de Certificado.");
        }

        int sufixo = Integer.parseInt(identificador.substring(identificador.lastIndexOf(".") + 1));
        if (sufixo < 1 || sufixo > 100) {
            throw new SignerException("O certificado deve ser do tipo A1, A2, A3 ou A4.");
        }

    } catch (Throwable error) {
        throw new SignerException(
                "A assinaturas digital deve ser criada com chave privada associada ao certificado ICP-Brasil tipo A1, A2, A3 ou A4",
                error);
    }
}

From source file:ch.bfh.unicert.certimport.CertificateHelper.java

License:GNU General Public License

/**
 * Converts a DER encoded octet string into a String
 * @param der DER formatted string/*w  w  w.ja  va 2s  . c  o m*/
 * @return the converted string
 */
public static String DERToString(DEROctetString der) {
    //4 first byte are header information
    byte[] stringContent = Arrays.copyOfRange(der.getOctets(), 2, der.getOctets().length);
    return new String(stringContent);
}

From source file:com.codename1.payments.GooglePlayValidator.java

/**
 * Generates a private key from a PKCS#8 encoded string.
 * @param key/*from ww w.j  a v  a  2 s .  c  o m*/
 * @return 
 */
private RSAPrivateKey getRSAPrivateKey(String key) {

    String privKeyPEM = key.replace("-----BEGIN PRIVATE KEY-----\n", "").replace("-----END PRIVATE KEY-----",
            "");
    try {
        byte[] encodedPrivateKey = Base64.decode(privKeyPEM.getBytes("UTF-8"));
        ASN1Sequence primitive = (ASN1Sequence) ASN1Sequence.fromByteArray(encodedPrivateKey);
        Enumeration<?> e = primitive.getObjects();
        BigInteger v = ((ASN1Integer) e.nextElement()).getValue();

        int version = v.intValue();
        if (version != 0 && version != 1) {
            throw new IllegalArgumentException("wrong version for RSA private key");
        }
        e.nextElement();
        DEROctetString octetString = (DEROctetString) e.nextElement();

        encodedPrivateKey = octetString.getOctets();
        primitive = (ASN1Sequence) ASN1Sequence.fromByteArray(encodedPrivateKey);
        return RSAPrivateKey.getInstance(primitive);

    } catch (Exception e2) {
        throw new RuntimeException(e2);
    }

}

From source file:com.google.u2f.server.impl.U2FServerReferenceImpl.java

License:Open Source License

/**
 * Parses a transport extension from an attestation certificate and returns
 * a List of HardwareFeatures supported by the security key. The specification of
 * the HardwareFeatures in the certificate should match their internal definition in
 * device_auth.proto//w  w w  . j a va 2 s. c  o  m
 *
 * <p>The expected transport extension value is a BIT STRING containing the enabled
 * transports:
 *
 *  <p>FIDOU2FTransports ::= BIT STRING {
 *       bluetoothRadio(0), -- Bluetooth Classic
 *       bluetoothLowEnergyRadio(1),
 *       uSB(2),
 *       nFC(3)
 *     }
 *
 *   <p>Note that the BIT STRING must be wrapped in an OCTET STRING.
 *   An extension that encodes BT, BLE, and NFC then looks as follows:
 *
 *   <p>SEQUENCE (2 elem)
 *      OBJECT IDENTIFIER 1.3.6.1.4.1.45724.2.1.1
 *      OCTET STRING (1 elem)
 *        BIT STRING (4 bits) 1101
 *
 * @param cert the certificate to parse for extension
 * @return the supported transports as a List of HardwareFeatures or null if no extension
 * was found
 */
public static List<Transports> parseTransportsExtension(X509Certificate cert)
        throws CertificateParsingException {
    byte[] extValue = cert.getExtensionValue(TRANSPORT_EXTENSION_OID);
    LinkedList<Transports> transportsList = new LinkedList<Transports>();
    if (extValue == null) {
        // No transports extension found.
        return null;
    }

    ASN1InputStream ais = new ASN1InputStream(extValue);
    ASN1Object asn1Object;
    // Read out the OctetString
    try {
        asn1Object = ais.readObject();
        ais.close();
    } catch (IOException e) {
        throw new CertificateParsingException("Not able to read object in transports extenion", e);
    }

    if (asn1Object == null || !(asn1Object instanceof DEROctetString)) {
        throw new CertificateParsingException("No Octet String found in transports extension");
    }
    DEROctetString octet = (DEROctetString) asn1Object;

    // Read out the BitString
    ais = new ASN1InputStream(octet.getOctets());
    try {
        asn1Object = ais.readObject();
        ais.close();
    } catch (IOException e) {
        throw new CertificateParsingException("Not able to read object in transports extension", e);
    }
    if (asn1Object == null || !(asn1Object instanceof DERBitString)) {
        throw new CertificateParsingException("No BitString found in transports extension");
    }
    DERBitString bitString = (DERBitString) asn1Object;

    byte[] values = bitString.getBytes();
    BitSet bitSet = BitSet.valueOf(values);

    // We might have more defined transports than used by the extension
    for (int i = 0; i < BITS_IN_A_BYTE; i++) {
        if (bitSet.get(BITS_IN_A_BYTE - i - 1)) {
            transportsList.add(Transports.values()[i]);
        }
    }
    return transportsList;
}

From source file:com.igeekinc.indelible.indeliblefs.security.EntityAuthenticationClient.java

License:Open Source License

public static DataMoverSessionID getSessionIDFromCertificate(X509Certificate checkCert) throws IOException {
    byte[] checkSessionIDBytesEncoded = checkCert
            .getExtensionValue(X509Extensions.SubjectAlternativeName.toString());
    ASN1InputStream decoder = new ASN1InputStream(new ByteArrayInputStream(checkSessionIDBytesEncoded));
    DERObject checkObject = decoder.readObject();
    DEROctetString checkOctetString = (DEROctetString) checkObject;
    byte[] checkSessionIDBytes = checkOctetString.getOctets();
    DataMoverSessionID checkSessionID = (DataMoverSessionID) ObjectIDFactory
            .reconstituteFromBytes(checkSessionIDBytes);
    return checkSessionID;
}

From source file:com.infinities.keystone4j.ssl.CRLVerifier.java

License:Apache License

/**
 * Extracts all CRL distribution point URLs from the
 * "CRL Distribution Point" extension in a X.509 certificate. If CRL
 * distribution point extension is unavailable, returns an empty list.
 */// w  w w . jav  a  2s  . c  o  m
public static List<String> getCrlDistributionPoints(X509Certificate cert)
        throws CertificateParsingException, IOException {
    byte[] crldpExt = cert.getExtensionValue(X509Extension.cRLDistributionPoints.getId());
    if (crldpExt == null) {
        return new ArrayList<String>();
    }
    ASN1InputStream oAsnInStream = null;
    ASN1InputStream oAsnInStream2 = null;
    try {
        oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(crldpExt));
        DERObject derObjCrlDP = oAsnInStream.readObject();
        DEROctetString dosCrlDP = (DEROctetString) derObjCrlDP;
        byte[] crldpExtOctets = dosCrlDP.getOctets();
        oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(crldpExtOctets));
        DERObject derObj2 = oAsnInStream2.readObject();
        CRLDistPoint distPoint = CRLDistPoint.getInstance(derObj2);
        List<String> crlUrls = new ArrayList<String>();
        for (DistributionPoint dp : distPoint.getDistributionPoints()) {
            DistributionPointName dpn = dp.getDistributionPoint();
            // Look for URIs in fullName
            if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) {
                GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames();
                // Look for an URI
                for (int j = 0; j < genNames.length; j++) {
                    if (genNames[j].getTagNo() == GeneralName.uniformResourceIdentifier) {
                        String url = DERIA5String.getInstance(genNames[j].getName()).getString();
                        crlUrls.add(url);
                    }
                }
            }
        }
        return crlUrls;
    } finally {
        if (oAsnInStream != null) {
            oAsnInStream.close();
        }

        if (oAsnInStream2 != null) {
            oAsnInStream2.close();
        }
    }
}

From source file:com.itextpdf.signatures.CertificateUtil.java

License:Open Source License

/**
 * Gets the URL of the TSA if it's available on the certificate
 * @param certificate   a certificate// ww w  . j  a v  a 2s .co  m
 * @return   a TSA URL
 * @throws IOException
 */
public static String getTSAURL(X509Certificate certificate) {
    byte[] der = SignUtils.getExtensionValueByOid(certificate, SecurityIDs.ID_TSA);
    if (der == null)
        return null;
    ASN1Primitive asn1obj;
    try {
        asn1obj = ASN1Primitive.fromByteArray(der);
        DEROctetString octets = (DEROctetString) asn1obj;
        asn1obj = ASN1Primitive.fromByteArray(octets.getOctets());
        ASN1Sequence asn1seq = ASN1Sequence.getInstance(asn1obj);
        return getStringFromGeneralName(asn1seq.getObjectAt(1).toASN1Primitive());
    } catch (IOException e) {
        return null;
    }
}

From source file:com.itextpdf.text.pdf.PdfPKCS7.java

License:Open Source License

private void findOcsp(ASN1Sequence seq) throws IOException {
    basicResp = null;//from ww  w.j a  v  a 2  s .c  o m
    boolean ret = false;
    while (true) {
        if (seq.getObjectAt(0) instanceof DERObjectIdentifier && ((DERObjectIdentifier) seq.getObjectAt(0))
                .getId().equals(OCSPObjectIdentifiers.id_pkix_ocsp_basic.getId())) {
            break;
        }
        ret = true;
        for (int k = 0; k < seq.size(); ++k) {
            if (seq.getObjectAt(k) instanceof ASN1Sequence) {
                seq = (ASN1Sequence) seq.getObjectAt(0);
                ret = false;
                break;
            }
            if (seq.getObjectAt(k) instanceof ASN1TaggedObject) {
                ASN1TaggedObject tag = (ASN1TaggedObject) seq.getObjectAt(k);
                if (tag.getObject() instanceof ASN1Sequence) {
                    seq = (ASN1Sequence) tag.getObject();
                    ret = false;
                    break;
                } else
                    return;
            }
        }
        if (ret)
            return;
    }
    DEROctetString os = (DEROctetString) seq.getObjectAt(1);
    ASN1InputStream inp = new ASN1InputStream(os.getOctets());
    BasicOCSPResponse resp = BasicOCSPResponse.getInstance(inp.readObject());
    basicResp = new BasicOCSPResp(resp);
}