Example usage for org.bouncycastle.asn1 ASN1InputStream readObject

List of usage examples for org.bouncycastle.asn1 ASN1InputStream readObject

Introduction

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

Prototype

public ASN1Primitive readObject() throws IOException 

Source Link

Usage

From source file:mx.bigdata.cfdi.CFDv3Debugger.java

License:Apache License

public void dumpDigests() throws Exception {
    System.err.println(cfd.getOriginalString());
    byte[] digest = cfd.getDigest();
    CFDv3.dump("Digestion generada", digest, System.err);
    String certStr = cfd.document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);
    X509Certificate cert = KeyLoader.loadX509Certificate(new ByteArrayInputStream(cbs));
    cert.checkValidity();/*from  w  ww.jav a  2  s .  co  m*/
    String sigStr = cfd.document.getSello();
    byte[] signature = b64.decode(sigStr);
    CFDv3.dump("Digestion firmada", signature, System.err);
    Cipher dec = Cipher.getInstance("RSA");
    dec.init(Cipher.DECRYPT_MODE, cert);
    byte[] result = dec.doFinal(signature);
    CFDv3.dump("Digestion decriptada", result, System.err);
    ASN1InputStream aIn = new ASN1InputStream(result);
    ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
    ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
    CFDv3.dump("Sello", sigHash.getOctets(), System.err);
}

From source file:mx.bigdata.sat.cfdi.CFDv3Debugger.java

License:Apache License

private void dumpDigests() throws Exception {
    System.err.println(cfd.getCadenaOriginal());
    String certStr = cfd.document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);
    X509Certificate cert = (X509Certificate) KeyLoaderFactory
            .createInstance(KeyLoaderEnumeration.PUBLIC_KEY_LOADER, new ByteArrayInputStream(cbs)).getKey();
    cert.checkValidity();//  w ww . j  a  v a 2s  .  c  o  m
    String sigStr = cfd.document.getSello();
    byte[] signature = b64.decode(sigStr);
    CFDv3.dump("Digestion firmada", signature, System.err);
    Cipher dec = Cipher.getInstance("RSA");
    dec.init(Cipher.DECRYPT_MODE, cert);
    byte[] result = dec.doFinal(signature);
    CFDv3.dump("Digestion decriptada", result, System.err);
    ASN1InputStream aIn = new ASN1InputStream(result);
    ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
    ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
    CFDv3.dump("Sello", sigHash.getOctets(), System.err);
}

From source file:nDasJoWo.signapk.SignApk.java

License:Apache License

private static void writeSignatureBlock(CMSTypedData paramCMSTypedData, X509Certificate paramX509Certificate,
        PrivateKey paramPrivateKey, OutputStream paramOutputStream)
        throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {
    ArrayList localArrayList = new ArrayList(1);
    localArrayList.add(paramX509Certificate);
    JcaCertStore localJcaCertStore = new JcaCertStore(localArrayList);

    CMSSignedDataGenerator localCMSSignedDataGenerator = new CMSSignedDataGenerator();
    ContentSigner localContentSigner = new JcaContentSignerBuilder("SHA1withRSA")
            .setProvider(sBouncyCastleProvider).build(paramPrivateKey);

    localCMSSignedDataGenerator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().setProvider(sBouncyCastleProvider).build())
                    .setDirectSignature(true).build(localContentSigner, paramX509Certificate));

    localCMSSignedDataGenerator.addCertificates(localJcaCertStore);
    CMSSignedData localCMSSignedData = localCMSSignedDataGenerator.generate(paramCMSTypedData, false);

    ASN1InputStream localASN1InputStream = new ASN1InputStream(localCMSSignedData.getEncoded());
    DEROutputStream localDEROutputStream = new DEROutputStream(paramOutputStream);
    localDEROutputStream.writeObject(localASN1InputStream.readObject());
}

From source file:net.jradius.client.auth.EAPTLSAuthenticator.java

License:Open Source License

/**
 * Initializs the SSL layer.// w  ww  .  j av  a 2  s  . c om
 * @throws Exception 
 * @throws FileNotFoundException 
 */
