Example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

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

Introduction

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

Prototype

public ASN1InputStream(byte[] input) 

Source Link

Document

Create an ASN1InputStream based on the input byte array.

Usage

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 a2  s  .  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 a  v a2 s.com*/
 * @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.jradius.client.auth.EAPTLSAuthenticator.java

License:Open Source License

/**
 * Create a private key parameter from a PKCS8 PrivateKeyInfo encoding read from a stream.
 * /*from ww  w  .j ava 2  s . c o  m*/
 * @param inStr the stream to read the PrivateKeyInfo encoding from
 * @return a suitable private key parameter
 * @throws IOException on an error decoding the key
 */
public static AsymmetricKeyParameter createKey(InputStream inStr) throws IOException {
    return createKey(PrivateKeyInfo.getInstance(new ASN1InputStream(inStr).readObject()));
}

From source file:net.jsign.timestamp.RFC3161Timestamper.java

License:Apache License

protected CMSSignedData timestamp(DigestAlgorithm algo, byte[] encryptedDigest)
        throws IOException, TimestampingException {
    TimeStampRequestGenerator reqgen = new TimeStampRequestGenerator();
    reqgen.setCertReq(true);/*from  w w w.j av a  2 s. c  om*/
    TimeStampRequest req = reqgen.generate(algo.oid, algo.getMessageDigest().digest(encryptedDigest));
    byte request[] = req.getEncoded();

    HttpURLConnection conn = (HttpURLConnection) tsaurl.openConnection();
    conn.setConnectTimeout(10000);
    conn.setReadTimeout(10000);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-type", "application/timestamp-query");
    conn.setRequestProperty("Content-length", String.valueOf(request.length));
    conn.setRequestProperty("Accept", "application/timestamp-query");
    conn.setRequestProperty("User-Agent", "Transport");

    conn.getOutputStream().write(request);
    conn.getOutputStream().flush();

    if (conn.getResponseCode() >= 400) {
        throw new IOException("Unable to complete the timestamping due to HTTP error: " + conn.getResponseCode()
                + " - " + conn.getResponseMessage());
    }

    try {
        TimeStampResp resp = TimeStampResp.getInstance(new ASN1InputStream(conn.getInputStream()).readObject());
        TimeStampResponse response = new TimeStampResponse(resp);
        response.validate(req);
        if (response.getStatus() != 0) {
            throw new IOException("Unable to complete the timestamping due to an invalid response ("
                    + response.getStatusString() + ")");
        }

        return response.getTimeStampToken().toCMSSignedData();

    } catch (Exception e) {
        throw new TimestampingException("Unable to complete the timestamping", e);
    }
}

From source file:net.link.util.common.KeyUtils.java

License:Open Source License

@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
private static SubjectKeyIdentifier createSubjectKeyId(PublicKey publicKey) {

    try {//  w  w  w .  ja v a2s.c o m
        ByteArrayInputStream bais = new ByteArrayInputStream(publicKey.getEncoded());
        SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(bais).readObject());

        return new SubjectKeyIdentifier(info);
    } catch (IOException e) {
        throw new InternalInconsistencyException("Can't read from a ByteArrayInputStream?", e);
    }
}

From source file:net.link.util.common.KeyUtils.java

License:Open Source License

@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
private static AuthorityKeyIdentifier createAuthorityKeyId(PublicKey publicKey) {

    try {/* w w w  .  j a v  a  2 s  .  c o m*/
        ByteArrayInputStream bais = new ByteArrayInputStream(publicKey.getEncoded());
        SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(bais).readObject());

        return new AuthorityKeyIdentifier(info);
    } catch (IOException e) {
        throw new InternalInconsistencyException("Can't read from a ByteArrayInputStream?", e);
    }
}

From source file:net.link.util.test.pkix.PkiTestUtils.java

License:Open Source License

@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
private static SubjectKeyIdentifier createSubjectKeyId(PublicKey publicKey) throws IOException {

    ByteArrayInputStream bais = new ByteArrayInputStream(publicKey.getEncoded());
    SubjectPublicKeyInfo info = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(bais).readObject());
    return new SubjectKeyIdentifier(info);
}

From source file:net.link.util.test.pkix.PkiTestUtils.java

License:Open Source License

@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
private static AuthorityKeyIdentifier createAuthorityKeyId(PublicKey publicKey) throws IOException {

    ByteArrayInputStream bais = new ByteArrayInputStream(publicKey.getEncoded());
    SubjectPublicKeyInfo info = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(bais).readObject());

    return new AuthorityKeyIdentifier(info);
}

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 ww .j a va 2s . 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;
}