public void init() throws RadiusException {
    try {
        if (getKeyFile() != null) {
            keyManagers = KeyStoreUtil.loadKeyManager(getKeyFileType(), new FileInputStream(getKeyFile()),
                    getKeyPassword());
        }

        if (getTrustAll().booleanValue()) {
            trustManagers = KeyStoreUtil.trustAllManager();
        } else if (getCaFile() != null) {
            trustManagers = KeyStoreUtil.loadTrustManager(getCaFileType(), new FileInputStream(getCaFile()),
                    getCaPassword());
        }

        tlsClient = new DefaultTlsClient(verifyer);

        try {
            if (keyManagers != null && keyManagers.length > 0) {
                X509CertificateStructure[] certs = null;
                X509Certificate[] certChain = ((X509KeyManager) keyManagers[0]).getCertificateChain("");
                PrivateKey key = ((X509KeyManager) keyManagers[0]).getPrivateKey("");
                Vector tmp = new Vector();

                for (X509Certificate cert : certChain) {
                    ByteArrayInputStream bis = new ByteArrayInputStream(cert.getEncoded());
                    ASN1InputStream ais = new ASN1InputStream(bis);
                    DERObject o = ais.readObject();
                    tmp.addElement(X509CertificateStructure.getInstance(o));
                    if (bis.available() > 0) {
                        throw new IllegalArgumentException(
                                "Sorry, there is garbage data left after the certificate");
                    }
                }
                certs = new X509CertificateStructure[tmp.size()];
                for (int i = 0; i < tmp.size(); i++) {
                    certs[i] = (X509CertificateStructure) tmp.elementAt(i);
                }

                tlsClient.enableClientAuthentication(new Certificate(certs), createKey(key.getEncoded()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        handler.setSendCertificate(isCertificateRequired());
        handler.setKeyManagers(keyManagers);
        handler.setTrustManagers(trustManagers);
    } catch (Exception e) {
        e.printStackTrace();
    }

    /*
     try
     {
    KeyManager keyManagers[] = null;
    TrustManager trustManagers[] = null;
            
    if (getKeyFile() != null)
    {
        KeyStore ksKeys = KeyStore.getInstance(getKeyFileType());
        ksKeys.load(new FileInputStream(getKeyFile()), getKeyPassword().toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ksKeys, getKeyPassword().toCharArray());
                
        keyManagers = kmf.getKeyManagers();
    }
            
    if (getCaFile() != null)
    {
        KeyStore caKeys = KeyStore.getInstance(getCaFileType());
        caKeys.load(new FileInputStream(getCaFile()), getCaPassword().toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(caKeys);
                
        trustManagers = tmf.getTrustManagers();
    }
    else 
    {
        if (getTrustAll().booleanValue()) 
        {
            trustManagers = new TrustManager[]{ new NoopX509TrustManager() };
        }
    }
     }
     catch (Exception e)
     {
    throw new RadiusException(e);
     }
     */
}

From source file:net.maritimecloud.identityregistry.keycloak.spi.authenticators.certificate.utils.CertificateUtil.java

License:Apache License

public Map<String, String> getUserFromCert(X509Certificate userCertificate) {
    Map<String, String> user = new HashMap<>();
    String certDN = userCertificate.getSubjectDN().getName();
    X500Name x500name = new X500Name(certDN);
    logger.warn("Parsed certificate, DN: " + certDN);
    String fullname = getElement(x500name, BCStyle.CN);
    user.put("fullname", fullname);
    String combinedOrg = getElement(x500name, BCStyle.O);
    user.put("email", getElement(x500name, BCStyle.EmailAddress));
    // Extract first and last name from full name
    String lastName = "";
    String firstName = "";
    if (fullname.split("\\w+").length > 1) {
        lastName = fullname.substring(fullname.lastIndexOf(" ") + 1);
        firstName = fullname.substring(0, fullname.lastIndexOf(' '));
    } else {/*from w w w.ja va  2  s. c  o  m*/
        firstName = fullname;
    }
    user.put("lastName", lastName);
    user.put("firstName", firstName);
    String[] orgNames = combinedOrg.split(";");
    String orgShortName = orgNames[0].toLowerCase();
    user.put("orgShortName", orgShortName);
    user.put("orgFullName", orgNames[1]);
    // prefix orgUserName with org shortname if not already done
    String orgUserName = getElement(x500name, BCStyle.UID).toLowerCase();
    if (!orgUserName.startsWith(orgShortName + ".")) {
        orgUserName = orgShortName.toLowerCase() + "." + orgUserName;
    }
    user.put("orgUserName", orgUserName);
    user.put("type", getElement(x500name, BCStyle.OU));
    // Extract info from Subject Alternative Name extension
    Collection<List<?>> san = null;
    try {
        san = userCertificate.getSubjectAlternativeNames();
    } catch (CertificateParsingException e) {
        logger.warn("could not extract info from Subject Alternative Names - will be ignored.");
    }
    // Check that the certificate includes the SubjectAltName extension
    if (san != null) {
        // Use the type OtherName to search for the certified server name
        for (List item : san) {
            Integer type = (Integer) item.get(0);
            if (type == 0) {
                // Type OtherName found so return the associated value
                ASN1InputStream decoder = null;
                String oid = "";
                String value = "";
                try {
                    // Value is encoded using ASN.1 so decode it to get it out again
                    decoder = new ASN1InputStream((byte[]) item.toArray()[1]);
                    DLSequence seq = (DLSequence) decoder.readObject();
                    ASN1ObjectIdentifier asnOID = (ASN1ObjectIdentifier) seq.getObjectAt(0);
                    ASN1Encodable encoded = seq.getObjectAt(1);
                    encoded = ((DERTaggedObject) encoded).getObject();
                    encoded = ((DERTaggedObject) encoded).getObject();
                    oid = asnOID.getId();
                    value = ((DERUTF8String) encoded).getString();
                } catch (UnsupportedEncodingException e) {
                    logger.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e);
                    continue;
                } catch (Exception e) {
                    logger.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e);
                    continue;
                } finally {
                    if (decoder != null) {
                        try {
                            decoder.close();
                        } catch (IOException e) {
                        }
                    }
                }
                logger.debug("oid: " + oid + ", value: " + value);
                switch (oid) {
                case MC_OID_FLAGSTATE:
                case MC_OID_CALLSIGN:
                case MC_OID_IMO_NUMBER:
                case MC_OID_MMSI_NUMBER:
                case MC_OID_AIS_SHIPTYPE:
                case MC_OID_PORT_OF_REGISTER:
                    logger.debug("Ship specific OIDs are ignored");
                    break;
                case MC_OID_MRN:
                    // We only support 1 mrn
                    user.put("mrn", value);
                    break;
                case MC_OID_PERMISSIONS:
                    user.put("permissions", value);
                    break;
                default:
                    logger.error("Unknown OID!");
                    break;
                }
            } else {
                // Other types are not supported so ignore them
                logger.warn("SubjectAltName of invalid type found: " + type);
            }
        }
    }
    return user;
}

From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java

License:Apache License

public UserDetails getUserFromCert(X509Certificate userCertificate) {
    String certDN = userCertificate.getSubjectDN().getName();
    X500Name x500name = new X500Name(certDN);
    InetOrgPerson.Essence essence = new InetOrgPerson.Essence();
    String name = getElement(x500name, BCStyle.CN);
    String uid = getElement(x500name, BCStyle.UID);
    essence.setUsername(uid);//from w w  w  .j  a  v a 2s  . c o  m
    essence.setUid(uid);
    essence.setDn(certDN);
    essence.setCn(new String[] { name });
    essence.setSn(name);
    essence.setO(getElement(x500name, BCStyle.O));
    essence.setOu(getElement(x500name, BCStyle.OU));
    essence.setDescription(certDN);
    // Hack alert! There is no country property in this type, so we misuse PostalAddress...
    essence.setPostalAddress(getElement(x500name, BCStyle.C));
    log.debug("Parsed certificate, name: " + name);

    // Extract info from Subject Alternative Name extension
    Collection<List<?>> san = null;
    try {
        san = userCertificate.getSubjectAlternativeNames();
    } catch (CertificateParsingException e) {
        log.warn("could not extract info from Subject Alternative Names - will be ignored.");
    }
    // Check that the certificate includes the SubjectAltName extension
    if (san != null) {
        // Use the type OtherName to search for the certified server name
        Collection<GrantedAuthority> roles = new ArrayList<>();
        for (List item : san) {
            Integer type = (Integer) item.get(0);
            if (type == 0) {
                // Type OtherName found so return the associated value
                ASN1InputStream decoder = null;
                String oid = "";
                String value = "";
                try {
                    // Value is encoded using ASN.1 so decode it to get it out again
                    decoder = new ASN1InputStream((byte[]) item.toArray()[1]);
                    DLSequence seq = (DLSequence) decoder.readObject();
                    ASN1ObjectIdentifier asnOID = (ASN1ObjectIdentifier) seq.getObjectAt(0);
                    ASN1Encodable encoded = seq.getObjectAt(1);
                    encoded = ((DERTaggedObject) encoded).getObject();
                    encoded = ((DERTaggedObject) encoded).getObject();
                    oid = asnOID.getId();
                    value = ((DERUTF8String) encoded).getString();
                } catch (UnsupportedEncodingException e) {
                    log.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e);
                    continue;
                } catch (Exception e) {
                    log.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e);
                    continue;
                } finally {
                    if (decoder != null) {
                        try {
                            decoder.close();
                        } catch (IOException e) {
                        }
                    }
                }
                log.debug("oid: " + oid + ", value: " + value);
                switch (oid) {
                case MC_OID_FLAGSTATE:
                case MC_OID_CALLSIGN:
                case MC_OID_IMO_NUMBER:
                case MC_OID_MMSI_NUMBER:
                case MC_OID_AIS_SHIPTYPE:
                case MC_OID_PORT_OF_REGISTER:
                    log.debug("Ship specific OIDs are ignored");
                    break;
                case MC_OID_MRN:
                    // We only support 1 mrn
                    essence.setUid(value);
                    break;
                case MC_OID_PERMISSIONS:
                    if (value != null && !value.trim().isEmpty()) {
                        SimpleGrantedAuthority role = new SimpleGrantedAuthority(value);
                        roles.add(role);
                    }
                    break;
                default:
                    log.error("Unknown OID!");
                    break;
                }
            } else {
                // Other types are not supported so ignore them
                log.warn("SubjectAltName of invalid type found: " + type);
            }
        }
        if (!roles.isEmpty()) {
            essence.setAuthorities(roles);
        }
    }
    return essence.createUserDetails();
}

From source file:net.maritimecloud.pki.CertificateHandler.java

License:Apache License

/**
 * Extracts a PKIIdentity from a certificate using the MC PKI certificate "format"
 *
 * @param userCertificate The certificate
 * @return The extracted identity//from   www . j a  v  a 2 s. c o m
 */
public static PKIIdentity getIdentityFromCert(X509Certificate userCertificate) {
    PKIIdentity identity = new PKIIdentity();
    String certDN = userCertificate.getSubjectDN().getName();
    X500Name x500name = new X500Name(certDN);
    String name = getElement(x500name, BCStyle.CN);
    String uid = getElement(x500name, BCStyle.UID);
    identity.setMrn(uid);
    identity.setDn(certDN);
    identity.setCn(name);
    identity.setSn(name);
    identity.setO(getElement(x500name, BCStyle.O));
    identity.setOu(getElement(x500name, BCStyle.OU));
    identity.setCountry(getElement(x500name, BCStyle.C));
    identity.setEmail(getElement(x500name, BCStyle.EmailAddress));
    // Extract first and last name from full name
    String lastName = "";
    String firstName = "";
    if (name.split("\\w +\\w").length > 1) {
        lastName = name.substring(name.lastIndexOf(" ") + 1);
        firstName = name.substring(0, name.lastIndexOf(' '));
    } else {
        firstName = name;
    }
    identity.setFirstName(firstName);
    identity.setLastName(lastName);
    log.debug("Parsed certificate, name: " + name);

    // Extract info from Subject Alternative Name extension
    Collection<List<?>> san = null;
    try {
        san = userCertificate.getSubjectAlternativeNames();
    } catch (CertificateParsingException e) {
        log.warn("could not extract info from Subject Alternative Names - will be ignored.");
    }
    // Check that the certificate includes the SubjectAltName extension
    if (san != null) {
        // Use the type OtherName to search for the certified server name
        StringBuilder permissions = new StringBuilder();
        for (List item : san) {
            Integer type = (Integer) item.get(0);
            if (type == 0) {
                // Type OtherName found so return the associated value
                ASN1InputStream decoder = null;
                String oid;
                String value;
                try {
                    // Value is encoded using ASN.1 so decode it to get it out again
                    decoder = new ASN1InputStream((byte[]) item.toArray()[1]);
                    DLSequence seq = (DLSequence) decoder.readObject();
                    ASN1ObjectIdentifier asnOID = (ASN1ObjectIdentifier) seq.getObjectAt(0);
                    ASN1Encodable encoded = seq.getObjectAt(1);
                    oid = asnOID.getId();
                    // For some weird reason we need to do this 2 times - otherwise we get a
                    // ClassCastException when extracting the value.
                    encoded = ((DERTaggedObject) encoded).getObject();
                    encoded = ((DERTaggedObject) encoded).getObject();
                    value = ((DERUTF8String) encoded).getString();
                } catch (UnsupportedEncodingException e) {
                    log.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e);
                    continue;
                } catch (Exception e) {
                    log.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e);
                    continue;
                } finally {
                    if (decoder != null) {
                        try {
                            decoder.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                log.debug("oid: " + oid + ", value: " + value);
                switch (oid) {
                case MC_OID_FLAGSTATE:
                    identity.setFlagState(value);
                    break;
                case MC_OID_CALLSIGN:
                    identity.setCallSign(value);
                    break;
                case MC_OID_IMO_NUMBER:
                    identity.setImoNumber(value);
                    break;
                case MC_OID_MMSI_NUMBER:
                    identity.setMmsiNumber(value);
                    break;
                case MC_OID_AIS_SHIPTYPE:
                    identity.setAisShipType(value);
                    break;
                case MC_OID_PORT_OF_REGISTER:
                    identity.setPortOfRegister(value);
                    break;
                case MC_OID_MRN:
                    // We only support 1 mrn
                    identity.setMrn(value);
                    break;
                case MC_OID_SHIP_MRN:
                    identity.setShipMrn(value);
                case MC_OID_PERMISSIONS:
                    if (value != null && !value.trim().isEmpty()) {
                        if (permissions.length() == 0) {
                            permissions = new StringBuilder(value);
                        } else {
                            permissions.append(',').append(value);
                        }
                    }
                    break;
                default:
                    log.error("Unknown OID!");
                    break;
                }
            } else {
                // Other types are not supported so ignore them
                log.warn("SubjectAltName of invalid type found: " + type);
            }
        }
        if (permissions.length() > 0) {
            identity.setPermissions(permissions.toString());
        }
    }
    return identity;
}

From source file:net.maritimecloud.pki.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.
 *///from w  w w . ja  v a  2  s  .com
public static List<String> getCrlDistributionPoints(X509Certificate cert)
        throws CertificateParsingException, IOException {
    byte[] crldpExt = cert.getExtensionValue(Extension.cRLDistributionPoints.getId());
    if (crldpExt == null) {
        return new ArrayList<>();
    }
    ASN1InputStream oAsnInStream = new ASN1InputStream(crldpExt);
    DEROctetString dosCrlDP = (DEROctetString) oAsnInStream.readObject();
    byte[] crldpExtOctets = dosCrlDP.getOctets();
    ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(crldpExtOctets));
    CRLDistPoint crlDistPoint = CRLDistPoint.getInstance(oAsnInStream2.readObject());
    oAsnInStream.close();
    oAsnInStream2.close();
    List<String> crlUrls = new ArrayList<>();
    for (DistributionPoint dp : crlDistPoint.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 (GeneralName genName : genNames) {
                if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) {
                    String url = DERIA5String.getInstance(genName.getName()).getString();
                    crlUrls.add(url);
                }
            }
        }
    }
    return crlUrls;
}

From source file:net.ripe.rpki.commons.crypto.cms.RpkiSignedObjectParser.java

License:BSD License

private void parseContent(CMSSignedDataParser sp) {
    contentType = sp.getSignedContent().getContentType();

    InputStream signedContentStream = sp.getSignedContent().getContentStream();
    ASN1InputStream asn1InputStream = new ASN1InputStream(signedContentStream);

    try {//from ww w .  j av  a 2 s  .co m
        decodeContent(asn1InputStream.readObject());
    } catch (IOException e) {
        validationResult.rejectIfFalse(false, DECODE_CONTENT);
        return;
    }
    validationResult.rejectIfFalse(true, DECODE_CONTENT);

    try {
        validationResult.rejectIfFalse(asn1InputStream.readObject() == null, ONLY_ONE_SIGNED_OBJECT);
        asn1InputStream.close();
    } catch (IOException e) {
        validationResult.rejectIfFalse(false, CMS_CONTENT_PARSING);
    }
    validationResult.rejectIfFalse(true, CMS_CONTENT_PARSING);
}

From source file:net.ripe.rpki.commons.crypto.util.Asn1Util.java

License:BSD License

/**
 * Decodes the byte array extension using the {@link ASN1InputStream}.
 *//*from   www  . j av  a  2 s  .  com*/
public static ASN1Primitive decode(byte[] extension) {
    try {
        ASN1InputStream is = new ASN1InputStream(extension);
        return is.readObject();
    } catch (IOException e) {
        throw new Asn1UtilException("IO exception while decoding resource extension", e);
    }
}